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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a187ac194853f24262347858a788f01c31d2f861
|
7e7fc42484fa77ebcc6ab36bdce75efb6a8b2362
|
/ml02.R
|
f1177e12b0e1bf670aff7e9c4a70bb1f4d0a3082
|
[] |
no_license
|
lee-saint/lab-r
|
80b1c9211c92debd095bc51389527c8f0517af22
|
157658d77276dad6a67535e4eb2a580b72af642a
|
refs/heads/master
| 2020-11-30T12:29:44.763574
| 2019-12-27T08:11:42
| 2019-12-27T08:11:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,113
|
r
|
ml02.R
|
# k-NN μκ³ λ¦¬μ¦μ μ΄μ©ν Iris νμ’
λΆλ₯
# csv νμΌμμ λ°μ΄ν°νλ μ μμ±
iris <- read.csv("data/Iris.csv", stringsAsFactors = F)
str(iris)
head(iris)
tail(iris)
# iris νμ’
λΆλ₯μλ κ΄κ³μλ λ³μ(νΉμ§)μΈ Idλ₯Ό μ κ±°
iris <- iris[-1]
str(iris)
# Species 컬λΌμ ν©ν°λ‘ λ§λ€κΈ° - λ μ΄λΈ
iris$Species <- factor(iris$Species,
levels = c("Iris-setosa", "Iris-versicolor", "Iris-virginica"),
labels = c("Setosa", "Versicolor", "Virginica"))
str(iris)
table(iris$Species)
# νμ΅ λ°μ΄ν° μΈνΈ, ν
μ€νΈ λ°μ΄ν° μΈνΈλ₯Ό μ€λΉ
# νμ’
λ³λ‘ ꡬλΆλμ΄ μλ λ°μ΄ν°λ₯Ό λλ€νκ² μμ ν λ°μ΄ν° μΈνΈλ₯Ό λλ μΌ ν¨
v <- c(1:10)
v
# sample(벑ν°): 벑ν°μ μμλ€μ λλ€νκ² λͺ¨λ μΆμΆ
sample(v)
# sample(벑ν°, n): 벑ν°μ μμλ€ μ€μμ nκ°μ μμλ₯Ό λλ€νκ² μΆμΆ
sample(v, 7)
# sample(n): 1 ~ nκΉμ§ nκ°μ μ μλ₯Ό λλ€νκ² μΆμΆ
sample(5)
sample(150)
# nrow(λ°μ΄ν°νλ μ), ncol(λ°μ΄ν°νλ μ): λ°μ΄ν°νλ μμ ν/μ΄μ κ°μ
nrow(iris)
iris_shuffled <- iris[sample(nrow(iris)), ]
head(iris_shuffled)
tail(iris_shuffled)
table(iris_shuffled$Species)
# νμ΅ λ°μ΄ν°
train_set <- iris_shuffled[1:100, -5]
head(train_set)
# νμ΅ λ°μ΄ν° λ μ΄λΈ
train_label <- iris_shuffled[1:100, 5]
head(train_label)
# ν
μ€νΈ λ°μ΄ν°
test_set <- iris_shuffled[101:150, -5]
head(test_set)
# ν
μ€νΈ λ°μ΄ν° λ μ΄λΈ
test_label <- iris_shuffled[101:150, 5]
head(test_label)
# μ΅μ-μ΅λ μ κ·ν ν¨μ μ μ
normalize <- function(x) {
return( (x - min(x)) / ( max(x) - min(x)))
}
train_set <- as.data.frame(lapply(train_set, normalize))
summary(train_set)
test_set <- as.data.frame(lapply(test_set, normalize))
summary(test_set)
# knn ν¨μκ° μλ ν¨ν€μ§
library(class)
# CrossTable ν¨μκ° μλ ν¨ν€μ§
library(gmodels)
search()
# knnμ μ μ©νμ λ μμΈ‘κ°
predict <- knn(train = train_set, test = test_set, cl = train_label, k = 9)
CrossTable(x = test_label, y = predict, prop.chisq = F)
|
e18b9d1b03af7e98f136496f11f0badfade267c0
|
fca1aacc8fbc5b749eb4a4488b5a3702589032eb
|
/R/get_kth_fold.R
|
39709811e92f5fe19b1b51936ba8c3b7d0ff84ab
|
[] |
no_license
|
vegarsti/fhtboost
|
8414ae6b35cf330df8aaf7414849d03ccf10ad5e
|
0f76df551e693063b0a8235a7bebd038f658d87a
|
refs/heads/master
| 2020-03-28T01:19:28.572369
| 2019-12-11T07:54:06
| 2019-12-11T07:54:06
| 147,496,116
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 72
|
r
|
get_kth_fold.R
|
#' @export
get_kth_fold <- function(folds, k) {
return(folds[[k]])
}
|
8f807ac2ef227547f51da3ec6e148df1c85a9ff9
|
a249beeec2598922dc69817a68d5bc7e6b1586ab
|
/tests/testthat.R
|
85cfb48fac1cade938c26f8eabb0a4dc1dc4d4bd
|
[] |
no_license
|
aedobbyn/dobtools
|
9c9b56241c65d37d318923bd546a03ce5963b43f
|
f63664430648e48f6ded8dade3afe55699c025bf
|
refs/heads/master
| 2021-01-19T21:24:33.469420
| 2019-05-03T21:13:28
| 2019-05-03T21:13:28
| 101,250,864
| 2
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 99
|
r
|
testthat.R
|
library(tidyverse)
library(assertthat)
library(testthat)
library(dobtools)
test_check("dobtools")
|
0ccbb07acb96f2f5e3e9bcda3ef2257391ee3bb5
|
130d972b7c45e2f71852fb39840e5b1b099a9dd7
|
/scripts/generate_filelist.R
|
13ef97162a647636bdb6a47e1af0799ece058450
|
[
"MIT"
] |
permissive
|
wheelern/CellProfiler_Pipelines
|
cbca146394f7d02740b474bf9d1ccf27349cca59
|
f7ce9f82d0c3079ecab137073d75ac7c7f1c52c0
|
refs/heads/main
| 2023-07-26T07:19:20.790658
| 2021-09-08T22:06:40
| 2021-09-08T22:06:40
| 373,529,059
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,706
|
r
|
generate_filelist.R
|
library(tidyverse)
# setwd('~/Desktop/')
args = commandArgs(trailingOnly = TRUE)
plate <- args[1]
mask <- args[2]
# plate <- '20210521-p01-KJG_641'
# wd <-'Users/njwheeler/Desktop'
# mask <- 'well_mask.png'
image_dir <- stringr::str_c(getwd(), 'CellProfiler_Pipelines', 'projects', plate, 'raw_images', sep = '/')
input_files <- list.files(path = image_dir, pattern = '.*TIF$')
load_csv <- dplyr::tibble(
Group_Number = 1,
Group_Index = seq(1, length(input_files)),
URL_RawImage = stringr::str_c('file:', getwd(), 'CellProfiler_Pipelines', 'projects', plate, 'raw_images', input_files, sep = '/'),
URL_WellMask = stringr::str_c('file:', getwd(), 'CellProfiler_Pipelines', 'masks', mask, sep = '/'),
PathName_RawImage = stringr::str_remove(URL_RawImage, pattern = "/[^/]*$") %>% str_remove(., 'file:'),
PathName_WellMask = stringr::str_remove(URL_WellMask, mask) %>% str_remove(., 'file:') %>% str_remove(., '/$'),
FileName_RawImage = input_files,
FileName_WellMask = mask,
Series_RawImage = 0,
Series_WellMask = 0,
Frame_RawImage = 0,
Frame_WellMask = 0,
Channel_RawImage = -1,
Channel_WellMask = -1,
Metadata_Date = stringr::str_extract(plate, '202[0-9]{5}'),
Metadata_FileLocation = URL_RawImage,
Metadata_Frame = 0,
Metadata_Plate = stringr::str_extract(plate, '-p[0-9]*-') %>% stringr::str_remove_all(., '-'),
Metadata_Researcher = stringr::str_extract(plate, '-[A-Z]{2,3}') %>% stringr::str_remove_all(., '-'),
Metadata_Series = 0,
Metadata_Well = stringr::str_extract(FileName_RawImage, '[A-H][0,1]{1}[0-9]{1}')
)
readr::write_csv(load_csv, file = stringr::str_c('/', getwd(), '/CellProfiler_Pipelines/', 'metadata/', 'image_paths.csv', sep = ''))
|
c396f31b705fa261984c9358f05f2af4acea7b6f
|
d32427ca155a12ea40abc6ad8aa38d00a1d2a44b
|
/man/segmentationHclust.Rd
|
1758459250d1c1f9c6f0538d9a537e4581b29aba
|
[
"Artistic-2.0"
] |
permissive
|
lima1/PureCN
|
4d60d1ff266294c97748c4ef3257550da061d799
|
df67480ec5fd05b14c7676ea1190af201141966b
|
refs/heads/devel
| 2023-07-19T20:56:20.077565
| 2023-07-18T15:29:48
| 2023-07-18T15:29:48
| 99,367,098
| 137
| 34
|
Artistic-2.0
| 2023-07-05T16:56:36
| 2017-08-04T17:49:35
|
R
|
UTF-8
|
R
| false
| true
| 2,712
|
rd
|
segmentationHclust.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/segmentationHclust.R
\name{segmentationHclust}
\alias{segmentationHclust}
\title{Minimal segmentation function}
\usage{
segmentationHclust(
seg,
vcf = NULL,
tumor.id.in.vcf = 1,
normal.id.in.vcf = NULL,
min.logr.sdev = 0.15,
prune.hclust.h = NULL,
prune.hclust.method = "ward.D",
chr.hash = NULL,
...
)
}
\arguments{
\item{seg}{If segmentation was provided by the user, this data structure
will contain this segmentation. Useful for minimal segmentation functions.
Otherwise PureCN will re-segment the data. This segmentation function
ignores this user provided segmentation.}
\item{vcf}{Optional \code{CollapsedVCF} object with germline allelic ratios.}
\item{tumor.id.in.vcf}{Id of tumor in case multiple samples are stored in
VCF.}
\item{normal.id.in.vcf}{Id of normal in in VCF. Currently not used.}
\item{min.logr.sdev}{Minimum log-ratio standard deviation used in the
model. Useful to make fitting more robust to outliers in very clean
data (currently not used in this segmentation function).}
\item{prune.hclust.h}{Height in the \code{hclust} pruning step. Increasing
this value will merge segments more aggressively. If NULL, try to find a
sensible default.}
\item{prune.hclust.method}{Cluster method used in the \code{hclust} pruning
step. See documentation for the \code{hclust} function.}
\item{chr.hash}{Mapping of non-numerical chromsome names to numerical names
(e.g. chr1 to 1, chr2 to 2, etc.). If \code{NULL}, assume chromsomes are
properly ordered.}
\item{...}{Currently unused arguments provided to other segmentation
functions.}
}
\value{
\code{data.frame} containing the segmentation.
}
\description{
A minimal segmentation function useful when segmentation was performed by
third-pary tools. When a \code{CollapsedVCF} with germline SNPs is provided,
it will cluster segments using \code{hclust}. Otherwise it will use the
segmentation as provided.
This function is called via the
\code{fun.segmentation} argument of \code{\link{runAbsoluteCN}}. The
arguments are passed via \code{args.segmentation}.
}
\examples{
vcf.file <- system.file("extdata", "example.vcf.gz",
package="PureCN")
interval.file <- system.file("extdata", "example_intervals_tiny.txt",
package="PureCN")
seg.file <- system.file('extdata', 'example_seg.txt',
package = 'PureCN')
res <- runAbsoluteCN(seg.file = seg.file,
fun.segmentation = segmentationHclust,
max.ploidy = 4, vcf.file = vcf.file,
test.purity = seq(0.3, 0.7, by = 0.05),
max.candidate.solutions = 1,
genome = 'hg19', interval.file = interval.file)
}
\seealso{
\code{\link{runAbsoluteCN}}
}
\author{
Markus Riester
}
|
22ece906adc21887d99c60642def2b40bb2a7ff4
|
1ade2742a79ba69f8a63658aa3c17ac914ff14e2
|
/Misc Code/misc_spatial_sims.R
|
7b539181e8427da32f6ece5caabe3659a3d9f653
|
[] |
no_license
|
lou0806/Louis_Ye_Honours_Project_Coding_R
|
05cdf4d8ced05c5cc73b39111eb88ef3572649a4
|
0b6f982ef1b99b8fe0690e897477d4bb0b1d1a75
|
refs/heads/master
| 2023-01-24T19:47:12.298115
| 2020-11-19T11:09:29
| 2020-11-19T11:09:29
| 256,194,821
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,864
|
r
|
misc_spatial_sims.R
|
output <- SSB.mod(y = matrix(y[,1],ncol = 1), z = z, x = x, n.terms = n, DOF=1,mx.sige=1,mx.sigs=1)
points(clusters_dist, type = 'p')
plot(z[,1],z[,2],col=output$membership, type = 'p', pch = 19)
points(clusters_dist, type = 'p')
#unique(output$membership)
#points(t(output$knot[,unique(output$membership)]), type = 'p', pch =5)
output <- SSB.mod(y = matrix(y[,3],ncol = 1), z = z, x = x, n.terms = 20, DOF=1,mx.sige=2,mx.sigs=2)
##Notes 15/10/2020:
## n.terms heavily influences clustering probabilities (away from first cluster)
# Idea: record the changes in allocation
##Notes 16/10/2020:
## Look at predictive differences with the Gelfand code (gsdp)
#Clear 2-cluster setup
#z <- rbind(cbind(rnorm(100,0,0.5), rnorm(100,0,0.5)), cbind(rnorm(150,5,0.5), rnorm(150,5,0.5)))
#z <- rbind(z, cbind(runif(100,min(z),max(z)), runif(100,min(z),max(z))))
for(t in 1:nt){
y.vec <- matrix(y[,t],ncol = 1)
output <- SSB.mod(y = y.vec, z = z)
g.mat[,t] <- output$membership
print(t)
}
for (t in 1:nt) {
temp <- 1
for (i in unique(g.mat[,t])) {
g.mat[,t][g.mat[,t] == i] <- temp
temp <- temp + 1
}
g.mat[,t]
}
#y.ssb <- matrix(unlist(y))
#x.ssb <- matrix(c(rep(x[,1],ncol(y)),rep(x[,2],ncol(y))), ncol = 2)
#
#output <- SSB.mod(y = y.ssb, z = x.ssb)
##TODO: Vary alpha, not just the hyperparameters
y[1,]
loc.1 <- gsdp(y,z,mx.siga=1, mx.sigb = .25,mx.taua = 1,mx.taub = .25,a.alpha = 3,b.alpha = 1, loc = 1 , mx.bphi = .1)
loc.2 <- gsdp(y,x,mx.siga=1, mx.sigb = .25,mx.taua = 1,mx.taub = .25,a.alpha = 10,b.alpha = 1, loc = 2, mx.bphi = .5)
loc.3 <- gsdp(y,x,mx.siga=1, mx.sigb = .25,mx.taua = 1,mx.taub = .25,a.alpha = 10,b.alpha = 1, loc = 3)
gsdp.cluster(y,x,mx.siga=1, mx.sigb = .25,mx.taua = 1,mx.taub = .25,a.alpha = 3,b.alpha = 1, mx.bphi = .1)
SpatialClust(z=y.spatClust,n.all = rep(3,ncol(y)),x=x,spatial=T,genetic=T)
|
14d6b4a6745fcef03e59118277688f047eb9dd4a
|
36975485c360081e1a1cd3bee16df40940221266
|
/Matrix.Differences.LargerThanOneAndAHalfSD.R
|
d575eed6f3b21c1083b8b40f64836def54d114c2
|
[] |
no_license
|
darokun/Others
|
7005291c7f538cedae626b1a2c2c26d246a843e5
|
2c85abb5a41ab7512758f3dff67300a012ac774e
|
refs/heads/master
| 2021-01-10T12:52:09.342865
| 2017-01-11T14:50:33
| 2017-01-11T14:50:33
| 45,177,486
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,062
|
r
|
Matrix.Differences.LargerThanOneAndAHalfSD.R
|
### Script for Miryam
# you may skip these two steps
# generating 102 (6*17) random values of mean 5 and sd 1.5
set.seed(1234)
x <- rnorm(102, 5, 1.5)
# building a matrix from x, with 6 rows and 17 columns
data <- matrix(x,nrow=6,ncol=17)
# you may start here
# sorting out the first column
sort(data[,1])
# create a vector to store differences
difference <- NULL
# calculating the differences: abs(x1-x2), and so on, until abs(x5-x6)
for(i in 1:(length(data[,1])-1)) {
difference[i] <- abs(data[,1][i] - data[,1][i+1])
}
# create a boolean vector to store whether or not the differences are >=1.5 sd of this first column or not
sd_1.5 <- NULL
for(i in 1:length(difference)) {
if(difference[i] >= sd(data[,1])*1.5) {
sd_1.5[i] <- TRUE
} else {
sd_1.5[i] <- FALSE
}
}
x <- c(0,1)
par(xpd=)
x <- sample(x,85, replace=TRUE)
x <- as.logical(x)
data <- matrix(x, nrow=5, ncol=17)
data
image(data, col=c("coral", "dark turquoise"), main="title")
par(xpd=TRUE)
legend(1,1.25, legend=c("1", "2"), col=c("coral", "dark turquoise"), pch=20)
|
34476bf4b050f7752994ff991553dd496bb2047c
|
c0a14859f57647064f89449005293d04777ef30f
|
/older_scripts/Oct18.R
|
956f76f22108204d4ff94df6fe18e19570cf7895
|
[] |
no_license
|
efeichtinger/LittleBlueDinos
|
d66905987f13cd9a7299365a1ba44ff970b90826
|
c993c31c2e1ed54f5746aa95472d3ca6b7c64a2f
|
refs/heads/master
| 2020-04-06T22:03:47.645177
| 2017-07-27T19:46:07
| 2017-07-27T19:46:07
| 50,062,977
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 6,556
|
r
|
Oct18.R
|
### 1981 to 2015
## Started 10-18-2016
library(survival)
library(ggplot2)
library(car)
library(coxme)
library(kinship2)
library(plyr)
library(corrplot)
#1981-2015
aprilD <- read.csv("April_Census_Dates.csv")
aprilD$CensusDate <- as.Date(aprilD$CensusDate, format = "%m/%d/%Y")
jays <- read.csv("Erin_HY_1981.csv")
jays$NestYear <- as.factor(jays$NestYear)
#Convert dates to date format
jays$FldgDate <- as.Date(jays$FldgDate, format = "%m/%d/%Y")
jays$LastObsDate <- as.Date(jays$LastObsDate, format = "%m/%d/%Y")
jays$HatchDate <- as.Date(jays$HatchDate, format = "%m/%d/%Y")
jays$MeasDate <- as.Date(jays$MeasDate, format = "%m/%d/%Y")
jays["Days"] <- jays$LastObsDate - jays$FldgDate
jays["Years"] <- round(jays$Days/365.25, digits = 2)
str(jays)
#Add censorship column, 1 if dead before 1 yr, 0 if yr > 1 or 4/12/12016
jays["Censor"] <- 1
jays$Censor[which(jays$Years >= 1)]<-0
yrlg.df <- subset(jays, jays$Years > 0 & jays$Days > 0)
yrlg.df$Censor[which(yrlg.df$LastObsDate == "2016-04-12")] <- 0
#Jay ID not unique but the band number is
#yrlg.df[,2] <- NULL
str(yrlg.df)
yrlg.df["Day11"] <- yrlg.df$MeasDate - yrlg.df$HatchDate
yrlg.df <- subset(yrlg.df, yrlg.df$Day11 <= 13)
yrlg.df[,8] <- NULL
yrlg.df[,15] <- NULL
colnames(yrlg.df)[7] <- "Mass"
group.size <- read.csv("groupsize1981.csv")
#String function and regular expressions to get a "TerrYr" variable to match
#Remember this is just for 1999 to 2015, the territory data goes to 1981
new.col <- gsub(".$","",yrlg.df$NatalNest)
colTY <- as.vector(new.col)
colTY <- cbind(colTY)
yrlg.df["TerrYr"] <- colTY
yrlg.df <- merge(yrlg.df, group.size, by="TerrYr")
## Add in territory info
#Scrub data
dom.veg <- read.csv("dom_veg.csv")
dom.veg <- subset(dom.veg, InABS == TRUE)
#Subset data to only keep scrub veg types
#create object to store charc strings corresponding to scrub types
keep <- c("RSh", "SFi", "SFl", "SFx", "SSo", "SSr")
#creat new data frame with only the scrub types in "keep"
vegdf <- dom.veg[dom.veg$Dom.Veg %in% keep, ]
scrub.terr <- ddply(vegdf, .(Terryr), summarise,
Count.Dom.Veg=sum(Count.Dom.Veg))
colnames(scrub.terr) <- c("TerrYr", "Scrub")
no.scr <- subset(dom.veg, !(Terryr %in% scrub.terr$TerrYr))
no.scr["scrb.count"] <- 0
#Keep only terryr and scrb.count
vars <- c("Terryr","scrb.count")
no.scr <- no.scr[vars]
#remove duplicate rows
no.scr <- no.scr[!duplicated(no.scr),]
colnames(no.scr)[1] <- "TerrYr"
colnames(scrub.terr)[2] <- "scrb.count"
#This includes terryears from 1981 to 2015, have to add year
#String operations?
scr.ct <- rbind(scrub.terr, no.scr)
#Time since fire data
tsf <- read.csv("tsf_terr.csv")
tsf <- subset(tsf, InABS == TRUE)
#TSF data
#Create object for the numbers, same logic as with veg data
keep2 <- c(1,2,3,4,5,6,7,8,9)
firedf <- tsf[tsf$TSF_years %in% keep2, ]
tsf.terr <- ddply(firedf, .(TERRYR), summarise, CellCount=sum(CellCount))
colnames(tsf.terr) <- c("TerrYr", "FireCount")
no.tsf1 <- subset(tsf, !(TERRYR %in% tsf.terr$TerrYr))
no.tsf1["tsf.count"] <- 0
no.tsf1 <- no.tsf1[,c(1,8)]
colnames(no.tsf1)[1] <- "TerrYr"
colnames(tsf.terr)[2] <- "tsf.count"
#All TerrYrs including counts of 0
tsf.ct <- rbind(tsf.terr,no.tsf1)
##territory size
terr <- read.csv("terr_size.csv")
terr <- subset(terr, InABS == TRUE)
#Keep only terryr and scrb.count
vars1 <- c("TERRYR","Count")
terr <- terr[vars1]
colnames(terr) <- c("TerrYr", "TerrSize")
#territory size
veg.size <- merge(scr.ct,terr)
#info on territory quality, cell count of scrub, size, tsf in 1-9 window
terr.info <- merge(veg.size, tsf.ct)
#remove duplicate rows
terr.info <- terr.info[!duplicated(terr.info),]
yrlg.df <- merge(yrlg.df, terr.info, by="TerrYr")
###Add code to see who drops out when the territory info is added to check
#for bias by year (i.e. more drop out as prop of total in some years)
#Who is not in the new df?
## Rearrange columns
colnames(yrlg.df)[16] <- "GroupSize"
colnames(yrlg.df)[18] <- "OakScrub"
colnames(yrlg.df)[20] <- "TSF"
yrlg.df["stdscr"] <- scale(yrlg.df$OakScrub, center = FALSE, scale = TRUE)
yrlg.df["stdtsf"] <- scale(yrlg.df$TSF, center = FALSE, scale = TRUE)
yrlg.df["stdsize"] <- scale(yrlg.df$TerrSize, center= FALSE, scale = TRUE)
# Data frame of covariates for correlation matirx
covars.stad <- yrlg.df[,c(8,11,12,16,17,21,22,23)]
covars.no <- yrlg.df[,c(8,11,12,16,17,18,19,20)]
corrs <- cor(covars.stad, use="complete.obs")
corrplot(corrs, method="pie", type="lower")
corrs2 <- cor(covars.no, use="complete.obs")
corrplot(corrs2, method="pie", type="lower")
#Change to numeric for survival object
yrlg.df$FldgDate <- as.numeric(yrlg.df$FldgDate)
yrlg.df$LastObsDate <- as.numeric(yrlg.df$LastObsDate)
yrlg.df$Years <- as.numeric(yrlg.df$Years)
yrlg.df$Days <- as.numeric(yrlg.df$Days)
yrlg.ob <- Surv(yrlg.df$Years, yrlg.df$Censor, type = c('right'))
my.fit <- survfit(yrlg.ob~1, conf.type = "log-log")
plot.fit <- plot(my.fit, xlab = "Time (years)", conf.int=TRUE,
log = "y", ylim = c(0.4, 1),xlim=c(0,1), ylab = "Cumulative Survival",
main = "Fledge to 1Yr - 1981 to 2015")
fit.yr <- survfit(yrlg.ob ~ yrlg.df$NestYear)
plot.yr <- plot(fit.yr,xlab = "Time (years)",
log = "y", ylim = c(0.1, 1),xlim=c(0,1), ylab = "Cumulative Survival",
main = "Curves for each year 1981 - 2015")
fit.yr
### Make a life table
## Models
#Cohort year
cox1 <- coxph(yrlg.ob ~ NestYear, data= yrlg.df)
cox1
anova(cox1)
#Day 11 Mass
cox.wt <- coxph(yrlg.ob ~ Mass, data = yrlg.df)
#Cohort and Mass
cox1b <- coxph(yrlg.ob ~ Mass + NestYear, data=yrlg.df)
anova(cox1b)
#Mixed effects with year as random effect
cox2 <- coxme(yrlg.ob ~ Mass + (1|NestYear), data= yrlg.df)
cox2
anova(cox2)
#Mixed effects with nestID as random effect
cox3 <- coxme(yrlg.ob ~ Mass + (1|NatalNest), data =yrlg.df)
cox3
anova(cox3)
#Interestingly, there is a lot of variation from year to year, but the effect
#of cohort year has a relatively small variance
#So I suppose there could be a lot of variation in p during the first year but
#the main source of variation may not be the stochastic (and other) effects
#represented by using cohort year identity
#High variance for natal nest ID as random term
#Checking other social factors
coxgrp <- coxph(yrlg.ob ~ GroupSize, data=yrlg.df)
coxgrp
anova(coxgrp)
coxgm <- coxph(yrlg.ob ~ Mass + GroupSize, data=yrlg.df)
coxgm
anova(coxgm)
coxterr <- coxph(yrlg.ob ~ OakScrub + TerrSize + GroupSize + GroupSize:TerrSize,
data = yrlg.df)
coxterr
anova(coxterr)
|
00cac62f2553a3c24aafe673c6fbf2b7a5aeba55
|
c85ab5fc908a443eac6e96f6818857842346a6e7
|
/code/sandbox/04a_geo_date_data.R
|
bfaedbed89f89b9d1e1beea6adaf887f332873dc
|
[] |
no_license
|
erflynn/sl_label
|
34d4df22f651a44317a9fb987970dfed6e1731a7
|
6e81605f4c336e0c1baa07abc168c72c9a9eaceb
|
refs/heads/master
| 2023-04-01T01:57:48.862307
| 2021-03-30T18:27:36
| 2021-03-30T18:27:36
| 244,698,848
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,344
|
r
|
04a_geo_date_data.R
|
# 02a_geo_date_data.R
# E Flynn
# 07/20/2020
#
# Get data for microarray samples. Some of this is in refine-bio studies but
# it has high missingness --> we will query GEOmetadb and ArrayExpress directly.
#
# END GOAL:
# have these tables so we can make a figure:
# 1. sample | organism | data_type | sex | studies | sample_date
# 2. study | study_date
# -- UPDATE: DEPRECATED! we don't need to query GEOmetadb for this info! ignore. -- #
require('tidyverse')
require('GEOmetadb')
comb_metadata <- read_csv("data/01_metadata/combined_human_mouse_meta.csv")
# 1. get GEO studies
# study-level
list_studies <- (comb_metadata %>%
filter(data_type=="microarray") %>%
select(study_acc) %>%
unique() %>%
separate_rows(study_acc, sep=";") %>%
unique())$study_acc
table(str_detect(list_studies, "GSE"))
# FALSE TRUE
# 260 19963
non_gse_studies <- list_studies[!str_detect(list_studies, "GSE")]
non_gse_studies %>% as_tibble() %>% rename(study=value) %>% write_csv("data/dates/non_gse.csv")
con <- dbConnect(SQLite(), "../labeling/GEOmetadb.sqlite") # sept 23, 2019
list_studies_str <- paste(list_studies, collapse="\',\'")
dbListTables(con)
study_res <- dbGetQuery(con, sprintf("SELECT gse.gse, submission_date FROM gse WHERE gse.gse IN ('%s');", list_studies_str))
stopifnot(nrow(study_res)==length(unique(study_res$gse)))
stopifnot(length(list_studies[str_detect(list_studies, "GSE")])==nrow(study_res))
# no missing dates! woot
any(is.na(study_res$submission_date))
any(study_res$submission_date=="")
# sample-level
dbListFields(con, "gsm")
list_samples <- (comb_metadata %>%
filter(data_type=="microarray"))$sample_acc
list_samples_str <- paste(list_samples, collapse="\',\'")
sample_res <- dbGetQuery(con, sprintf("SELECT gsm.gsm, submission_date FROM gsm WHERE gsm.gsm IN ('%s');",
list_samples_str))
any(is.na(sample_res$submission_date))
any(sample_res$submission_date=="")
length(list_samples)
nrow(sample_res)
table(str_detect(list_samples, "GSM")) #5k samples are non-GSM
length(list_samples[str_detect(list_samples, "GSM")])
dbDisconnect(con)
# missing 10 GSM samples from the list of dates, not bad
# SAVE THIS!
sample_res %>% write_csv("data/dates/geo_sample_dates.csv")
study_res %>% write_csv("data/dates/geo_study_dates.csv")
|
9624c2be1d4ad7bf0de6750a360fa819b8fa725f
|
8b306c29c6fb2355e624dad4775c62978b571287
|
/man/alphaMcmcPost-methods.Rd
|
d616f774676a505d78db43abc65124fc52807272
|
[] |
no_license
|
sba1/mgsa-bioc
|
079552a6a1605d125185fc34823ca9f1bc68a87d
|
e33a2ebb0498b33bba34ba79ca7565a29f622577
|
refs/heads/master
| 2021-06-08T13:31:23.187732
| 2021-05-16T16:29:59
| 2021-05-16T16:29:59
| 14,407,304
| 4
| 5
| null | 2017-04-03T18:45:04
| 2013-11-14T21:18:32
|
R
|
UTF-8
|
R
| false
| false
| 584
|
rd
|
alphaMcmcPost-methods.Rd
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/MgsaResults-class.R
\docType{methods}
\name{alphaMcmcPost}
\alias{alphaMcmcPost}
\alias{alphaMcmcPost,MgsaMcmcResults-method}
\title{posterior estimates of the parameter alpha for each MCMC run}
\usage{
alphaMcmcPost(x)
\S4method{alphaMcmcPost}{MgsaMcmcResults}(x)
}
\arguments{
\item{x}{a \code{\linkS4class{MgsaMcmcResults}}.}
}
\value{
\code{matrix}: Posterior estimates of the parameter alpha for each MCMC run.
}
\description{
Posterior estimates of the parameter alpha for each MCMC run.
}
|
7c2fc7ef673391845fc1d13fafb7474fe6fffaaf
|
0500ba15e741ce1c84bfd397f0f3b43af8cb5ffb
|
/cran/paws.management/man/appregistry_get_application.Rd
|
772ef6b48a53abe7447c62fbc0b91d64331e9b25
|
[
"Apache-2.0"
] |
permissive
|
paws-r/paws
|
196d42a2b9aca0e551a51ea5e6f34daca739591b
|
a689da2aee079391e100060524f6b973130f4e40
|
refs/heads/main
| 2023-08-18T00:33:48.538539
| 2023-08-09T09:31:24
| 2023-08-09T09:31:24
| 154,419,943
| 293
| 45
|
NOASSERTION
| 2023-09-14T15:31:32
| 2018-10-24T01:28:47
|
R
|
UTF-8
|
R
| false
| true
| 908
|
rd
|
appregistry_get_application.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/appregistry_operations.R
\name{appregistry_get_application}
\alias{appregistry_get_application}
\title{Retrieves metadata information about one of your applications}
\usage{
appregistry_get_application(application)
}
\arguments{
\item{application}{[required] The name, ID, or ARN of the application.}
}
\description{
Retrieves metadata information about one of your applications. The application can be specified by its ARN, ID, or name (which is unique within one account in one region at a given point in time). Specify by ARN or ID in automated workflows if you want to make sure that the exact same application is returned or a \code{ResourceNotFoundException} is thrown, avoiding the ABA addressing problem.
See \url{https://www.paws-r-sdk.com/docs/appregistry_get_application/} for full documentation.
}
\keyword{internal}
|
cbd28a372389151b10e4f398b0d70176346c2559
|
26d23229dc13b530c86ebc58abb20e3507153a1a
|
/runBeta.R
|
63091f01318c919c182269cd4a1defc17ad8eab8
|
[] |
no_license
|
hajaramini/KIAT_F1
|
8053a8d0b01be4ed70e49340ada4f77c862243d9
|
b94fa1e649ad99a6ab3b89965eb38b1b0e97fcb7
|
refs/heads/master
| 2021-04-28T08:36:57.748743
| 2018-02-20T19:01:22
| 2018-02-20T19:01:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,073
|
r
|
runBeta.R
|
library(MBASED)
library(tidyverse)
TwoSample <- function(annotatedData, mySNVs, genotype1, genotype2, numSim = 0){
RO1 <- paste(genotype1, "RO", sep = "_")
AO1 <- paste(genotype1, "AO", sep = "_")
RO2 <- paste(genotype2, "RO", sep = "_")
AO2 <- paste(genotype2, "AO", sep = "_")
RAB1 <- paste(genotype1, "refBias", sep = "_")
RAB2 <- paste(genotype2, "refBias", sep = "_")
DISP1 <- paste(genotype1, "disp", sep = "_")
DISP2 <- paste(genotype2, "disp", sep = "_")
mySample <- SummarizedExperiment(
assays = list(lociAllele1Counts = matrix(c(annotatedData[, RO1], annotatedData[, RO2]), ncol = 2,
dimnames = list(names(mySNVs), c(genotype1, genotype2))),
lociAllele2Counts = matrix(c(annotatedData[, AO1], annotatedData[, AO2]), ncol = 2,
dimnames = list(names(mySNVs), c(genotype1, genotype2))),
lociAllele1CountsNoASEProbs = matrix(c(annotatedData[, RAB1], annotatedData[, RAB2]),
ncol=2, dimnames=list(names(mySNVs), c(genotype1, genotype2))),
lociCountsDispersions = matrix(c(annotatedData[, DISP1], annotatedData[, DISP2]),
ncol=2, dimnames=list(names(mySNVs), c(genotype1, genotype2)))
),
rowRanges=mySNVs)
MBASEDOutput <- runMBASED(
ASESummarizedExperiment = mySample,
isPhased = TRUE,
numSim = numSim
#BPPARAM = MulticoreParam(workers = 9) # Default: No paralellization
)
return(MBASEDOutput)
}
runOnSubset <- function(annotatedData, index){
annotatedData.trimmed <- annotatedData[index, ]
mySNVs.trimmed <- GRanges(
seqnames = annotatedData.trimmed$CHROM,
ranges = IRanges(start = annotatedData.trimmed$POS, width = 1),
aseID = as.vector(annotatedData.trimmed$GeneID),
allele1 = annotatedData.trimmed$REF,
allele2 = annotatedData.trimmed$ALT)
return(TwoSample(annotatedData.trimmed, mySNVs.trimmed, "F1_414", "F1_415", numSim = 1000000))
}
load("phasedData.Rdata")
BMBASED.F1.414.vs.F1.415A <- runOnSubset(phasedData, 1:4997)
save(BMBASED.F1.414.vs.F1.415A, file = "BMBASED.F1.414.vs.F1.415A.Rdata")
BMBASED.F1.414.vs.F1.415B1 <- runOnSubset(phasedData, 4998:7501)
save(BMBASED.F1.414.vs.F1.415B1, file = "BMBASED.F1.414.vs.F1.415B1.Rdata")
BMBASED.F1.414.vs.F1.415B2 <- runOnSubset(phasedData, 7502:10002)
save(BMBASED.F1.414.vs.F1.415B2, file = "BMBASED.F1.414.vs.F1.415B2.Rdata")
BMBASED.F1.414.vs.F1.415C1 <- runOnSubset(phasedData, 10003:12501)
save(BMBASED.F1.414.vs.F1.415C1, file = "BMBASED.F1.414.vs.F1.415C1.Rdata")
BMBASED.F1.414.vs.F1.415C2 <- runOnSubset(phasedData, 12502:15006)
save(BMBASED.F1.414.vs.F1.415C2, file = "BMBASED.F1.414.vs.F1.415C2.Rdata")
print("Working on E1")
BMBASED.F1.414.vs.F1.415E1 <- runOnSubset(phasedData, 20005:22507)
save(BMBASED.F1.414.vs.F1.415E1, file = "BMBASED.F1.414.vs.F1.415E1.Rdata")
print("working on F2")
BMBASED.F1.414.vs.F1.415F2 <- runOnSubset(phasedData, 27505:30004)
save(BMBASED.F1.414.vs.F1.415F2, file = "BMBASED.F1.414.vs.F1.415F2.Rdata")
print("working on H")
BMBASED.F1.414.vs.F1.415H <- runOnSubset(phasedData, 35004:37502)
save(BMBASED.F1.414.vs.F1.415H, file = "BMBASED.F1.414.vs.F1.415H.Rdata")
print("working on I")
BMBASED.F1.414.vs.F1.415I <- runOnSubset(phasedData, 37503:41404)
save(BMBASED.F1.414.vs.F1.415I, file = "BMBASED.F1.414.vs.F1.415I.Rdata")
print("working on E2")
BMBASED.F1.414.vs.F1.415E2 <- runOnSubset(phasedData, 22508:24002)
save(BMBASED.F1.414.vs.F1.415E2, file = "BMBASED.F1.414.vs.F1.415E2.Rdata")
print("working on E3")
BMBASED.F1.414.vs.F1.415E3 <- runOnSubset(phasedData, 24003:25001)
save(BMBASED.F1.414.vs.F1.415E3, file = "BMBASED.F1.414.vs.F1.415E3.Rdata")
print("working on F1")
BMBASED.F1.414.vs.F1.415F1 <- runOnSubset(phasedData, 25002:27504)
save(BMBASED.F1.414.vs.F1.415F1, file = "BMBASED.F1.414.vs.F1.415F1.Rdata")
|
b93dc2a80fd12155ad8d9b8626051c2c9d433314
|
1431062791ec634e6e2220743345ed0aa356e852
|
/tests/testthat/test-sklearn.R
|
9eed41b176fb2c9b1c43815b4a66699adca5a892
|
[
"MIT"
] |
permissive
|
news-r/gensimr
|
4da573e4e4c79b64ff71c0a0e6856626ac27e93e
|
8e7f4408501e954c50499c2dd4dcf6bbf415af51
|
refs/heads/master
| 2021-06-27T12:27:55.009018
| 2021-01-07T13:54:34
| 2021-01-07T13:54:34
| 198,456,476
| 36
| 5
|
NOASSERTION
| 2019-07-29T08:02:26
| 2019-07-23T15:18:46
|
R
|
UTF-8
|
R
| false
| false
| 3,534
|
r
|
test-sklearn.R
|
test_that("sklearn works", {
# set seed
seed <- 42L
set.seed(seed)
reticulate::py_set_seed(seed)
# preprocess
data(corpus, package = "gensimr")
docs <- prepare_documents(corpus)
dictionary <- corpora_dictionary(docs)
corpus_bow <- doc2bow(dictionary, docs)
corpus_mm <- serialize_mmcorpus(corpus_bow, auto_delete = FALSE)
tfidf <- model_tfidf(corpus_mm)
corpus_transformed <- wrap(tfidf, corpus_bow)
data("authors", package = "gensimr")
# author topic
auth2doc <- auth2doc(authors, name, document)
expect_type(auth2doc, "environment")
temp <- tempfile("serialized")
atmodel <- sklearn_at(
id2word = dictionary,
author2doc = auth2doc,
num_topics = 2L,
passes = 100L,
serialized = TRUE,
serialization_path = temp
)
unlink(temp, recursive = TRUE)
expect_type(atmodel, "environment")
fit <- atmodel$fit(corpus_bow)$transform("jack") %>%
reticulate::py_to_r()
expect_length(fit, 2)
# doc2vec
d2v <- sklearn_doc2vec(min_count = 1, size = 5)
expect_type(d2v, "environment")
vectors <- d2v$fit_transform(docs) %>%
reticulate::py_to_r()
expect_length(vectors, 45) #Β size = 5 * 9 docs
# hdp
hdp <- sklearn_hdp(id2word = dictionary)
expect_type(d2v, "environment")
vectors <- hdp$fit_transform(corpus_bow) %>%
reticulate::py_to_r()
expect_length(vectors, 81) # 9 docs
# lda
lda <- sklearn_lda(
num_topics = 2L,
id2word = dictionary,
iterations = 20L,
random_state = 1L
)
expect_type(lda, "environment")
trans <- lda$fit_transform(corpus_bow) %>%
reticulate::py_to_r()
expect_length(trans, 18) # 9 docs * 2 topics
#Β lsi
lsi <- sklearn_lsi(id2word = dictionary, num_topics = 15L)
expect_type(lsi, "environment")
# L2 reg classifier
clf <- sklearn_logistic(penalty = "l2", C = 0.1, solver = "lbfgs")
# sklearn pipepline
pipe <- sklearn_pipeline(lsi, clf)
# Create some random binary labels for our documents.
labels <- sample(c(0L, 1L), 9, replace = TRUE)
# How well does our pipeline perform on the training set?
fit <- pipe$fit(corpus_bow, labels)$score(corpus_bow, labels) %>%
reticulate::py_to_r()
expect_gt(fit, .7)
# random projections
rp_model <- sklearn_rp(id2word = dictionary)
expect_type(rp_model, "environment")
rp_fit <- rp_model$fit(corpus_bow)
# Use the trained model to transform a document.
result <- rp_fit$transform(corpus_bow) %>%
reticulate::py_to_r()
expect_length(result, 2700)
#Β phrase detection
corpus_split <- corpus %>%
purrr::map(strsplit, " ") %>%
purrr::map(function(x){
sentence <- x[[1]]
tolower(sentence)
})
# Create the model. Make sure no term is ignored and combinations seen 2+ times are captured.
pt_model <- sklearn_pt(min_count = 1, threshold = 2)
# Use sklearn fit_transform to see the transformation.
pt_trans <- pt_model$fit_transform(corpus_split)
# Since graph and minors were seen together 2+ times they are considered a phrase.
expect_true(c("graph_minors") %in% reticulate::py_to_r(pt_trans)[[9]])
#Β word id mapping
skbow_model <- sklearn_doc2bow()
# fit
corpus_skbow <- skbow_model$fit_transform(corpus) %>%
reticulate::py_to_r()
expect_length(corpus_skbow, 9)
# tfidf
tfidf_model <- sklearn_tfidf(dictionary = dictionary)
tfidf_w_sklearn <- tfidf_model$fit_transform(corpus_bow)
# same as with gensim
expect_true(corpus_transformed[[1]] == tfidf_w_sklearn[[1]])
# cleanup
delete_mmcorpus(corpus_mm)
})
|
61befe770924a87201a82ce32707380878cfe9bb
|
81d2188a3ac862d66c7a4110a8b0f3ee58680bfe
|
/update document/RShiny-amr/ui.R
|
5d87054db545b9f3993cc2290b4b6a66e570a846
|
[
"Apache-2.0"
] |
permissive
|
YaraSabry96/NTI-Project-
|
f46a53ed96984bee0a65e4f5bdbfc3c296a0ae91
|
e174b377a757c6ae7c1a3ebd2054873ec2e54507
|
refs/heads/master
| 2020-04-09T11:34:12.560957
| 2018-12-04T07:34:04
| 2018-12-04T07:34:04
| 160,315,143
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 7,648
|
r
|
ui.R
|
library(shiny)
library(shinydashboard)
shinyUI(
dashboardPage(
dashboardHeader(),
dashboardSidebar(
sidebarMenu(
menuItem("upload", tabName = "upload", icon = icon("dashboard")),
menuItem("Analysis", tabName = "analysis", icon = icon("dashboard")),
menuItem("Visualization ACF & PACF ", tabName = "vis_acf", icon = icon("dashboard")),
menuItem("Comparison", tabName = "comp", icon = icon("dashboard")),
menuItem("Forcasted Matched Actual", tabName = "FMA", icon = icon("dashboard"))
)
),
#-----------------------------------------
dashboardBody(
tabItems(
#-------------------first page-------------------------
# First tab content
tabItem(
tabName = "upload",
fluidRow(
box(
width = 12,
title = "The Dataset Come From Yahoo Website With The Latest Version The previous Day",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
actionButton("upload data","Download",class="btn btn-info")
),
box(
width = 12,
title = "The Data as Shown Below (This is a Sample of The Data )",
status= "success",
solidHaider = TRUE,
collapsible = TRUE,
actionButton("sample_data","View Dataset",class="btn btn-info"),
dataTableOutput("sample_data_t")
)
)
),
tabItem(tabName = "analysis",
fluidRow(
box(
width = 12,
title = "Ploting Mean of Dataset ",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
plotOutput("plot_close", click = "plot_close")
)),
#---------------
fluidRow(
box(
width = 12,
title = "Summary Of The Dataset",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
dataTableOutput("AAPL_summary")
)
),
fluidRow(
box(
width = 6,
title = "Jark Pera Test For Normality ",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
textOutput("jark_pera_test")
),
box(
width = 6,
title = "Kolomogorov and Smirnof Test For Normality ",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
textOutput("kolomogorov_test")
)
),
fluidRow(
box(
width = 12,
title = "Histogram Illistrate that The Model is Normally Distrubuted",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
plotOutput("hist_apple_data", click = "hist_apple_data")
)
),
fluidRow(
box(
width = 12,
title = "Questions to be Discused with AAPL market",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
dataTableOutput("document")
)
)
),
#------------------------------------------------------------------------------------------------------------
#----------------------second page -------------------------------------------
# Second tab content
#---------------------------------third page---------------------------------------------------------------------------
# Third tab content
tabItem(tabName = "vis_acf",
fluidRow(
box(
width = 12,
title = "Ploting of Stationary",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
plotOutput("plot_stationary", click = "plot_stationary")
)),
fluidRow(
box(
width = 6,
title = "ploting ACF",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
plotOutput("plot_acf", click = "plot_acf")
),
box(
width = 6,
title = "ploting PACF",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
plotOutput("plot_pacf", click = "plot_pacf")
)
)
),
#---------------------------------------fourth-----------------------
# Fourth tab content
tabItem(tabName = "comp",
fluidRow(
box(
width = 12,
title = "Actual and Forecasted plot (Black is Actual) (Red is Forecasted)",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
plotOutput("plot_afp", click = "plot_afp")
),
box(
width = 12,
title = "View Comparison",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
dataTableOutput("my_comparison")
)
)
),
#---------------------------------------fifth-----------------------
# Fifth tab content
tabItem(tabName = "FMA",
fluidRow(
box(
width = 12,
title = "percentage of comparison of the actual and forcasted values ",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
valueBoxOutput("Accuracy_Box"),
box(
width = 12,
title = "Coefficient of ARIMA Model ",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
tableOutput("arima_coeff")
),
box(
width = 12,
title = "ME $ MSE ",
status= "info",
solidHaider = TRUE,
collapsible = TRUE,
tableOutput("arima_ME")
)
)
)
#-----------------------------------------------------------------------
)
)
)
))
|
83307d51bc7917c087893f0970f8c0dce179a0fc
|
a66068dd2e2b72d3fcff2a9581c92cf1098f3761
|
/2_data_visualization/stratify_and_box_plot.R
|
75f0b0b1e91463e910123a5c626b7018cd002eba
|
[] |
no_license
|
marc-haddad/data-science-cert-journey
|
05f67a26f7e04b0319296b43960c5074ea18fa84
|
00c4e33e67d8b61aa63bbc9b19ce66f482f94ed4
|
refs/heads/master
| 2020-11-26T02:14:05.964650
| 2020-04-25T17:25:59
| 2020-04-25T17:25:59
| 228,933,878
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 305
|
r
|
stratify_and_box_plot.R
|
p = gapminder %>%
filter(year == 2010, !is.na(gdp)) %>%
mutate(region = reorder(region, dollars_per_day, FUN = median)) %>%
ggplot(aes(region, dollars_per_day, fill = continent))
p + geom_boxplot() +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
scale_y_continuous(trans = "log2")
|
eb7c7a9daa53fe172c5e3ad6a725447584636675
|
bed336fc87b09834348f6c3de364953c7558d8bb
|
/R/mosaicsRunAll.R
|
fd692bffd2e945700c5fb8c8076799c2f5f8bc5c
|
[] |
no_license
|
keleslab/mosaics
|
7bc6b95376d8b8a78427194ef3181be67020de40
|
786f5db1438015aaa6bac6c423e7b3655e5df946
|
refs/heads/master
| 2021-07-14T18:00:09.109482
| 2020-02-27T00:37:56
| 2020-02-27T00:37:56
| 38,325,192
| 1
| 0
| null | 2016-05-02T17:50:57
| 2015-06-30T18:11:55
|
R
|
UTF-8
|
R
| false
| false
| 18,815
|
r
|
mosaicsRunAll.R
|
mosaicsRunAll <- function(
chipFile=NULL, chipFileFormat=NULL,
controlFile=NULL, controlFileFormat=NULL,
binfileDir=NULL,
peakFile=NULL, peakFileFormat=NULL,
reportSummary=FALSE, summaryFile=NULL,
reportExploratory=FALSE, exploratoryFile=NULL,
reportGOF=FALSE, gofFile=NULL,
PET=FALSE, byChr=FALSE, useChrfile=FALSE, chrfile=NULL, excludeChr=NULL,
FDR=0.05, fragLen=200, binSize=200, capping=0, bgEst="rMOM", d=0.25,
signalModel="BIC", maxgap=200, minsize=50, thres=10, parallel=FALSE, nCore=8 ) {
analysisType <- "IO"
# check options: input & output (required)
if ( is.null(chipFile) ) { stop( "Please specify 'chipFile'!" ) }
if ( is.null(chipFileFormat) ) { stop( "Please specify 'chipFileFormat'!" ) }
if ( is.null(controlFile) ) { stop( "Please specify 'controlFile'!" ) }
if ( is.null(controlFileFormat) ) { stop( "Please specify 'controlFileFormat'!" ) }
if ( is.null(peakFile) ) { stop( "Please specify 'peakFile'!" ) }
if ( is.null(peakFileFormat) ) { stop( "Please specify 'peakFileFormat'!" ) }
if ( is.null(binfileDir) ) { stop( "Please specify 'binfileDir'!" ) }
# check options: peak list
if ( length(peakFile) != length(peakFileFormat) ) {
stop( "Lengths of 'peakFileName' and 'peakFileFormat' should be same!" )
}
# check options: reports (optional)
if ( reportSummary ) {
if ( is.null(summaryFile) ) {
stop( "Please specify 'summaryFile'!" )
}
}
if ( reportGOF ) {
if ( is.null(gofFile) ) {
stop( "Please specify 'gofFile'!" )
}
}
if ( reportExploratory ) {
if ( is.null(exploratoryFile) ) {
stop( "Please specify 'exploratoryFile'!" )
}
}
# check options: parallel computing (optional)
if ( parallel == TRUE ) {
message( "Use 'parallel' package for parallel computing." )
if ( length(find.package('parallel',quiet=TRUE)) == 0 ) {
stop( "Please install 'parallel' package!" )
}
}
# construction of bin-level files
cat( "Info: constructing bin-level files...\n" )
processSet <- list()
processSet[[1]] <- c( chipFile, chipFileFormat )
processSet[[2]] <- c( controlFile, controlFileFormat )
if ( parallel == TRUE ) {
# if "parallel" package exists, utilize parallel computing with "mclapply"
mclapply( processSet, function(x) {
constructBins(
infile = x[1], fileFormat = x[2], outfileLoc = binfileDir,
byChr = byChr, useChrfile = useChrfile, chrfile = chrfile, excludeChr = excludeChr,
PET = PET, fragLen = fragLen, binSize = binSize, capping = capping )
}, mc.cores=nCore )
} else {
# otherwise, use usual "lapply"
lapply( processSet, function(x) {
constructBins(
infile = x[1], fileFormat = x[2], outfileLoc = binfileDir,
byChr = byChr, useChrfile = useChrfile, chrfile = chrfile, excludeChr = excludeChr,
PET = PET, fragLen = fragLen, binSize = binSize, capping = capping )
} )
}
if ( byChr ) {
###############################################################
# #
# chromosome-wise analysis #
# #
###############################################################
# read in bin-level files
cat( "Info: analyzing bin-level files...\n" )
setwd( binfileDir )
if ( PET == TRUE ) {
list_chip <- list.files( path=binfileDir,
paste(basename(chipFile),"_bin",binSize,"_.*.txt",sep="") )
list_control <- list.files( path=binfileDir,
paste(basename(controlFile),"_bin",binSize,"_.*.txt",sep="") )
} else {
list_chip <- list.files( path=binfileDir,
paste(basename(chipFile),"_fragL",fragLen,"_bin",binSize,"_.*.txt",sep="") )
list_control <- list.files( path=binfileDir,
paste(basename(controlFile),"_fragL",fragLen,"_bin",binSize,"_.*.txt",sep="") )
}
# check list of chromosomes & analyze only chromosomes
# that bin-level files for both chip & control exist
#chrID_chip <- unlist( lapply( strsplit( list_chip, paste("_",basename(chipFile),sep="") ),
# function(x) x[1] ) )
#chrID_control <- unlist( lapply( strsplit( list_control, paste("_",controlFile,sep="") ),
# function(x) x[1] ) )
chrID_chip <- unlist( lapply( list_chip, function(x) {
splitvec <- strsplit( x, "_" )[[1]]
IDtxt <- splitvec[ length(splitvec) ]
return( strsplit( IDtxt, ".txt" )[[1]][1] )
} ) )
chrID_control <- unlist( lapply( list_control, function(x) {
splitvec <- strsplit( x, "_" )[[1]]
IDtxt <- splitvec[ length(splitvec) ]
return( strsplit( IDtxt, ".txt" )[[1]][1] )
} ) )
index_chip <- which( !is.na( match( chrID_chip, chrID_control ) ) )
index_control <- match( chrID_chip, chrID_control )
index_list <- list()
for ( i in 1:length(index_chip) ) {
index_list[[i]] <- c( index_chip[i], index_control[i] )
}
# model fitting & peak calling
# check whether rparallel is available. if so, use it.
cat( "Info: fitting MOSAiCS model & call peaks...\n" )
if ( length(index_chip) < nCore ) {
nCore <- length(index_chip)
}
if ( parallel == TRUE ) {
# if "parallel" package exists, utilize parallel computing with "mclapply"
out <- mclapply( index_list, function(x) {
# read in bin-level file
chip_file <- list_chip[ x[1] ]
input_file <- list_control[ x[2] ]
bin <- readBins(
type=c("chip","input"), fileName=c(chip_file,input_file),
parallel=parallel, nCore=nCore )
# fit model
fit <- mosaicsFit( bin, analysisType=analysisType, bgEst=bgEst, d=d,
parallel=parallel, nCore=nCore )
# call peaks
if ( signalModel=="BIC" ) {
# if not specified, use BIC
if ( fit@bic1S < fit@bic2S ) {
peak <- mosaicsPeak( fit, signalModel="1S",
FDR=FDR, maxgap=maxgap, minsize=minsize, thres=thres )
opt_sig_model <- "One-signal-component model"
} else {
peak <- mosaicsPeak( fit, signalModel="2S",
FDR=FDR, maxgap=maxgap, minsize=minsize, thres=thres )
opt_sig_model <- "Two-signal-component model"
}
} else {
peak <- mosaicsPeak( fit, signalModel=signalModel,
FDR=FDR, maxgap=maxgap, minsize=minsize, thres=thres )
if ( signalModel=="1S" ) {
opt_sig_model <- "One-signal-component model"
} else {
opt_sig_model <- "Two-signal-component model"
}
}
# keep results
peakPrint <- print(peak)
return( list( chrID=as.character( chrID_chip[ x[1] ] ),
bin=bin, fit=fit, peak=peak, peakPrint=peakPrint,
n_peaks=nrow(peak@peakList), peak_width=median(peak@peakList$peakSize),
opt_sig_model=opt_sig_model ) )
}, mc.cores=nCore )
} else {
# otherwise, use usual "lapply"
out <- lapply( index_list, function(x) {
# read in bin-level file
chip_file <- list_chip[ x[1] ]
input_file <- list_control[ x[2] ]
bin <- readBins(
type=c("chip","input"), fileName=c(chip_file,input_file),
parallel=parallel, nCore=nCore )
# fit model
fit <- mosaicsFit( bin, analysisType=analysisType, bgEst=bgEst, d=d,
parallel=parallel, nCore=nCore )
# call peaks
if ( signalModel=="BIC" ) {
# if not specified, use BIC
if ( fit@bic1S < fit@bic2S ) {
peak <- mosaicsPeak( fit, signalModel="1S",
FDR=FDR, maxgap=maxgap, minsize=minsize, thres=thres )
opt_sig_model <- "One-signal-component model"
} else {
peak <- mosaicsPeak( fit, signalModel="2S",
FDR=FDR, maxgap=maxgap, minsize=minsize, thres=thres )
opt_sig_model <- "Two-signal-component model"
}
} else {
peak <- mosaicsPeak( fit, signalModel=signalModel,
FDR=FDR, maxgap=maxgap, minsize=minsize, thres=thres )
if ( signalModel=="1S" ) {
opt_sig_model <- "One-signal-component model"
} else {
opt_sig_model <- "Two-signal-component model"
}
}
# keep results
peakPrint <- print(peak)
return( list( chrID=as.character( chrID_chip[ x[1] ] ),
bin=bin, fit=fit, peak=peak, peakPrint=peakPrint,
n_peaks=nrow(peak@peakList), peak_width=median(peak@peakList$peakSize),
opt_sig_model=opt_sig_model ) )
} )
}
# summarize results
peakSetFinal <- c()
for ( i in 1:length(out) ) {
peakSetFinal <- rbind( peakSetFinal, out[[i]]$peakPrint )
}
resultList <- list()
resultList$chrID <- resultList$n_peaks <-
resultList$peak_width <- resultList$opt_sig_model <- rep( NA, length(out) )
for ( i in 1:length(out) ) {
resultList$chrID[i] <- out[[i]]$chrID
resultList$n_peaks[i] <- out[[i]]$n_peaks
resultList$peak_width[i] <- out[[i]]$peak_width
resultList$opt_sig_model[i] <- out[[i]]$opt_sig_model
}
} else {
###############################################################
# #
# genome-wide analysis #
# #
###############################################################
# read in bin-level files
cat( "Info: analyzing bin-level files...\n" )
setwd( binfileDir )
if ( PET == TRUE ) {
chip_file <- list.files( path=binfileDir,
paste(basename(chipFile),"_bin",binSize,".txt",sep="") )
input_file <- list.files( path=binfileDir,
paste(basename(controlFile),"_bin",binSize,".txt",sep="") )
} else {
chip_file <- list.files( path=binfileDir,
paste(basename(chipFile),"_fragL",fragLen,"_bin",binSize,".txt",sep="") )
input_file <- list.files( path=binfileDir,
paste(basename(controlFile),"_fragL",fragLen,"_bin",binSize,".txt",sep="") )
}
# model fitting & peak calling
# check whether rparallel is available. if so, use it.
cat( "Info: fitting MOSAiCS model & call peaks...\n" )
out <- list()
# read in bin-level file
out$bin <- readBins( type=c("chip","input"), fileName=c(chip_file,input_file),
parallel=parallel, nCore=nCore )
# fit model
out$fit <- mosaicsFit( out$bin, analysisType=analysisType, bgEst=bgEst, d=d,
parallel=parallel, nCore=nCore )
# call peaks
if ( signalModel=="BIC" ) {
# if not specified, use BIC
if ( out$fit@bic1S < out$fit@bic2S ) {
out$peak <- mosaicsPeak( out$fit, signalModel="1S",
FDR=FDR, maxgap=maxgap, minsize=minsize, thres=thres )
out$opt_sig_model <- "One-signal-component model"
} else {
out$peak <- mosaicsPeak( out$fit, signalModel="2S",
FDR=FDR, maxgap=maxgap, minsize=minsize, thres=thres )
out$opt_sig_model <- "Two-signal-component model"
}
} else {
out$peak <- mosaicsPeak( out$fit, signalModel=signalModel,
FDR=FDR, maxgap=maxgap, minsize=minsize, thres=thres )
if ( signalModel=="1S" ) {
out$opt_sig_model <- "One-signal-component model"
} else {
out$opt_sig_model <- "Two-signal-component model"
}
}
# keep results
peakSetFinal <- print(out$peak)
peakPrint <- split( peakSetFinal, peakSetFinal$chrID )
out$chrID <- names(peakPrint)
out$n_peaks <- unlist( lapply( peakPrint, nrow ) )
out$peak_width <- unlist( lapply( peakPrint, function(x) { median(x$peakSize) } ) )
resultList <- list()
resultList$chrID <- out$chrID
resultList$n_peaks <- out$n_peaks
resultList$peak_width <- out$peak_width
resultList$opt_sig_model <- rep( out$opt_sig_model, length(resultList$chrID) )
}
# write peak calling results
cat( "Info: writing the peak list...\n" )
for ( ff in 1:length(peakFileFormat) ) {
if ( peakFileFormat[ff] == "txt" ) {
.exportTXT( peakList=peakSetFinal, filename=peakFile[ff] )
} else if ( peakFileFormat[ff] == "bed" ) {
.exportBED( peakList=peakSetFinal, filename=peakFile[ff] )
} else if ( peakFileFormat[ff] == "gff" ) {
.exportGFF( peakList=peakSetFinal, filename=peakFile[ff] )
} else {
stop( "Inappropriate peak file format!" )
}
}
# report: summary
cat( "Info: generating reports...\n" )
if ( reportSummary ) {
.reportSummary( summaryFile=summaryFile, resultList=resultList,
chipFile=chipFile, chipFileFormat=chipFileFormat,
controlFile=controlFile, controlFileFormat=controlFileFormat,
binfileDir=binfileDir,
peakFile=peakFile, peakFileFormat=peakFileFormat,
byChr=byChr, FDR=FDR, fragLen=fragLen, binSize=binSize, capping=capping,
analysisType=analysisType, d=d,
signalModel=signalModel, maxgap=maxgap, minsize=minsize, thres=thres )
}
# GOF
if ( reportGOF ) {
pdf(gofFile)
if ( byChr ) {
for ( i in 1:length(out) ) {
chrID <- out[[i]]$chrID
fit <- out[[i]]$fit
# chrID
plot( 0, 0, type="n", axes=F, ann=F )
text( 0, 0, chrID, cex=4 )
# GOF
plot(fit)
}
} else {
fit <- out$fit
plot(fit)
}
dev.off()
}
# exploratory analysis
if ( reportExploratory ) {
pdf(exploratoryFile)
if ( byChr ) {
for ( i in 1:length(out) ) {
chrID <- out[[i]]$chrID
bin <- out[[i]]$bin
# chrID
plot( 0, 0, type="n", axes=F, ann=F )
text( 0, 0, chrID, cex=4 )
# exploratory plots
plot( bin )
if ( analysisType=="IO" ) {
plot( bin, plotType="input" )
}
if ( analysisType=="OS" ) {
plot( bin, plotType="M" )
plot( bin, plotType="GC" )
}
if ( analysisType=="TS" ) {
plot( bin, plotType="M" )
plot( bin, plotType="GC" )
plot( bin, plotType="M|input" )
plot( bin, plotType="GC|input" )
}
}
} else {
bin <- out$bin
# exploratory plots
plot( bin )
if ( analysisType=="IO" ) {
plot( bin, plotType="input" )
}
if ( analysisType=="OS" ) {
plot( bin, plotType="M" )
plot( bin, plotType="GC" )
}
if ( analysisType=="TS" ) {
plot( bin, plotType="M" )
plot( bin, plotType="GC" )
plot( bin, plotType="M|input" )
plot( bin, plotType="GC|input" )
}
}
dev.off()
}
}
|
a35d7fcdd7208a41886173648aa6a08c26693796
|
a45bdb32cd9b137bc8d6744186d997a80315deb4
|
/code/prepare_data/delete_temp_vital_rate_files.R
|
b75ce7091e0d8ade5d2eb8ab3e3e4c9e357a89f2
|
[] |
no_license
|
akleinhesselink/forecast-plants
|
afff9bd51bd19dd37aeaed020eb84d857195874f
|
272774addd8be03492f8fc095bd36a6089eaf522
|
refs/heads/master
| 2023-08-22T23:59:24.015321
| 2023-08-14T16:11:03
| 2023-08-14T16:11:03
| 181,106,169
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 318
|
r
|
delete_temp_vital_rate_files.R
|
rm (list = ls())
combos <- expand.grid(spp = c('ARTR', 'HECO', 'POSE', 'PSSP'), vr = c('growth','survival', 'recruitment'))
temp_files <- file.path( 'data/temp', paste0( combos$spp, '_', combos$vr, '.RDS'))
to_remove <- temp_files[ file.exists(temp_files) ]
file.remove(to_remove) # Clean up temporary files
|
44cdc23516ecd65aa3af3b3daf9b2dc31fa23ac7
|
8ab72a394d8ece44c405202b77866bfa6d20001a
|
/R/download.R
|
9a271ffc5f421af7931aa461799542fc2499acbd
|
[] |
no_license
|
ateucher/era5landDownloadTools
|
bdbcc0c618d11a9fadba94b344c6e39ca410604a
|
3fa887e67bde245daae497808a707d12c13018ae
|
refs/heads/master
| 2023-08-12T04:04:50.254279
| 2021-10-01T17:46:26
| 2021-10-01T17:46:26
| 414,678,375
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,180
|
r
|
download.R
|
#' Download hourly
#'
#' This function
#'
#' @param aoi any sf object
#' @param aoi_name string
#' @param years numeric from 1979-2021
#' @param months numeric from 1-12
#' @param days numeric from 1-31
#' @param hours numeric from 0-23
#' @param variables 'surface_net_solar_radiation','2m_temperature','total_precipitation','snow_depth_water_equivalent', ...
#' @param user your user id as a string
#' @param key your api key as a string
#' @param download_dir download directory
#' @return A matrix of the infile
#' @export
era5land_download_hourly <- function(aoi = aoi,
aoi_name = name,
years = 2021:2021,
months = 5:8,
days = 1:31,
hours = 0:23,
variables = c('surface_net_solar_radiation'),
user = "",
key = "",
download_dir = "."){
### AUTHENTICATE ####
wf_set_key(user = user,
key = key,
service = "cds")
#### FORMAT REQUEST ####
# Format years
years <- as.character(years)
# Format months
months <- str_pad(string = months, width = 2, side = "left", pad = 0)
# Format days
days <- str_pad(string = days, width = 2, side = "left", pad = "0") # MAX 31
# Format time
hours <- paste0(str_pad(string = hours, width = 2, side = "left", pad = "0"),":00") # MAX 23
# Out name
target <- paste0("ERA5-land-hourly_",
aoi_name, "_",
min(years),"-",
max(years),"y_",
min(months),"-",
max(months),"m_",
min(days),"-",
max(days),"d_",
min(hours),"-",
max(hours),"h_",
length(variables),"vars.grib")
# FORMAT BOUNDS
bounds = paste(st_bbox(aoi)[4] %>% as.numeric() %>% round(0),
st_bbox(aoi)[1] %>% as.numeric() %>% round(0),
st_bbox(aoi)[2] %>% as.numeric() %>% round(0),
st_bbox(aoi)[3] %>% as.numeric() %>% round(0), sep = "/")
# Setup request
request <- list("dataset_short_name" = 'reanalysis-era5-land',
'product_type' = 'reanalysis',
"variable" = variables,
"year" = years,
"month" = months,
"day" = days,
"time" = hours,
"area" = bounds,
"format" = "grib",
"target" = target)
file <- wf_request(user = user,
request = request,
transfer = TRUE,
path = download_dir)
return(file)
}
#' Download monthly
#'
#' This function
#'
#' @param aoi any sf object
#' @param aoi_name string
#' @param years numeric from 1979-2021
#' @param months numeric from 1-12
#' @param variables 'surface_net_solar_radiation','2m_temperature','total_precipitation','snow_depth_water_equivalent', ...
#' @param user your user id as a string
#' @param key your api key as a string
#' @param download_dir download directory
#' @return A matrix of the infile
#' @export
era5land_download_monthly <- function(aoi = aoi,
aoi_name = name,
years = 2021:2021,
months = 5:8,
variables = c('2m_temperature', 'total_precipitation'),
user = "",
key = "",
download_dir = "."){
### AUTHENTICATE ####
wf_set_key(user = user,
key = key,
service = "cds")
#### FORMAT REQUEST ####
# Format years
years <- as.character(years)
# Format months
months <- str_pad(string = months, width = 2, side = "left", pad = 0)
# Out name
target <- paste0("ERA5-land-monthly_",
aoi_name, "_",
min(years),"-",
max(years),"y_",
min(months),"-",
max(months),"m_",
length(variables),"vars.grib")
# FORMAT BOUNDS
bounds = paste(st_bbox(aoi)[4] %>% as.numeric() %>% round(0),
st_bbox(aoi)[1] %>% as.numeric() %>% round(0),
st_bbox(aoi)[2] %>% as.numeric() %>% round(0),
st_bbox(aoi)[3] %>% as.numeric() %>% round(0), sep = "/")
# Setup request
request <- list("dataset_short_name" = 'reanalysis-era5-land-monthly-means',
"product_type" = "monthly_averaged_reanalysis",
"variable" = variables,
"year" = years,
"month" = months,
"time" = "00:00",
"area" = bounds,
"format" = "grib",
"target" = target)
file <- wf_request(user = user,
request = request,
transfer = TRUE,
path = download_dir)
return(file)
}
|
92fc412fb771eb61314c3c3e0d4522a2856c5a25
|
99439d0385ef8ccdd69ff84c69e628582613f9d4
|
/comparisonoftails.R
|
f52f675022ea178861ba801c4c962c1e1354d21c
|
[] |
no_license
|
kanishkasthana/TADLocator
|
017e325271b6bc221e2c5e3a4ac04ac39f52682c
|
7baa3a66bd5a76f61436075c2de6bfc8d0b7bafd
|
refs/heads/master
| 2021-03-12T21:37:23.845659
| 2015-01-20T21:37:59
| 2015-01-20T21:37:59
| 27,063,829
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 342
|
r
|
comparisonoftails.R
|
tailbins=function(stringency){
tailbins=apply(all_rates,2,function(rates){
mn=mean(rates);
s=sd(rates);
new_rows_left[rates<=(mn-stringency*s)]
})
return(tailbins[[6]])
}
out=sapply(1:length(sts),function(i)
{
out=length(intersect(rep1[[i]],rep2[[i]]))/min(length(rep1[[i]]),length(rep2[[i]]));
return(out)
})
|
5794246bca8e45108ea17009af02a1167aeff218
|
b1a12b171097fcb0b2a6f7a10e0ab7afdf41aac1
|
/man/gaugeArrow.Rd
|
f420a1ecb45968338ccba8208e121b1abe9ed9cc
|
[] |
no_license
|
myndworkz/rAmCharts
|
7e1d66002cbca9ef63e1d2af6b4e49a1ac7cd3c3
|
6ea352cab2c9bc5f647447e5e7d902d9cbec0931
|
refs/heads/master
| 2021-01-14T13:06:28.947936
| 2015-07-29T12:34:13
| 2015-07-29T12:34:13
| 39,955,321
| 1
| 0
| null | 2015-07-30T14:37:43
| 2015-07-30T14:37:43
| null |
UTF-8
|
R
| false
| false
| 453
|
rd
|
gaugeArrow.Rd
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/GaugeArrow.R
\name{gaugeArrow}
\alias{gaugeArrow}
\title{Constructor.}
\usage{
gaugeArrow(fillAlpha, alpha = 1, axis, ...)
}
\arguments{
\item{\code{...}:}{{Properties of GaugeArrow.
See \code{\url{http://docs.amcharts.com/3/javascriptcharts/GaugeArrow}}}}
}
\value{
An \code{\linkS4class{GaugeArrow}} object
}
\description{
Constructor.
}
\examples{
gaugeArrow()
}
|
f5e9c6575d9a3cca64030e7afdddf598d393de97
|
fc36112ec2687ee3a56086fc121a8e8101c5d62c
|
/man/validate_title.Rd
|
817854c6a35947a05b575ab34df19ada7d596ee0
|
[
"MIT"
] |
permissive
|
EDIorg/EMLassemblyline
|
ade696d59147699ffd6c151770943a697056e7c2
|
994f7efdcaacd641bbf626f70f0d7a52477c12ed
|
refs/heads/main
| 2023-05-24T01:52:01.251503
| 2022-11-01T01:20:31
| 2022-11-01T01:20:31
| 84,467,795
| 36
| 17
|
MIT
| 2023-01-10T01:20:56
| 2017-03-09T17:04:28
|
R
|
UTF-8
|
R
| false
| true
| 440
|
rd
|
validate_title.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/validate_arguments.R
\name{validate_title}
\alias{validate_title}
\title{Validate dataset title}
\usage{
validate_title(fun.args)
}
\arguments{
\item{fun.args}{(named list) Function arguments and their values.}
}
\value{
\item{character}{Description of issues}
\item{NULL}{If no issues were found}
}
\description{
Validate dataset title
}
\keyword{internal}
|
e64231562163dc78466942ed3c9ac5fe5c297162
|
c1bf7397ddc833b7ba9617e22ee2bdc86e646ee4
|
/rCode/sql for app_version.R
|
a0134561c232a92b08807e86daf8e2283af9cf3e
|
[] |
no_license
|
cxq914/Data-Science
|
1b5f6f9ac089d098b8d6c91d722dbf70f75e5613
|
6f9648cf323f8cfbcd69aa6b97991f9162013d34
|
refs/heads/master
| 2021-01-19T18:55:56.696529
| 2016-02-18T00:34:11
| 2016-02-18T00:34:11
| 21,634,205
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 7,356
|
r
|
sql for app_version.R
|
library(openxlsx)
library(scales)
library(DBI)
library(RPostgreSQL)
# create a connection
# save the password that we can "hide" it as best as we can by collapsing it
pw <- {
"SJux7eBpuZRN"
}
# loads the PostgreSQL driver
drv <- dbDriver("PostgreSQL")
# creates a connection to the postgres database
# note that "con" will be used later in each connection to the database
con <- dbConnect(drv, dbname = "elc",
host = "pgdatabase-1.cjkahljjqai2.us-west-2.rds.amazonaws.com", port = 5432,
user = "elc_logger", password = pw)
rm(pw) # removes the password
# check for the cartable
dbExistsTable(con, "daily_restaurant_stats")
# query the data from postgreSQL
query <- paste( "select count(main_app_version), main_app_version, desired_restaurant_code from devices d join restaurants r on d.desired_restaurant_code = r.code where status = 'Customer - Live' and r.code like 'applebees_%' group by main_app_version, desired_restaurant_code order by desired_restaurant_code; ")
query <- paste("select desired_restaurant_code,g ->>'app_name' as app_name, count(distinct mac) as Freq
from devices cross join json_array_elements(devices.other_app_versions) g
where (g ->> 'app_name' = '7D Mine Train' or g ->> 'app_name' = 'Olaf''s Adventures') and last_heartbeat > now() - interval '2 day'
group by desired_restaurant_code,g ->>'app_name'
order by count(distinct mac),g ->>'app_name' desc;")
df_postgres <- dbGetQuery(con, query)
query <- paste("select desired_restaurant_code, count(distinct mac) as HeartBeatFreq
from devices
where last_heartbeat > now() - interval '2 day'
group by desired_restaurant_code
order by count(distinct mac) desc;")
df_postgres_heartbeat <- dbGetQuery(con, query)
train <- subset(df_postgres,df_postgres$app_name=='7D Mine Train')
olaf <- subset(df_postgres,df_postgres$app_name=="Olaf's Adventures")
dat <- merge(train, olaf, by='desired_restaurant_code',all = TRUE)
dat1 <- dat[,c(1,3,5)]
colnames(dat1) <- c('Restaurant.Code','7D Mine Train',"Olaf's Adventures")
withHeart <- merge(dat1,df_postgres_heartbeat,by.x='Restaurant.Code', by.y = 'desired_restaurant_code',all=TRUE)
res <- unique(res.info[,c(3,7,8)])
res <- subset(res,res$`Number.of.Presto's.Installed`>0)
dat.new <- merge(withHeart,res, by='Restaurant.Code')
dat.new[is.na(dat.new)] <- 0
write.xlsx(dat.new,file = 'Disney Game with Heartbeat count.xlsx')
dat.final <- merge(dat1,res,by='Restaurant.Code',all=TRUE)
dat.final[is.na(dat.final)] <- 0
weired <- subset(dat.final,dat.final$`Number.of.Presto's.Installed`==0)
normal <- subset(dat.new,dat.new$`Number.of.Presto's.Installed`!=0)
withHeart[is.na(withHeart)] <- 0
normal <- withHeart
normal$`7D Mine Train Per` <- round(normal$`7D Mine Train`/normal$heartbeatfreq,4)
normal$`Olaf's Adventures Per` <- round(normal$`Olaf's Adventures`/normal$heartbeatfreq,4)
normal[normal$`7D Mine Train Per`>1,]$`7D Mine Train Per` <- 1
normal[normal$`Olaf's Adventures Per`>1,]$`Olaf's Adventures Per` <- 1
Train_level <- cut(normal$`7D Mine Train Per`,breaks=c(0,0.000001,0.5,0.9,0.99999,1),include.lowest = TRUE,right = TRUE)
levels(Train_level) <- c('0','<50%','50-90%','>90%','100%')
normal <- cbind(normal,Train_level)
Olaf_level <- cut(normal$`Olaf's Adventures Per`,breaks=c(0,0.000001,0.5,0.9,0.999999,1),include.lowest = TRUE,right = TRUE)
levels(Olaf_level) <- c('0','<50%','50-90%','>90%','100%')
normal <- cbind(normal,Olaf_level)
write.xlsx(normal,'Disney Game Downloads_with Heartbeat_new.xlsx')
query <- paste("select count(main_app_version), main_app_version, desired_restaurant_code
from devices d join restaurants r on d.desired_restaurant_code = r.code
where status = 'Customer - Live' and r.code like 'applebees_%' and last_heartbeat > now() - interval '2 days'
group by main_app_version, desired_restaurant_code
order by desired_restaurant_code;")
df_postgres <- dbGetQuery(con, query)
query1 <- paste("select count(distinct mac), desired_restaurant_code
from devices d join restaurants r on d.desired_restaurant_code = r.code
where status = 'Customer - Live' and r.code like 'applebees_%' and last_heartbeat > now() - interval '2 days'
group by desired_restaurant_code
order by desired_restaurant_code;")
df_postgres1 <- dbGetQuery(con, query1)
version.count <- merge(df_postgres,df_postgres1, by = 'desired_restaurant_code')
version.count$diff <- version.count$count.x-version.count$count.y
query1 <- paste("select chain_name,restaurant_code, day, presto_games_total, round(avg(presto_games_total/pos_check_count),3) as AverageRevenuePerPOSCheck,pos_check_count,pos_check_total,presto_payments_count
from daily_restaurant_stats
where restaurant_status = 'Customer - Live' and day = '2016-01-16' and restaurant_name like 'Applebee%' and pos_check_count >0
group by chain_name,restaurant_code, day, presto_games_total,pos_check_count,pos_check_total,presto_payments_count
order by day;
")
df_postgres1 <- dbGetQuery(con, query1)
query2 <- paste("select restaurant_code, presto_payments_count,pos_check_count from daily_restaurant_stats
where pos_check_count>0 and day > '2016-01-15'
")
df_postgres2 <- dbGetQuery(con, query2)
query3 <- paste("select chain_name,restaurant_code, day, presto_games_total, round(avg(presto_games_total/pos_check_count),3) as AverageRevenuePerPOSCheck,pos_check_count,pos_check_total,presto_payments_count
from daily_restaurant_stats
where restaurant_status = 'Customer - Live' and day = '2016-01-17' and restaurant_name like 'Applebee%' and pos_check_count >0
group by chain_name,restaurant_code, day, presto_games_total,pos_check_count,pos_check_total,presto_payments_count
order by day;
")
df_postgres3 <- dbGetQuery(con, query3)
query4 <- paste("select chain_name,restaurant_code, day, presto_games_total, round(avg(presto_games_total/pos_check_count),3) as AverageRevenuePerPOSCheck,pos_check_count,pos_check_total,presto_payments_count
from daily_restaurant_stats
where restaurant_status = 'Customer - Live' and day = '2016-01-24' and restaurant_name like 'Applebee%' and pos_check_count >0
group by chain_name,restaurant_code, day, presto_games_total,pos_check_count,pos_check_total,presto_payments_count
order by day;
")
df_postgres4 <- dbGetQuery(con, query4)
total <- rbind(df_postgres1,df_postgres2,df_postgres3,df_postgres4)
dat <- read.xlsx('Applebee Data/Result/Data with Payment( 2015-12-07 - 2016-01-17 ).xlsx', detectDates = TRUE)
dat <- unique(dat[,c(1,5,6)])
dat.total <- merge(total,dat, by.x = 'restaurant_code', by.y = 'Restaurant.Code')
write.xlsx(dat.total,'TotalData.xlsx')
res1 <- unique(df_postgres1$restaurant_code)
res2 <- unique(df_postgres2$restaurant_code)
sunday<- merge(df_postgres4,df_postgres3,by=c('chain_name','restaurant_code'))
sunday$diff <- sunday$presto_games_total.x-sunday$presto_games_total.y
total <- merge(sunday,dat, by.x = 'restaurant_code',by.y = 'Restaurant.Code')
write.xlsx(total,'totalData.xlsx')
|
1f2f5234eca6a2a315a9f15af35615c8f5b4583a
|
1f9b2393f1ad1408b5f41723d76b93a6c3817640
|
/airflow/scripts/R/upsert_tidyverse_data.R
|
5e107e1336a37c327f3567c20495c0aabc839b73
|
[] |
no_license
|
dscheel42/productor
|
259d8bf31da3e12dd3153af5c4739c06c8348990
|
413387ed6b35e503777820ffeb47e8f625d36064
|
refs/heads/master
| 2022-12-03T12:04:35.841905
| 2020-07-29T21:21:18
| 2020-07-29T21:21:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 487
|
r
|
upsert_tidyverse_data.R
|
library(productor)
(function() {
con <-
postgres_connector(
POSTGRES_HOST = Sys.getenv('POSTGRES_HOST'),
POSTGRES_PORT = Sys.getenv('POSTGRES_PORT'),
POSTGRES_USER = Sys.getenv('PRODUCTOR_POSTGRES_USER'),
POSTGRES_PASSWORD = Sys.getenv('PRODUCTOR_POSTGRES_PASSWORD'),
POSTGRES_DB = Sys.getenv('PRODUCTOR_POSTGRES_DB')
)
on.exit(expr = {
message('Disconnecting')
dbDisconnect(conn = con)
})
upsert_tidyverse_data(con)
})()
|
0d22545498337cf9195a8deaa3de8451f23c7fce
|
93a5d1061c7ab7e9f206bbba4f7db15af6402cff
|
/tests/testthat/test-export_list.R
|
bf7b239a6335d3ba0f5dab90013f16bb1f3622d8
|
[
"MIT"
] |
permissive
|
medpsytuebingen/medpsytueR
|
5167020e7883835df31cbd136bff13aa1c1fa832
|
a9e99e7b4a45d0db27fd37218b87cb44d12a3b5b
|
refs/heads/master
| 2018-11-23T05:26:07.233791
| 2018-10-12T08:43:31
| 2018-10-12T08:43:31
| 122,198,819
| 1
| 1
| null | 2018-09-04T10:59:52
| 2018-02-20T13:01:56
|
R
|
UTF-8
|
R
| false
| false
| 182
|
r
|
test-export_list.R
|
context("test-export_list.R")
l <- list(a = c("a", "b"),
b = c(1, 2, 3))
v <- c(1, 2, 3)
test_that("fail if no list is provided", {
expect_error(export_list = v)
})
|
7486b7a1826fa187344939a93fd86ee8d10744c8
|
9cbc8d7ae4c57f4948d47f11e2edcba21a1ba334
|
/sources/modules/VETransportSupply/man/BusEquivalents_df.Rd
|
8b412c21de55ebb6adb44369ca4e626590682213
|
[
"Apache-2.0"
] |
permissive
|
rickdonnelly/VisionEval-Dev
|
c01c7aa9ff669af75765d1dfed763a23216d4c66
|
433c3d407727dc5062ec4bf013abced4f8f17b10
|
refs/heads/master
| 2022-11-28T22:31:31.772517
| 2020-04-29T17:53:33
| 2020-04-29T17:53:33
| 285,674,503
| 0
| 0
|
Apache-2.0
| 2020-08-06T21:26:05
| 2020-08-06T21:26:05
| null |
UTF-8
|
R
| false
| true
| 1,226
|
rd
|
BusEquivalents_df.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/AssignTransitService.R
\docType{data}
\name{BusEquivalents_df}
\alias{BusEquivalents_df}
\title{Bus equivalency factors}
\format{A data frame with 8 rows and 2 variables containing factors for
converting revenue miles of various modes to bus equivalent revenue miles.
Mode names are 2-character codes corresponding to consolidated mode types.
Consolidated mode types represent modes that have similar characteristics and
bus equivalency values. The consolidate mode codes and their meanings are as
follows:
DR = Demand-responsive
VP = Vanpool and similar
MB = Standard motor bus
RB = Bus rapid transit and commuter bus
MG = Monorail/automated guideway
SR = Streetcar/trolley bus/inclined plain
HR = Heavy Rail/Light Rail
CR = Commuter Rail/Hybrid Rail/Cable Car/Aerial Tramway
\describe{
\item{Mode}{abbreviation for consolidated mode}
\item{BusEquivalents}{numeric factor for converting revenue miles to bus equivalents}
}}
\source{
AssignTransitService.R script.
}
\usage{
BusEquivalents_df
}
\description{
Bus revenue mile equivalency factors to convert revenue miles for various
modes to bus-equivalent revenue miles.
}
\keyword{datasets}
|
0957dbb62b57d8d34aca88f0dc26d36cf1c27dda
|
9de3ee2a75cfb11724662e53651c11d01d7b4b1b
|
/inst/tests/CopyOfcheck_incDemo.R
|
3b1e3cf651a672caf62c16566cde75b691adfff1
|
[] |
no_license
|
markusfritsch/pdynmc
|
52a3d884c907380085a932f661d2e2ae61bf57b8
|
62f96a72438260fb589aaaba750696a03dfd47d2
|
refs/heads/master
| 2023-08-09T07:42:42.064521
| 2023-07-26T10:50:46
| 2023-07-26T10:50:46
| 229,298,521
| 6
| 3
| null | 2022-04-26T08:48:24
| 2019-12-20T16:23:37
|
R
|
UTF-8
|
R
| false
| false
| 11,956
|
r
|
CopyOfcheck_incDemo.R
|
rm(list = ls())
# install.packages("pdynmc")
library(pdynmc)
# install.packages("pder")
library(pder)
data("DemocracyIncome", package = "pder")
data("DemocracyIncome25", package = "pder")
dat <- DemocracyIncome
# dat <- DemocracyIncome25
rm(DemocracyIncome, DemocracyIncome25)
head(dat)
tail(dat)
str(dat)
#dat <- dat[!is.na(dat[,"democracy"]), ]
#dat.full <- data.frame("i" = rep(unique(as.numeric(dat$country)), each = length(unique(dat$year))),
# "country" = rep(unique(as.character(dat$country)), each = length(unique(dat$year))),
# "t" = rep(unique(as.numeric(dat$year)), each = length(unique(dat$country))),
# "year" = rep(unique(as.character(dat$year)), each = length(unique(dat$country))),
# "democracy" = NA,
# "income" = NA
#)
table(dat[, "year"])
data.info(dat, i.name = "country", t.name = "year")
strucUPD.plot(dat, i.name = "country", t.name = "year")
m10 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 1
,opt.meth = "none"
)
summary(m10)
m11 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 1
,include.dum = TRUE, dum.lev = TRUE, dum.diff = FALSE, varname.dum = "year"
,opt.meth = "none"
)
summary(m11)
m12 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 1
,include.dum = TRUE, dum.lev = TRUE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m12)
m13 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 1
,include.dum = TRUE, dum.lev = FALSE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m13)
m14 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,include.dum = TRUE, dum.lev = FALSE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m14)
m15 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = TRUE, dum.diff = FALSE, varname.dum = "year"
,opt.meth = "none"
)
summary(m15)
m16 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = FALSE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m16)
m17 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = TRUE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m17)
m20 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 1
,opt.meth = "BFGS"
)
summary(m20)
m21 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 1
,include.dum = TRUE, dum.lev = FALSE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "BFGS", max.iter = 4
)
summary(m21)
m22 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 1
,include.dum = TRUE, dum.lev = TRUE, dum.diff = FALSE, varname.dum = "year"
,opt.meth = "BFGS", max.iter = 4
)
summary(m22)
m23 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 1
,include.dum = TRUE, dum.lev = TRUE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "BFGS", max.iter = 4
)
summary(m23)
m24 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,include.dum = TRUE, dum.lev = FALSE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m24)
m25 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,include.dum = TRUE, dum.lev = TRUE, dum.diff = FALSE, varname.dum = "year"
,opt.meth = "none"
)
summary(m25)
m26 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,include.dum = TRUE, dum.lev = TRUE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m26)
m27 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = FALSE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m27)
m28 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = TRUE, dum.diff = FALSE, varname.dum = "year"
,opt.meth = "none"
)
summary(m28)
m29 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = TRUE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m29)
m30 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 1
,opt.meth = "none"
)
summary(m30)
m31 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,opt.meth = "none"
)
summary(m31)
m32 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,opt.meth = "BFGS", max.iter = 4
)
summary(m32)
m33 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,opt.meth = "none", estimation = "iterative", max.iter = 50
)
summary(m33)
m34 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,include.dum = TRUE, dum.lev = FALSE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m34)
m35 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,include.dum = TRUE, dum.lev = TRUE, dum.diff = FALSE, varname.dum = "year"
,opt.meth = "none"
)
summary(m35)
m36 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,include.dum = TRUE, dum.lev = TRUE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m36)
m37 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = FALSE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m37)
m38 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = TRUE, dum.diff = FALSE, varname.dum = "year"
,opt.meth = "none"
)
summary(m38)
m39 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = TRUE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "none"
)
summary(m39)
m40 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 1
,opt.meth = "BFGS"
)
summary(m40)
m41 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,opt.meth = "BFGS"
)
summary(m41)
m42 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,opt.meth = "BFGS", max.iter = 4
)
summary(m42)
m44 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,include.dum = TRUE, dum.lev = FALSE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "BFGS", max.iter = 4
)
summary(m44)
m45 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,include.dum = TRUE, dum.lev = TRUE, dum.diff = FALSE, varname.dum = "year"
,opt.meth = "BFGS", max.iter = 4
)
summary(m45)
m46 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 2
,include.dum = TRUE, dum.lev = TRUE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "BFGS", max.iter = 4
)
summary(m46)
m47 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = FALSE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "BFGS", max.iter = 4
)
summary(m47)
m48 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = TRUE, dum.diff = FALSE, varname.dum = "year"
,opt.meth = "BFGS", max.iter = 4
)
summary(m48)
m49 <- pdynmc(dat = dat, varname.i = "country", varname.t = "year"
,use.mc.diff = TRUE, use.mc.lev = TRUE, use.mc.nonlin = FALSE
,varname.y = "democracy", include.y = TRUE, lagTerms.y = 3
,include.dum = TRUE, dum.lev = TRUE, dum.diff = TRUE, varname.dum = "year"
,opt.meth = "BFGS", max.iter = 4
)
summary(m49)
ls()[grepl(ls(), pattern = "m")]
length(ls()[grepl(ls(), pattern = "m")]) # 37 configurations are estimated
|
508e1cc8e8ea438b47d0ca7213899110f5de3d7e
|
7322d471211d096da536eb3383753fd75c994807
|
/res/rol-5.r
|
0cfb1893b51a091dc8c3536b128772a9cc9b2ede
|
[] |
no_license
|
HeitorBRaymundo/861
|
fbe09d7d226511895a493174b90fcdfe0a7f490d
|
cfcedf9097280073d4325fc9c5d7e28ba3633a52
|
refs/heads/master
| 2020-06-28T18:22:50.598143
| 2019-11-01T21:45:39
| 2019-11-01T21:45:39
| 200,306,264
| 0
| 0
| null | 2019-11-01T21:46:10
| 2019-08-02T22:48:20
|
Assembly
|
UTF-8
|
R
| false
| false
| 1,274
|
r
|
rol-5.r
|
| pc = 0xc002 | a = 0x02 | x = 0x00 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
| pc = 0xc004 | a = 0x02 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
| pc = 0xc007 | a = 0x02 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 | MEM[0x0305] = 0x02 |
| pc = 0xc00a | a = 0x02 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
| pc = 0xc00d | a = 0x02 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
| pc = 0xc010 | a = 0x02 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
| pc = 0xc013 | a = 0x02 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
| pc = 0xc016 | a = 0x02 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
| pc = 0xc019 | a = 0x02 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
| pc = 0xc01c | a = 0x02 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
| pc = 0xc01f | a = 0x02 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
| pc = 0xc022 | a = 0x02 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
| pc = 0xc025 | a = 0x04 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 | MEM[0x0305] = 0x04 |
| pc = 0xc027 | a = 0x05 | x = 0x05 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110100 |
|
c7cb16f3d600bf13e63fdd73f272e17175eab423
|
da112c3e7e600b5bb42723eac31899260173de8a
|
/R/cprd_medcodes.R
|
ba9170565a3e996aea229255ddf7586a1a61db8b
|
[] |
no_license
|
rosap/test
|
b1b01d039ed895be7cbff04ac23d1661b4dec76b
|
604585f7bb9350db1b0fe7ddc6457083aeb3936b
|
refs/heads/master
| 2020-04-12T09:39:23.594450
| 2016-10-07T15:01:47
| 2016-10-07T15:01:47
| 63,771,068
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,001
|
r
|
cprd_medcodes.R
|
#' Produce a dataset of CPRD medcodes with frequencies of patients in the clinical table
#'
#' This function aggregates all distinct patients matching each CPRD medcode in the clinical table
#'
#' Note that this does not translate to Read/OXMIS codes.
#' This function should be fast because all of the heavy lifting happens in SQLite before the data is exported to R
#'
#' @param db a database connection
#' @param clinical_table name of the clinical table in the database
#' @param patid name of the patid field
#' @param medcode name of the medcode field
#' @export
#' @examples \dontrun{
#' medcode_counts <- patients_per_medcode(db)
#' head(medcode_counts)
#' }
patients_per_medcode <- function(db, clinical_table = "Clinical", patid = "patid", medcode = "medcode"){
sqldf(sprintf("SELECT %s, COUNT(DISTINCT %s) AS patients FROM %s GROUP BY %s",
medcode, patid, clinical_table, medcode),
connection = db)
}
#' Translate CPRD medcodes to Read/Oxmis
#'
#' This function accepts a data frame with a column for CPRD medcodes and merges with a medical lookup table to give columns for Read/OXMIS codes and optional descriptions
#'
#' Note that if the names of the medcodes columns are different in the data and the lookup table, the name in the data is retained
#' To maintain sanity, a warning will be given to inform of are any name conflicts between the input data and the lookup
#'
#' @export
#'
#' @param medcodes_data a dataframe with a column matching medcodes_name
#' @param lookup_table a dataframe with columns matching lookup_readcodes and lookup_medcodes
#' @param medcodes_name character name of the CPRD medcodes column in medcodes_data
#' @param lookup_readcodes character name of the Read codes column in the lookup_table
#' @param lookup_medcodes character name of the CPRD medcodes column in the lookup_table
#' @param description logical Should description and other categories from the lookup table also be included?
#' @return a data frame matching the input medcodes_data with the Read codes and optional description columns merged in.
medcodes_to_read <- function(medcodes_data, lookup_table, medcodes_name = "medcode", lookup_readcodes = "readcode", lookup_medcodes = "medcode", description = TRUE){
if(c(lookup_readcodes, lookup_medcodes) %in% names(lookup_table) && medcodes_name %in% names(medcodes_data)){
if(!description) lookup_table <- lookup_table[, c(lookup_medcodes, lookup_readcodes)]
if(medcodes_name != lookup_medcodes) names(lookup_table)[names(lookup_table) == lookup_medcodes] <- medcodes_name
if(intersect(names(lookup_table), names(medcodes_data)) != medcodes_name) warning("Name conflicts in data and lookup. output names may not be sane!")
merge(medcodes_data, lookup_table, all.x = TRUE, by = medcodes_name)
} else stop("Names in lookup/data do not match those specified")
}
#' Translate Read/Oxmis codes to CPRD medcodes
#'
#' This function accepts a data frame with a column for Read/Oxmis codes and merges with a medical lookup table to give columns for CPRD medcodes and optional descriptions
#'
#' Note that if the names of the Read/Oxmis codes columns are different in the data and the lookup table, the name in the data is retained
#' To maintain sanity, a warning will be given to inform of are any name conflicts between the input data and the lookup
#'
#' @export
#'
#' @param readcodes_data a dataframe with a column matching medcodes_name
#' @param lookup_table a dataframe with columns matching lookup_readcodes and lookup_medcodes
#' @param readcodes_name character name of the Read codes column in readcodes_data
#' @param lookup_readcodes character name of the Read codes column in the lookup_table
#' @param lookup_medcodes character name of the CPRD medcodes column in the lookup_table
#' @param description logical Should description and other categories from the lookup table also be included?
#' @return a data frame matching the input medcodes_data with the Read codes and optional description columns merged in.
read_to_medcodes <- function(readcodes_data, lookup_table, readcodes_name = "readcode",
lookup_readcodes = "readcode", lookup_medcodes = "medcode", description){
if(c(lookup_readcodes, lookup_medcodes) %in% names(lookup_table) && readcodes_name %in% names(readcodes_data)){
if(!description) lookup_table <- lookup_table[, c(lookup_medcodes, lookup_readcodes)]
if(readcodes_name != lookup_readcodes) names(lookup_table)[names(lookup_table) == lookup_readcodes] <- readcodes_name
names_in_both <- intersect(names(lookup_table), names(readcodes_data))
if(length(names_in_both) > 1) warning("Name conflicts in data and lookup. output names may not be sane!")
out <- merge(readcodes_data, lookup_table, all.x = TRUE, by = readcodes_name)
out[!is.na(out[[lookup_medcodes]]),]
} else stop("Names in lookup/data do not match those specified")
}
|
3baf425e096132ee90509f2bcf3eaa05546310aa
|
642015754f6334c883d87fc35d4ab83e3e1f2f5c
|
/metacell/scrdb/internal_tests/test_datasets.R
|
ea3821389431ef69ee15de81e1ad3a49afac56c2
|
[] |
no_license
|
tanaylab/hematopoiesis2018
|
343d226e56842e0ccac088c9ced77a0e4a843e7e
|
5b83d8e5addbc827a39b85d12bdc5d03d5e97673
|
refs/heads/master
| 2020-07-17T14:08:29.587073
| 2018-06-19T07:18:38
| 2018-06-19T07:18:38
| 206,033,624
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 904
|
r
|
test_datasets.R
|
source("./tests/testthat//workflow.R")
test_all = function(label="base", # what are we testing now? will be part of the output pathe, should be a valid sub-directory name (no "/").
datasets = c("e9", "hsc_tier3", "melanoma"), #all contain a matrix called umis
datadir = "/net/mraid14/export/data/users/atanay/proj/scmat/datasets/",
outdir = "/net/mraid14/export/data/users/atanay/proj/scmat/tests/"){
for(ds in datasets) {
one_test(ds, label, datadir, outdir)
}
}
one_test = function(ds, label,
datadir = "/net/mraid14/export/data/users/atanay/proj/scmat/datasets/",
outdir = "/net/mraid14/export/data/users/atanay/proj/scmat/tests/", nplots=100) {
load(paste(datadir, ds, ".Rda", sep=""))
call_workflow_tests(umis,label = label, basedir = paste(outdir, ds, sep="/"), nplots = nplots)
}
|
726353cc692d0ba2ba31ee5b6a0d4041ce9a36a9
|
2693a682078fe71bed78997f82b71b82c0abd0ad
|
/modules/emulator/man/jump.Rd
|
1e3b9d1515d89a0933cfd0dc228aef1435d98b12
|
[
"NCSA",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
ashiklom/pecan
|
642a122873c9bca4f7ac60f6f260f490f15692e4
|
52bb31866810e2c93ddf540f2065f41ec008627b
|
refs/heads/develop
| 2023-04-01T11:39:16.235662
| 2021-05-24T22:36:04
| 2021-05-24T22:36:04
| 28,980,311
| 3
| 0
|
NOASSERTION
| 2023-04-01T20:08:15
| 2015-01-08T18:44:03
|
R
|
UTF-8
|
R
| false
| true
| 238
|
rd
|
jump.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/jump.R
\name{jump}
\alias{jump}
\title{jump}
\usage{
jump(ic = 0, rate = 0.4, ...)
}
\arguments{
\item{rate}{}
}
\description{
jump
}
\author{
Michael Dietze
}
|
d0bc70877bda77f2e6c2ea875fe23c6fcaf6d022
|
615dd5f834a08734a2ec9586233a7a8dfaf7d2dd
|
/server.R
|
a858433960429c552cca1e3a282b14cd8b51b344
|
[] |
no_license
|
lingani/DS_CapstoneProject
|
ba9077902e32b886e95426bc50d1f8d4a3a9653c
|
fd589312034bde278c4fac93bbb4a204f90f3ee2
|
refs/heads/master
| 2020-05-18T07:37:41.657407
| 2015-04-26T04:05:55
| 2015-04-26T04:05:55
| 34,597,197
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 952
|
r
|
server.R
|
# This is the server logic for a Shiny web application.
# You can find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com
#
library(shiny)
devtools::install_github ("lingani/swiftcap")
library(swiftcap)
data(model)
shinyServer(function(input, output, clientData, session) {
pred <- reactive({
s <- paste(input$textfield)
s <- paste(s, sep = ' ', collapse = ' ')
predict (model, s)
})
output$predictions <- renderText({
pre <- pred()
s <- pre$word
ss <- paste0 ("(", pre$rank, ")", pre$word)
ss <- paste(ss, sep = ', ', collapse = ' ')
})
output$phonePlot <- renderPlot({
pre <- pred()
pre$word2 <- reorder(pre$word, pre$p)
ggplot(pre, aes(x=word2, y=p)) +
geom_bar(stat = "identity", position="stack") +
coord_flip() +
labs(title="The most likely next words and the probability of each as calculated by the model")
})
})
|
2592586ca27054b8c9361efbb4fe2328ceaee4d8
|
afc0d3af1c1600408eee99e1dc75d76e16a255e9
|
/keep_potential_hits.R
|
2ae633d07fc068ef6d5280c40088521aeaa876b6
|
[
"BSD-3-Clause"
] |
permissive
|
ruppinlab/tcga-microbiome-prediction
|
d2ac408c2b46ca997839c154400f4ccd9b9552fb
|
6f90aa76e41afa3689037a620258f4e6f0dabded
|
refs/heads/master
| 2023-04-08T05:01:19.436964
| 2022-06-04T14:10:28
| 2022-06-04T14:10:28
| 280,190,541
| 15
| 8
| null | null | null | null |
UTF-8
|
R
| false
| false
| 469
|
r
|
keep_potential_hits.R
|
# Keep comparisons that have a p-value (p_adj is not NA) and for which
# the comparison vs. clinical covariates is in the right direction.
suppressPackageStartupMessages({
library(dplyr)
library(readr)
})
args <- commandArgs(trailingOnly = TRUE)
results_table <- read_tsv(args, col_types = cols())
results_table <- results_table %>%
filter(!is.na(p_adj) & p_greater <= 0.05) %>%
arrange(analysis, features, how, desc(avg_test)) %>%
format_tsv() %>%
cat()
|
b7308a134c63f5f7805ee6a04e8edba78e5d077f
|
bb54e684f4d38ab7762aefa24e3a3cbf9a6c8dcd
|
/R/addCronjob.R
|
cf66b6bafc5fba2a41018dda23d4c8d05b84f279
|
[] |
no_license
|
ebailey78/crontabR
|
385cec7ac97a8719590c6da0aa3d4d8546912376
|
b072ecc6a679c23aaea7618fcf34d3661b4a6605
|
refs/heads/master
| 2020-05-22T01:16:47.456220
| 2019-05-31T18:23:13
| 2019-05-31T18:23:13
| 59,335,938
| 3
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,188
|
r
|
addCronjob.R
|
#'Task Scheduling
#'
#'Add/remove a cronjob to automate an R script to your personal crontab
#'
#'@rdname task_scheduling
#'
#'@param name A unique name for this cronjob
#'@param desc A description of what the script does
#'@param env_vars A list of environment variables that need to be set for this cronjob
#'@param scheduled_time A list or string describing when the task should be run.
#'@param script_path The filepath to the script you want to automate
#'@param overwrite If the cronjob already exists, should it be overwritten?
#'@param verbose Should extra messages be displayed while the cronjob is being built?
#'@param warn Should errors stop the function or just give an warning?
#'@param bashrc Should the user's .bashrc file be loaded before running the script?
#'@param logLevel What is the minimum message level that should be logged?
#'@param textLevel What is the minimul message level that should be texted, if texting is enabled?
#'
#'@details
#'\code{cron} does not start a shell and therefore doesn't load environment variables that would normally get loaded. Use
#'\code{env.var} to set variables that are needed by your script and/or set \code{bashrc = TRUE} to load the user's
#'.bashrc file each time before the script is run.
#'
#'\code{scheduled_time} should be either a named list containing any combination of \code{minute} (0-59), \code{hour} (0-23),
#'\code{day_of_month}(1-31), \code{month}(1-12)(Jan-Dec), \code{day_of_week}(0-7)(Sun-Sat) or a properly formatted cron string
#'For example, \code{scheduled_time = list(minute=30, hour=7, day_of_week=2)} would result in the task being scheduled for
#'7:30AM every Tuesday. \code{scheduled_time = "30 7 * * 2"} would accomplish the same thing.
#'
#'\code{script_path} should point to the location of a script you wish to automate. The script will be copied to
#'the \code{.crontabR} directory in your home directory. Additional code will be copied to the beginning and end
#'of the script so that \code{crontabR}'s logging functions will work. It is this modified copy of the script
#'that will be run by \code{crontabR}.
#'
#'@export
addCronjob <- function(name, desc = NULL, env_vars, scheduled_time, script_path,
overwrite = FALSE, verbose = FALSE, warn = FALSE, bashrc = TRUE,
logLevel = "info", textLevel = "none") {
name <- formatNames(name, verbose)
scheduled_time <- formatScheduledTime(scheduled_time)
if(cronjobExists(name) & !overwrite) {
err <- paste0("Cronjob already exists. Set `overwrite = TRUE` to overwrite the existing cronjob or give this cronjob a different name.")
if(warn) {
warning(err)
return(FALSE)
} else {
stop(err)
}
} else {
if(cronjobExists(name)) deleteCronjob(name)
if(processScript(name, desc, script_path, overwrite, warn = warn, logLevel = logLevel, textLevel = textLevel)) {
cronjob <- writeCronjob(name, desc, env_vars, scheduled_time, bashrc, logLevel, textLevel)
crontab <- readCrontab()
crontab <- c(crontab, cronjob)
writeCrontab(crontab)
if(verbose) message("Cronjob: ", name, " added to crontab.")
return(TRUE)
}
}
}
|
a5fa02e79019197fac0c39dffd2d8c4d401f97d6
|
b8652ccef6a738eaff1658f1ccc22ebcaefded75
|
/plot3.R
|
87e70f7ebc4a4fe45532cc30c503f81fac56bc3a
|
[] |
no_license
|
lifan0127/ExData_Plotting1
|
81a77449cab34708bc786ce59b9f127efa900964
|
7a68037c4f09e17281ed1da32cfc439c349d4c37
|
refs/heads/master
| 2020-12-11T01:40:41.329411
| 2014-05-11T19:28:26
| 2014-05-11T19:28:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,100
|
r
|
plot3.R
|
# Coursera Data Science Specialization (JHU)
# 4. Exploratory Data Analysis
# Fan Li
# 5/11/2014
# Import data
library(lubridate)
data <- read.table("household_power_consumption.txt",
header=TRUE,
sep=";",
nrows=2500000,
as.is=TRUE)
# Convert to date/time format
data$Date.Time <- dmy_hms(paste(data$Date, data$Time))
data$Date <- data$Time <- NULL
# Subset data
select.data <- subset(data, as.Date(Date.Time)=="2007-02-01" | as.Date(Date.Time)=="2007-02-02")
# Replace "?" with NA
select.data[select.data=="?"] <- NA
select.data[, -8] <- apply(select.data[, -8], 2, as.numeric)
# Create Plot 3
png(file="plot3.png")
with(select.data, {
plot(Date.Time, Sub_metering_1,
col="black",
type="l",
xlab="",
ylab="Energy sub metering")
lines(Date.Time, Sub_metering_2,
col="red",
type="l")
lines(Date.Time, Sub_metering_3,
col="blue",
type="l")
legend("topright",lty=1, col=c("black", "red", "blue"),
legend=colnames(select.data[5:7]))
})
dev.off()
|
d3ea63a1ab1188b5a7b4ce771b5197d93e12b28f
|
4bfe6f2e9226f8b27b3c0c3a8160135e7d336b5b
|
/man/lm_outliers.Rd
|
bb2951884445a2ad692e00a936b2b717522a00b1
|
[
"MIT"
] |
permissive
|
cedricbatailler/marguerite
|
7f905a8cef0b4744a7600d690ecc312a0bc5316d
|
301aafc5243898bb5338260ea07b44102d772aa4
|
refs/heads/main
| 2022-06-24T04:25:34.721092
| 2022-06-13T11:04:56
| 2022-06-13T11:04:56
| 292,825,108
| 1
| 0
|
NOASSERTION
| 2022-06-13T11:04:57
| 2020-09-04T10:58:53
|
R
|
UTF-8
|
R
| false
| true
| 1,115
|
rd
|
lm_outliers.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/lm_outliers.R
\name{lm_outliers}
\alias{lm_outliers}
\title{Returns outlier indices}
\usage{
lm_outliers(data, formula, id, verbose = FALSE)
}
\arguments{
\item{data}{A data.frame.}
\item{formula}{A model formula.}
\item{id}{A column name from \code{data} used to identify observations (optional).}
\item{verbose}{A boolean indicating whether the function should call print on
the output. Useful when using \code{lm_outliers} with pipes.}
}
\description{
Returns a \code{data.frame} with outlier indices for a specific \code{lm}
model. Indices include studentized residuals, residuals' cook's distance,
and residuals' hat values.
}
\examples{
mtcars |>
lm_outliers(mpg ~ disp) |>
lm(mpg ~ disp,
data = _)
}
\references{
Judd, C. M., McClelland, G. H., & Ryan, C. S. (2009). Data
analysis: a model comparison approach (2nd ed). New York ; Hove: Routledge.
}
\author{
Dominique Muller, \email{dominique.muller@univ-grenoble-alpes.fr}
CΓ©dric Batailler, \email{cedric.batailler@univ-grenoble-alpes.fr}
}
\keyword{outliers}
|
5c5c57f9c59f096a040a61b8ae1b11c7ec908d6e
|
d8a28f2f5a8d532da596a433aa75348187befa76
|
/functions/func_openEVI.R
|
ebb75f3dde1ed0800d94c4b212765e28bea4b0b4
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
nreinicke/EVIPro-Fleet-Gen
|
9340e5139024a7e1997ec5c55e89df90a946126d
|
3892d9eefeaa57801ff3daa12b18fa2383d74220
|
refs/heads/master
| 2023-01-10T15:45:36.795840
| 2020-07-10T19:20:13
| 2020-07-10T19:20:13
| 283,615,589
| 1
| 0
|
NOASSERTION
| 2020-07-29T22:34:45
| 2020-07-29T22:34:44
| null |
UTF-8
|
R
| false
| false
| 2,561
|
r
|
func_openEVI.R
|
# Author: Schatz Energy Research Center
# Original Version: Micah Wright
# Edits: Jerome Carman, Max Blasdel
# Version: 2.1
# Description: wrapper function to create a PEV fleet
# Required Variables
# evi_raw: data table of EVI-Pro charge session data
# fleet: integer specifying the size of the desired fleet
# pev: length 4 vector, type double and sum(pev)=1, indicating the proportion of PHEV20, PHEV50, BEV100, and BEV250
# dvmt: number (type double) specifying the mean daily vmt for the fleet
# pref: length 2 vector, type double and sum(pref)=1, indicating the proportion of drivers who prefer home or work
# home: length 3 vector, type double and sum(home)=1, indicating the proportion of fleet with access to level 1, 2, qnd 3 home charging stations
# work: length 2 vector, type double and sum(work)=1, indicating the proportion of fleet with access to level 1 and 2 work charging stations
# loc_class: string of value either "urban" or "rural". Impacts dvmt distribution.
# veh_class: length 2 vector, type double and sum(veh_class)=1, indicating proportion Sedan and SUV vehicles
# Version History
# 1.0: JKC added language to header and added comments.
# 2.0: JKC restructured to allow for embedded parallelization and looping through permutations of weights
# 2.1: JKC and MB edited to allow for use with run-all.R wrapper script.
# library(data.table)
openEVI <- function(evi_raw,
fleet = c(1000),
pev = c(0.25,0.25,0.25,0.25),
dvmt = c(30),
pref = c(0.8,0.2),
home = c(0.20,0.70,0.1),
work = c(0,1),
loc_class = "urban",
veh_class = c(0.8,0.2)) {
#Create data table of fleet weights that will work with evi_fleetGen()
fleet_weights <- create_fleet_weights(pev, # change for suvs
pref,
home,
work,
veh_class)
#Create fleet
# step through below function
evi_fleet <- evi_fleetGen(evi_raw,
fleet_size = fleet,
weights = fleet_weights, # list of five weights
mean_vmt = dvmt,
bin_width = 10, #Do not change this from 10 unless evi_load_profiles are re-run with a different bin width
loc_class = loc_class)
# Return fleet
return(evi_fleet)
}
|
833ed0854b11105295be9c28f8f1c4627639dabf
|
9b230b93b14b1dbdf606044f31cdc934c2849894
|
/three_way_admixture/finemap_distributions_ld.R
|
6eaa4146798b24563d1c6420451601d969b132c0
|
[] |
no_license
|
marcustutert/thesis_code
|
237362acaf4b37b250db35ed63146f3f816d6642
|
fd058f2bd46b36451e4047e18fc67036749b816a
|
refs/heads/main
| 2023-06-23T09:21:22.398256
| 2021-07-20T10:26:30
| 2021-07-20T10:26:30
| 354,377,182
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,470
|
r
|
finemap_distributions_ld.R
|
#Run FINEMAP across the distributions of LD
#We will do this (eventually) with summary statistic imputation added in, but for now just using the true sumstats data
#We need to calculate the FINEMAP statistics across the true GWAS haplotypes, the different reference panels, including those combined- and my weighted reference panel;
#Read in snakemake params
regions = snakemake@params$regions
#Read in GWAS panel (this stays constant through the samples)
gwas_case_haplotypes = t(as.matrix(read.table(sprintf("hapgen2/gwas_region_%s.cases.haps",regions, header = T)))) #Read in the GWAS haplotypes (cases and control)
gwas_control_haplotypes = t(as.matrix(read.table(sprintf("hapgen2/gwas_region_%s.controls.haps",regions, header = T)))) #Read in the GWAS haplotypes (cases and control)
#Merge together the haplotypes
gwas_haplotypes = rbind(gwas_case_haplotypes,gwas_control_haplotypes)
#Read in the TRUE sumstats from SNPTEST
true_sumstats = read.table(sprintf("snptest/sumstats_gwas_region_%s",regions), header = T, skip = 10, stringsAsFactors = F)
#Loop across the LD distribution samples
nSamples = 100
for (i in 1:nSamples) {
#### Create master file ####
master_colnames = paste("z","ld","snp","config","cred","log","n_samples",sep = ";") #Get the colnames
true_sumstats_inferred_ld = paste(sprintf("finemap_distributions/inferred_ld_true_sumstats_region_%s_sample_%s.z", regions,i),
sprintf("finemap_distributions/inferred_ld_true_sumstats_region_%s_sample_%s.ld", regions,i),
sprintf("finemap_distributions/inferred_ld_true_sumstats_region_%s_sample_%s.snp", regions,i),
sprintf("finemap_distributions/inferred_ld_true_sumstats_region_%s_sample_%s.config", regions,i),
sprintf("finemap_distributions/inferred_ld_true_sumstats_region_%s_sample_%s.cred",regions,i),
sprintf("finemap_distributions/inferred_ld_true_sumstats_region_%s_sample_%s.log",regions,i),
10000,
sep = ";")
#Rbind all the data together
write.table(rbind(master_colnames,
true_sumstats_inferred_ld),
sprintf("finemap_distributions/gwas_region_%s_sample_%s_master",regions,i),col.names = F, row.names = F, quote = F)
#### Create Z file ####
#To do this each of the 3 elements in these vectors will correspond to:
rsid = replicate(1,true_sumstats$rsid)
chromosome = replicate(1,true_sumstats$chromosome)
position = replicate(1,true_sumstats$position)
allele1 = replicate(1,true_sumstats$alleleA)
allele2 = replicate(1,true_sumstats$alleleB)
maf = replicate(1,rep(0.420,length(true_sumstats$rsid))) #Nice
beta = cbind(true_sumstats$frequentist_add_beta_1)
se = cbind(true_sumstats$frequentist_add_se_1)
#Bind this data all together into a matrix for all three cases
true_sumstats_z = cbind(rsid[,1],chromosome[,1],position[,1],allele1[,1],allele2[,1],maf[,1],beta[,1],se[,1])
colnames(true_sumstats_z) = c("rsid","chromosome","position","allele1","allele2","maf","beta","se")
#Note that we will need to restrict any variants that are NA in the sumstats (because HAPGEN create far too low freq variants to pick up)
#Find a way to fix this!
low_freq_snps = which(is.na(beta[,1]))
#Remove this SNPs from all 3 z files
if (length(low_freq_snps)>0) {
true_sumstats_z = true_sumstats_z[-low_freq_snps,]
}
#Extract each row for each of the three cases
write.table(true_sumstats_z, file = sprintf("finemap_distributions/inferred_ld_true_sumstats_region_%s_sample_%s.z",regions,i),quote = F, row.names = F, col.names = T)
#Read in the inferred LD panel:
inferred_LD = readRDS(sprintf("distribution_ld_results/inferred_LD_sample_%s_region_%s",i,regions))
write.table(inferred_LD, file = sprintf("finemap_distributions/inferred_ld_true_sumstats_region_%s_sample_%s.ld", regions,i), quote = F, col.names = F, row.names = F)
#####RUN FINEMAP######
#Do this across different configurations of reference panel LD and my inferred LD
system(sprintf("/well/mcvean/mtutert/software/FINEMAP/finemap_v1.4_x86_64 --sss --in-files finemap_distributions/gwas_region_%s_sample_%s_master --n-causal-snps 3 --log",regions,i))
}
|
feec6a830f222cd9776c5454a3f35fe5fe959447
|
99e57cd556aef28c5c753895589372eed8f5cab7
|
/man/raw_to_char.Rd
|
81e10f1f7ed19973b25ffc79799a610075a2271f
|
[
"MIT"
] |
permissive
|
Athospd/forkliftr
|
83a051bcbe9859f4b0c91786237993d5ee0bb4d4
|
a88f89fa4793e3fcc2362ea3b3a3be028fa865de
|
refs/heads/master
| 2020-04-05T12:10:25.139392
| 2017-08-13T20:20:41
| 2017-08-13T20:20:41
| 95,243,073
| 3
| 1
| null | 2017-07-03T22:54:23
| 2017-06-23T17:47:50
|
R
|
UTF-8
|
R
| false
| true
| 337
|
rd
|
raw_to_char.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/guess_aux.R
\name{raw_to_char}
\alias{raw_to_char}
\title{Auxiliar function to convert vector of raws to chars}
\usage{
raw_to_char(raw)
}
\arguments{
\item{raw}{Vector of raw characters}
}
\description{
Auxiliar function to convert vector of raws to chars
}
|
074368d196819c36425220b67e274e874d77d727
|
98ea0c910eedcb82659f23ef9a5811c2e4fdca26
|
/cachematrix.R
|
3dc5474a4a6561f7affce9f3de466f2ced804210
|
[] |
no_license
|
Shivali-Vij/ProgrammingAssignment2
|
ee208ebaad865d7b9c670defdecb74c1387f4c4b
|
8775571499467ccb84c66ba3cc5bf67fa8762ac8
|
refs/heads/master
| 2021-01-22T19:23:11.814161
| 2014-10-25T17:55:12
| 2014-10-25T17:55:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,322
|
r
|
cachematrix.R
|
## Matrix inversion is usually a costly computation and their may be some benefit to
##caching the inverse of a matrix
##rather than compute it repeatedly
## function makeCacheMatrix creates a special "matrix" object that can cache its inverse.
makeCacheMatrix <- function(x = matrix()) {
m<-matrix()
set <- function(y) { ## Method to see the matrix
## This function sets the cache m to null
##again if the matrix changes
x <<- y
m <<- NULL
}
get <- function() { ## Method that returns the matrix
x
}
setinverse<-function(inverse){ ##Method to set the inverse of matrix
m<<-inverse
}
getinverse <- function(){ ## Method to return the inverse of matrix
m
}
## To return the list of methods
list(set=set, get=get,setinverse=setinverse,getinverse=getinverse)
}## End of makeCacheMatrix
## this function checks if cache exits. If the inverse has already been calculated
## and the matrix has notchanged),
## then the "cachesolve" should retrieve the inverse from the cache
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getinverse()
## Just return the inverse if its already set
if(!is.null(m)) {
message("We have already calculated this inverse. Fetching cached data")
return(m)
}
## Get the matrix from our object
matrix <- x$get()
inverse<-matrix()
## Calculate the inverse using matrix multiplication
inverse <- solve(matrix)
message("Calculating inverse")
## Set the inverse to the object
x$setinverse(inverse)
message("Caching the calculation")
## Return the matrix
inverse
}
##########################################################
##########################################################
#To see it run,
#Run the code as follows:
#
#
#t<-makeCacheMatrix()
#t$set(matrix(1:4, 2, 2))
# t$get()
#> t$get()
# [,1] [,2]
#[1,] 1 3
#[2,] 2 4
#> cacheSolve(t)
#Calculating inverse
#Caching the calculation
# [,1] [,2]
#[1,] -2 1.5
#[2,] 1 -0.5
#> cacheSolve(t)
#We have already calculated this inverse. Fetching cached data
# [,1] [,2]
#[1,] -2 1.5
#[2,] 1 -0.5
#>
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
|
e39812c52c7665cb07ba16187ad9440419191207
|
797bdd4783d74de145977a64c39ec4b9b1b58e87
|
/uusi_tapa.R
|
4696b1039ce3d285f18889a7f2d1b244491327f5
|
[] |
no_license
|
LCHawk/op
|
bcbca1661fc234924a62486915d747c737853083
|
b17a62bdfc7923772d3baeb2da717e95b0aa9a07
|
refs/heads/master
| 2022-11-23T11:29:01.764992
| 2020-07-31T13:50:56
| 2020-07-31T13:50:56
| 283,794,929
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,811
|
r
|
uusi_tapa.R
|
library(tidyverse)
library(rvest)
pankit <- read_html("https://www.op.fi/op-ryhma/osuuspankit/osuuspankkien-omat-sivut")
pankit <- pankit %>% html_nodes("a") %>% html_attr("href")
pankit <- pankit[grepl("www.op.fi",pankit)]
hn<-list()
#TehdÀÀn aluksi yhdellÀ ja tutkitaan hallintoa
for(i in 1:length(pankit)){
pankki <- pankit[i]
pankki_nimi<-unlist(str_split(pankki,"/"))[4]
if(pankki_nimi=="kuortaneen-osuuspankki"){
pankki_nimi<-"op-kuortane"
}
#TehdÀÀn helsigin kohdalla poikkeus, koska ei ole samaa muotoa
if(pankki_nimi %in% c("op-helsinki","op-korsnas","op-suomenselka")){
next
}
pankki <- read_html(paste0("https://www.op.fi/web/",pankki_nimi,"/hallinto"))
print(c(pankki_nimi,i))
hallintoneuvosto <- pankki %>%
html_table(fill = T)
hallintoneuvosto <- hallintoneuvosto[[1]]
hallintoneuvosto$Pankki <- pankki_nimi
print(paste("Pankki",pankki_nimi,"luku onnistui."))
hn[[i]]<-hallintoneuvosto
# if(i == 1){
# hn <- hallintoneuvosto
# }else{
# print(paste("Pankki",pankki_nimi,"liitos yritys."))
# hn <- hn %>% bind_rows(hallintoneuvosto)
# print(paste("Pankki",pankki_nimi,"liitos onnistui"))
#
# }
}
#Editoidaan aineistoa
hallintoneuvosto <- hn
#Kirjoitettava uudelleen, koska lista.
# hallintoneuvosto <- hallintoneuvosto %>%
# mutate(Nimi = coalesce(Nimi,Namn,X1), Ammatti = coalesce(Ammatti, Yrke,X2),
# Kotipaikka = coalesce(Kotipaikka,Hemort,X3),
# Toimikausi = coalesce(Toimikausi,Mandatperiod, X4))
# #Poistetaan ylimÀÀrÀiset
# hallintoneuvosto <- hallintoneuvosto %>% select(Nimi,Ammatti,Kotipaikka,Toimikausi,Pankki)
# #Poista ne, joissa rivillΓ€ mainitaan sana nimi nimi-sarakkeessa. NiitΓ€ on tullut.
# #Aluksi voitaisiin laskea eri kuntien ja ammattien mÀÀrÀt
#
|
3e0482c0f673dcb29063b5f067283e6d8199a588
|
8f061026073ec0dbfbb36342d560db8d85ec6970
|
/Hands-on/0.Profiling/Profiling.R
|
5009377762275a5290365642304f56dce7e9abe0
|
[] |
no_license
|
bbrydsoe/R_for_HPC
|
7b4f287521dc9be1112482d5bf4ce3c269d6d0dd
|
796349a6d964f2dac44530329426bfb9b5bb7642
|
refs/heads/main
| 2023-03-08T20:22:15.845637
| 2021-02-26T07:44:07
| 2021-02-26T07:44:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,855
|
r
|
Profiling.R
|
#---
#title: "Exercises"
#author: "Pedro Ojeda, Birgitte BrydsΓΆ, Mirko Myllykoski"
#date: "Feb., 2021"
#output: html_document
#---
## 1. Exercise
#Use the following template by filling the *FIXME* strings with the corresponding
#R code. In this exercise, you will use the **tictoc** package to time different
#parts of a R code and save the results in a log file:
library(*FIXME*) #We will use **tictoc** package
*FIXME*() #Clear the existing log file
*FIXME*("Total execution time") #Start the stopwatch for the entire code
*FIXME*("time: var init") #Start stopwatch for variables initialization
A <- matrix(1.0, 5000, 5000)
*FIXME*() #Stop stopwatch for variables initialization
sumcol <- function(B) {
*FIXME*("time: var init func") #Start stopwatch for variables initialization in function
l <- ncol(B) #obtain the number of columns
colsm <- rep(0,l) #create a vector to save the sums
*FIXME*(*FIXME*) #Stop stopwatch for variables initialization in function
*FIXME*("time: for loop") #Start stopwatch for loop
for(j in 1:l){
s <- 0
for(i in 1:l){
s <- s + B[i,j]
}
colsm[j] <- s
}
*FIXME*(*FIXME*) #Stop stopwatch for loop
return(colsm)
}
res1 <- sumcol(A)
*FIXME*(*FIXME*) #Stop stopwatch for entire code
*FIXME* <- *FIXME*() #Save the **tictoc** log file into a variable called *logfile*
#What is the most expensive part of this code?
## 2. Exercise
#In this problem you will use common packages to profile R code. Replace the *FIXME* strings
#with appropriate R code.
#Given the matrix A of ones with a size of 5000x5000:
A <- matrix(1.0, 5000, 5000)
#compare the profiling results of the following functions in a) and b).
#a) the user function *sumcol* computes the sum of the elements by columns
sumcol <- function(B) {
l <- ncol(B) #obtain the number of columns
colsm <- rep(0,l) #create a vector to save the sums
for(j in 1:l){
s <- 0
for(i in 1:l){
s <- s + B[i,j]
}
colsm[j] <- s
}
return(colsm)
}
*FIXME*("*FIXME*") #Start Rprof and write output in a filename called Rprofa.out
res1 <- *FIXME*(*FIXME*) #profile the sumcol function with the matrix A as input
*FIXME*(*FIXME*) #Finish Rprof profiling
*FIXME*Rprof("*FIXME") #view the profiling's summary of Rprof
#b) the R built-in *colSums* function for computing the sums of elements by columns
*FIXME*("*FIXME*") #Start Rprof and write output in a filename called Rprofb.out
res2 <- *FIXME*(*FIXME*) #profile the colSums function with the matrix A as input
*FIXME*(*FIXME*) #Finish Rprof profiling
summary*FIXME*("*FIXME*") #view the profiling's summary of Rprof
#* Are the performances of the two functions similar?
#* The two functions do the same calculation, why the performaces could differ?
## 3. Exercise
#**Challenge:** Do a benchmarking of the previous two functions by using rbenchmark
#and microbenchmark packages:
#initialize the matrix A and set function sumcol
A <- matrix(1.0, 5000, 5000)
sumcol <- function(B) {
l <- ncol(B) #obtain the number of columns
colsm <- rep(0,l) #create a vector to save the sums
for(j in 1:l){
s <- 0
for(i in 1:l){
s <- s + B[i,j]
}
colsm[j] <- s
}
return(colsm)
}
library(*FIXME*) #load rbenchmark package
#benchmark sumcol and colSums functions using the matrix A for 10 replicas
res3 <- *FIXME*(*FIXME*(*FIXME*), *FIXME*(*FIXME*), replications=*FIXME*)
res3
library(*FIXME*) #load microbenchmark package
#benchmark sumcol and colSums functions using the matrix A for 10 replicas
res4 <- *FIXME*(*FIXME*(*FIXME*), *FIXME*(*FIXME*), times=*FIXME*)
res4
|
f3500847747d39242bfd542c08667b04a7148466
|
b4d40b3981527b4879d1c4e9411c8d051ed1539c
|
/corr.R
|
02fed933051e047364ff45ace1be141b4e7eef83
|
[] |
no_license
|
victoriaehall/datasciencecoursera
|
47164cf3a479abbb51f5cfeea4688d38c1252e1c
|
31d88289652a247c3b8782e6ba9dbbe82984e392
|
refs/heads/master
| 2020-05-20T01:10:31.604457
| 2015-02-15T21:53:43
| 2015-02-15T21:53:43
| 28,843,165
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 638
|
r
|
corr.R
|
setwd("/Users/victoriahall/datasciencecoursera")
corr <- function(directory, threshold=0) {
allfiles <- list.files(directory, full.names=TRUE)
mydata <- data.frame()
final <- numeric()
for (i in 1:length(allfiles)) {
current_file <- read.csv(allfiles[i])
good <- complete.cases(current_file)
cases <- sum(good)
if(cases > threshold) {
x <- current_file[good,2]
y <- current_file[good,3]
final[i] <- cor(x,y)
}
}
final[!is.na(final)]
}
|
f43a72eae333ce4a3ebd2fd392d0f6b19a4c015a
|
517388003b7b82681c000be24fa8538c4c8505fa
|
/HW4/hw4.R
|
dad0e3929baba8014ea46c27f1c8368199a79c32
|
[] |
no_license
|
liuyangyu0622/STAT347
|
728afa114a40baa521331a96663b37f7d30bc497
|
ff4f67aeff36d01a8d75f380cfeb250ce5a01b13
|
refs/heads/master
| 2021-04-28T18:36:54.557392
| 2018-02-17T17:44:59
| 2018-02-17T17:44:59
| 121,877,293
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,674
|
r
|
hw4.R
|
# 1(a)
data(leafblotch)
View(leafblotch)
str(leafblotch)
plot(blotch~as.numeric(site),leafblotch,xlab="site",main="blotch against site")
plot(blotch~as.numeric(variety),leafblotch,xlab="variety",main="blotch against variety")
# 1(b)
leafblotch$affected <- leafblotch$blotch*10000
leafblotch$unaffected <- 10000 - leafblotch$affected
View(leafblotch)
fit1b <- glm(blotch~site+variety,leafblotch,family = binomial)
summary(fit1b)
df.residual(fit1b)
deviance(fit1b)
pchisq(deviance(fit1b),72,lower=F)
# 1(c)
fit1c <- glm(blotch~site+variety,leafblotch,family = quasibinomial)
sumary(fit1c)
(sigma2 <- sum(residuals(fit1b,type = "pearson")^2)/df.residual(fit1b))
# 1(d)
plot(residuals(fit1c)~fitted(fit1c),main="Residuals vs Predicted Values",
xlab="Predicted Values",ylab="Residuals")
# fitted or predict?
plot(residuals(fit1c)~predict(fit1c),main="Residuals vs Predicted Values",
xlab="Predicted Values",ylab="Residuals")
# 1(e)
miu = 1/(fitted(fit1c)*(1-fitted(fit1c)))
fit_1e = glm(blotch~site+variety,family=quasibinomial,data=leafblotch,weights = miu)
plot(fit_1e)
summary(fit_1e)
# 1(f)
miu = c(rep(0,90))
for (i in 1:90) {
miu[i] = fitted(meed)[i]^2*(1-fitted(meed)[i])^2
}
fitt = glm(cbind(blotch,1-blotch)~site+variety,family=quasibinomial,data=leafblotch)
fit_1f = glm(cbind(blotch,1-blotch)~site+variety,family=binomial,data=leafblotch,weights = miu*(1-miu))
summary(fitt)
# 3(a)
library(faraway)
library(ggplot2)
library(lme4)
library(RLRsim)
data(lawn)
View(lawn)
ggplot(lawn, aes(y=time, x=machine, shape=manufact, col=speed))+
geom_point()+xlab("machine")+
ggtitle("time against machine\ngrouped by speed and manufacturers")
# 3(b)
fit3b <- lm(time~manufact+machine+speed,lawn)
sumary(fit3b)
# 3(c)
fit3c <- lmer(time~manufact+speed+manufact:speed+(1|machine),lawn)
summary(fit3c)
# 3(d)
# test the significance of interaction
fit3c1 <- lmer(time~manufact+speed+manufact:speed+(1|machine),lawn,REML = F)
fit3d1 <- lmer(time~manufact+speed+(1|machine),lawn,REML = F)
anova(fit3d1,fit3c1)
# p-value > 0.05, cannot reject the null, we can remove interaction
fit3d2 <- lmer(time~speed+(1|machine),lawn,REML = F)
fit3d3 <- lmer(time~manufact+(1|machine),lawn,REML = F)
anova(fit3d2,fit3d1)
# p-value > 0.05, we can remove manufact
anova(fit3d3,fit3d1)
# p-value < 0.05, we cannot remove speed
fit3d <- lmer(time~speed+(1|machine),lawn,REML = F)
# 3(e) ?
fit3ef = lmer(time~speed+(1|machine),lawn)
fit3es = lm(time~speed,lawn)
exactLRT(fit3ef,fit3es)
# 3(f)
fit3f <- lmer(time~speed+(1|manufact)+(1|manufact:machine),lawn)
summary(fit3f3)
exactRLRT(fit3f1,fit3f,fit3f2)
exactRLRT(fit3f2,fit3f,fit3f1)
# 3(g)
confint(fit3f, method="boot")
|
c8e2d29b873c8424dfb25f26408064821d453411
|
661d4d3f14e14b699c697efc8db05a220ed40eb9
|
/mosaicApps/mosaicManipOriginal/R/mCI.R
|
95ba15939eb523c09daf58fec10e5fe7047c5b04
|
[] |
no_license
|
dtkaplan/MOSAIC-Summer-2015
|
60518bb08edb3c7165ddb5e74104ccdfdb1c0225
|
2f97827b9e09fccc7cc5679888fe3000d71fe1cc
|
refs/heads/master
| 2021-01-23T13:31:24.897643
| 2015-11-17T22:39:39
| 2015-11-17T22:39:39
| 35,576,261
| 0
| 1
| null | 2015-06-02T21:24:26
| 2015-05-13T21:58:29
|
R
|
UTF-8
|
R
| false
| false
| 4,845
|
r
|
mCI.R
|
#' Interactive applets to explore confidence interval coverage
#'
#' These applets allow the user explore the coverage of confidence intervals
#' computed from many random samples.
#'
#' Data for \code{mCIprop} is created using \code{rbinom}. The user may choose
#' to calculate confidence intervals using a Wald interval or an Agresti
#' interval by using the type of CI picker. There are sliders in the manipulate
#' box to interact with sample size, confidence level, true mean, number of
#' trials, and random seed. Number of trials increases the number of lines
#' plotted. The total number of confidence intervals not containing the true
#' mean, or "failed CIs", is printed above the plot.
#'
#' Known bugs: Color scheme may be redone, orange/chocolate1 may not be the
#' best color for failed CIs. Wald CIs "error" when true mean is near the edge
#' of the line and sample size is low, however this is more a product of the
#' Wald CI calculation than the program.
#'
#' @aliases mCIprop mCIt
#' @param ... additional arguments
#' @return A function that allows the user to explore confidence interval
#' coverage interactively.
#' @author Andrew Rich (\email{andrew.joseph.rich@@gmail.com}) and Daniel
#' Kaplan (\email{kaplan@@macalester.edu})
#' @keywords statistics
#' @examples
#'
#' if (require(manipulate)) {
#' mCIprop()
#' mCIt()
#' }
mCIprop <- function(...){
if(!require(manipulate))
stop("Must use a manipulate-compatible version of R, e.g. RStudio")
if (!require(lattice) | !require(grid)) stop("Missing packages.")
Wald=function(p.hat, n, conf.level, sd=sqrt(p.hat*(1-p.hat))){
error = (qnorm(.5+conf.level/2)*sd)/(sqrt(n))
return(list(lower = p.hat-error, upper = p.hat+error))
}
Agresti= function(p.hat, n, conf.level){
sd=sqrt(p.hat*(1-p.hat))
z = qnorm(.5+conf.level/2)
ntilde = n+z^2
ptilde = (p.hat*n + (z^2)/2)/ntilde
error = z*sqrt(ptilde*(1-ptilde)/ntilde)
return(list(lower=p.hat-error, upper=p.hat+error))
}
myFun=function(n=n, conf.level=0.95,p=p,ntrials=10,seed=125, int.type=Wald){
set.seed(seed)
# === start of panel function
mypanel=function(x,y){
outside = 0
for (trial in (ntrials:1) ) {
p.hat <- rbinom(1,size=n,prob=p)/n
int <- int.type(p.hat=p.hat,n=n,conf.level=conf.level)
lower.bound <- int[1]
upper.bound <- int[2]
panel.abline(v=p, col = "red")
panel.segments(0, trial, 1, trial, col='gray50')
panel.segments(x0=lower.bound,y0=trial,x1=upper.bound,y1=trial, lwd=5)
panel.text(c(lower.bound, upper.bound), c(trial,trial), c("(",")")) # OPTIONAL PARENTHENSES ARROWS
panel.points(p.hat, trial, pch = 16)
if(p<lower.bound|p>upper.bound){
lpoints(1.02, trial, pch = 8, col = "chocolate1", cex = 1.5)
outside=outside+1
}
}
popViewport()
grid.text(paste("Total failed CIs:", outside),
x=unit(.5, "npc"),
y=unit(.98, "npc"),
just = "center",
gp = gpar(fontsize=15, col="chocolate1"))
}
# === end of panel function
xyplot(0:1 ~ 0:1, panel = mypanel, type="n",
ylim=rev(c(0,max(ntrials+1,20))),
xlim=c(-.1, 1.1),
ylab="Trial Number",
xlab="Probability")
}
#==========
manipulate(myFun(n=n, conf.level=conf.level,p=p, ntrials=ntrials, seed=seed, int.type=int.type),
n = slider(5, 500, step = 1, initial=100, label = "Sample Size"),
conf.level = slider(.01, 1.00, step = .01, initial=0.95, label = "Confidence Level"),
p = slider(0,1, step = .01, initial=0.8, label = "True Mean"),
ntrials = slider(1, 100, step = 1, initial = 1, label = "Number of Trials"),
seed = slider(100,200, step=1, initial=125, label = "Random Seed"),
int.type = picker("Agresti"=Agresti,"Wald"=Wald, label = "Type of CI")
)
}
mCIt <- function(...){
ESTIMAND = 10
pickerList <- list(
list(rdist=rnorm, args=list(mean=ESTIMAND, sd=1)),
list(rdist=rnorm, args=list(mean=ESTIMAND, sd=3)),
list(rdist=rexp, args=list(rate=1/ESTIMAND)),
list(rdist=rchisq, args=list(df=ESTIMAND))
)
names(pickerList) <- c(
paste("Norm(",ESTIMAND,",1)", sep=''),
paste("Norm(",ESTIMAND,",3)", sep=''),
paste("Exp(1/",ESTIMAND,")",sep=""),
paste("Chisq(",ESTIMAND,")",sep="")
)
manipulate(
xYplot( Cbind(estimate, lower, upper) ~ sample,
data=CIsim(n=N, samples=SAMPLES, rdist=DIST$rdist, estimand = ESTIMAND, args = DIST$args),
groups=cover, ylim=c(ESTIMAND-WIDTH,ESTIMAND+WIDTH),
ylab="",
panel = function(x,y,...) {
panel.abline (h=ESTIMAND, col='gray50');
panel.xYplot(x,y,...)
}
),
N=slider(1,200,initial=20, label="sample size"),
SAMPLES = slider(1,200, initial=50, label="number of samples"),
DIST = picker(pickerList),
WIDTH = slider(1,2*ESTIMAND, initial=round(ESTIMAND/2), step=ESTIMAND/40)
)
}
|
2c75696b07568f226306ef7de0a115c920233d3c
|
a8aee44a8d388660d1747fecf0350076830ec753
|
/man/U_equation.Rd
|
17fefd0b89c685bb942e4aa831feae3a6735c8d5
|
[] |
no_license
|
ZexiCAI/TVQRLB
|
0f5cccadc95d1198ba5439711278eaac843722c0
|
fc91914df78e2f766da5623473009ce79f4a90a9
|
refs/heads/master
| 2020-04-12T22:55:13.567396
| 2019-12-29T10:47:15
| 2019-12-29T10:47:15
| 155,048,285
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,079
|
rd
|
U_equation.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/TVQRLB_main.R
\name{U_equation}
\alias{U_equation}
\title{Form the Estimating Equation}
\usage{
U_equation(beta, dataset, denom, qtile, weight, norm = TRUE)
}
\arguments{
\item{beta}{The parameter estimate.}
\item{dataset}{The survival data.}
\item{denom}{The denominator used in the estimating equation.}
\item{qtile}{The quantile level used to conduct the quantile regression.}
\item{weight}{The weight of each observation. Default is equal weights.}
\item{norm}{Whether the norm of the function value should be returned. \code{TRUE}: return the norm; \code{FALSE}: return the function value. Default is \code{TRUE}.}
}
\value{
This function returns the function value (a vector of length n+1) of the estimating equation evaluated at "beta" if norm = FALSE; otherwise returns the norm of it.
}
\description{
Set up an estimating equation.
}
\references{
Cai, Z. and Sit, T. (2018+),
"Quantile regression model with time-varying covariates under length-biased sampling,"
\emph{Working Paper}.
}
|
6cc4b832d4efdcbcb3d4684c82e38968299a3817
|
5dace2e2ef48e88eba95c8c07bbba7697cd9c042
|
/man/ihdengland.Rd
|
7c97c463c8a4c31c68e0eff28c4e3e4efd1d486c
|
[] |
no_license
|
kingwatam/disbayes
|
555be72a081d0fec1e4543e9d509f3bc8443a90b
|
67bcff25afbe083f299dec7affa0cbbebb481ccf
|
refs/heads/master
| 2023-06-11T07:42:22.872477
| 2021-07-07T10:14:20
| 2021-07-07T10:14:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,493
|
rd
|
ihdengland.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/disbayes-package.R
\docType{data}
\name{ihdengland}
\alias{ihdengland}
\title{Ischemic heart disease in England}
\format{
A data frame with columns:
\code{sex}: \code{"male"} or \code{"female"}.
\code{ageyr}. Year of age.
\code{location}. Name of the location, which is either a city region or region in England.
\code{num_mort}. Numerator behind the estimate of mortality
\code{num_inc}. Numerator behind the estimate of incidence
\code{num_prev}. Numerator behind the estimate of prevalence
\code{denom_mort}. Denominator behind the estimate of mortality
\code{denom_inc}. Denominator behind the estimate of incidence
\code{denom_prev}. Denominator behind the estimate of prevalence
}
\source{
Global Burden of Disease, 2017
}
\usage{
ihdengland
}
\description{
Ischemic heart disease in England
}
\details{
The data were processed to
* change the geography to refer to England city regions and the remaining English regions,
* change counts by 5-year age groups to estimated 1-year counts,
* obtain estimated numerators and denominators from the published point estimates and uncertainty intervals.
A point estimate of the risk is equivalent to the numerator divided by the denominator. The denominator is
related to the extent of uncertainty around this estimate.
The script used to do this is available from REF GITHUB TODO
}
\references{
TODO our paper when available
}
\keyword{datasets}
|
2fe47e53c223cb4de69b3145c05859445a8a7b0c
|
8d99e28aa5de124ef88e41a8bbe6d0fcaaefc9af
|
/man/revbayes.Rd
|
a92ee6c3786235e890ee72d4f28d3bf5f4117493
|
[] |
no_license
|
DomBennett/om..revbayes
|
13b596b82ee451a3acb8e717464fe68d4bd6bb21
|
74131b1debfd7aed6e72716f1d80ab8a46764b11
|
refs/heads/master
| 2020-04-22T16:53:05.262928
| 2019-10-25T13:05:57
| 2019-10-25T13:05:57
| 170,522,842
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 394
|
rd
|
revbayes.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/functions.R
\name{revbayes}
\alias{revbayes}
\title{revbayes}
\usage{
revbayes(...)
}
\arguments{
\item{...}{Arguments}
}
\description{
Run revbayes
}
\details{
Note, no interaction possible.
}
\examples{
library(outsider)
revbayes <- module_import('revbayes', repo = 'dombennett/om..revbayes')
revbayes('--help')
}
|
8f111191d3a87b4a9f3615a3544eb85f5ab24197
|
9fcbcdd002b754a2ebf108a67e99985fe434cda8
|
/scripts/web-scraper/2.indexing.R
|
de98c9bc40f17117bd1bbf108a64cdd42cea747a
|
[] |
no_license
|
paddytobias/pc_publications
|
f374e8b9853be041e30ffee04052d30b458443b0
|
783b82fc511d281df0f5fc2a01f278a568b3b1b0
|
refs/heads/master
| 2020-04-05T02:50:14.186396
| 2018-11-07T05:09:28
| 2018-11-07T05:09:28
| 155,674,495
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,229
|
r
|
2.indexing.R
|
query_terms = c(#"peacebuilding",
#"peace and conflict studies",
#"conflict resolution",
#"liberal peacebuilding",
#"peacemaking"
#,"conflict transformation"
#, 'state-building'
#, 'nation-building'
"conflict prevention",
"peacekeeping"
)
for (search in query_terms){
page_files = list.files(paste0("../data/", search, "/"), pattern = "^page_")
#add search attr for each page file
for (i in 1:length(page_files)){
filename = page_files[i]
filepath = paste0("../data/", search,"/",filename)
dat = read.csv(filepath)
if (!("search" %in% names(dat))){
dat$search = search
write.csv(dat, paste0("../data/", search,"/", filename), row.names = FALSE)
}
}
#clean up authors table per search by removing rows that have empty author name and adding search attr
authors = read.csv(paste0("../data/", search, "/authors_", search,".csv"))
if (!("search" %in% names(authors))){
authors$search = search
for (j in 1:nrow(authors)){
if (authors[j,1]=="" | is.null(authors[j,1])|is.na(authors[j,1])){
authors = authors[-c(j),]
}
}
write.csv(authors, paste0("../data/", search, "/authors_", search,".csv"), row.names = FALSE)
}
}
|
02f77dcf8e4c63f5a062004e7a23b8fa185ed21d
|
e1eba8f8812ff239d21dd5b1f348ecf62e48ddc9
|
/man/may_terminate.Rd
|
6b393f4a5918c49f1409c1f74ca91d4ff6a9a9d7
|
[] |
no_license
|
lorenzwalthert/namespaces
|
e5c60259f5e2f86c032f6da16af76a22b9cd93af
|
1d7c95f54bf1202068789b4706a0dcc66d126ef3
|
refs/heads/master
| 2020-03-09T09:51:50.753911
| 2019-05-06T09:59:17
| 2019-05-06T09:59:17
| 128,722,777
| 7
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 641
|
rd
|
may_terminate.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/bisect.R
\name{may_terminate}
\alias{may_terminate}
\title{How did it all end?}
\usage{
may_terminate(range, fun)
}
\arguments{
\item{range}{A range of candidates for the bisection}
\item{fun}{A function to be applied to range once range shrank to length one.}
}
\description{
Asssess the result of a binary search. Return the successful condition
if one is found, otherwise return NA. If the search has not yet been
determined, return a character string of length zero. The function is not
written for performance, but just to be explicit.
}
\keyword{internal}
|
a5f46cbbc2b200306aa8da145c60f1f604865201
|
a2b22db23c7a4d69fa8027d268677e29152d398e
|
/man/dmm.JModel.Rd
|
b42d22547f022bfde833fd2271ee224523d9d65f
|
[
"MIT"
] |
permissive
|
nsdumont/jDirichletMixtureModels
|
42d20baca5f6e62a00d8b9da729ab9d5837a879d
|
b01ab74d3542fada132bba6cfa00b702f3004f2e
|
refs/heads/master
| 2020-03-11T16:56:09.555422
| 2018-04-22T03:50:35
| 2018-04-22T03:50:35
| 130,132,458
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 2,522
|
rd
|
dmm.JModel.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dmm_model.R
\name{dmm.JModel}
\alias{dmm.JModel}
\title{Create a model using Julia fucntions}
\usage{
\code{dmm.addfile(filename)}
\code{model <- dmm.model(pdf_name, sample_name, marg_name, params, isconjugate=TRUE)}
\code{model <- dmm.Jmodel(pdf_name, sample_name, marg_name, params, isconjugate=TRUE)}
\code{model <- dmm.JConjugateModel(pdf_name, sample_name, marg_name, params)}
\code{model <- dmm.JNonConjugateModel(pdf_name, sample_name, params)}
}
\arguments{
\item{pdf_name}{A string. The name of the Julia function in \code{filename} that returns the probability density function likelihood. The function should be of the form \code{pdf_name(y::Float64, theta::Tuple, params::Tuple)} or \code{pdf_name(y::Array{Float64,1}, theta::Tuple, params::Tuple)}.}
\item{sample_name}{A string. The name of the Julia function in \code{filename} that returns the sample posterior function for conjugate case or the sample prior for nonconjugate case. The function should be of the form \code{sample_name(y::Float64, params::Tuple)}, \code{sample_name(y::Array{Float64,1}, params::Tuple)} or \code{sample_name(y::Array{Float64,2}, params::Tuple)}.}
\item{marg_name}{A string. For conjugate case only. The name of the Julia function in \code{filename} that returns the marginal likelihood. The function should be of the form \code{marg_name(y::Float64, params::Tuple)}.}
\item{params}{A list of all hyperparameters needed for the above three functions.}
\item{isconjugate}{A logical. \code{TRUE} (default) if the user specfied model is conjugate, \code{FALSE} if not.}
}
\value{
A model object of type JModel which can be passed to \code{dmm.cluster}.
}
\description{
Create an model object to be used in the \code{dmm.cluster} function, using user given Julia functions. Must call \code{dmm.addfile} to import files, in which the Julia functions are stored, before using \code{dmm.cluster} on a JModel.
Functions \code{dmm.JConjugateModel} and \code{dmm.JNonConjugateModel} are alternatives.
}
\details{
\code{marg_name} is only requried for conjugate models.
}
\examples{
dmm.addfile(filename)
# The following all make models using Julia functions
model <- dmm.model(pdf_name, sample_name, marg_name, params, isconjugate=TRUE)
model <- dmm.Jmodel(pdf_name, sample_name, marg_name, params, isconjugate=TRUE)
model <- dmm.JConjugateModel(pdf_name, sample_name, marg_name, params)
model <- dmm.JNonConjugateModel(pdf_name, sample_name, params)
}
|
6c5e35e6789dee2632418464ab8d4deaa7a17c60
|
502d0505e01e1c1385571cf5fb935630614896de
|
/man/FELLA.sample.Rd
|
612665b3eb1a12efc9dfad2640f1bb972fc30d1b
|
[] |
no_license
|
b2slab/FELLA
|
43308e802b02b8f566ac26c972dc51e72a340c0e
|
53276c4dfcb8cb4b5a688b167ba574d0f85228a6
|
refs/heads/master
| 2021-03-27T20:53:29.212810
| 2020-10-27T15:33:01
| 2020-10-27T15:33:01
| 24,852,722
| 14
| 4
| null | null | null | null |
UTF-8
|
R
| false
| true
| 818
|
rd
|
FELLA.sample.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/doc-data.R
\docType{data}
\name{FELLA.sample}
\alias{FELLA.sample}
\title{FELLA.DATA sample data}
\format{An object of class \code{FELLA.DATA} of length 1.}
\source{
Generated from a mid-2017 KEGG release
(\url{http://www.genome.jp/kegg/})
}
\usage{
data(FELLA.sample)
}
\value{
A \code{\link[FELLA]{FELLA.DATA}} object
}
\description{
This \code{\link[FELLA]{FELLA.DATA}} object is
a small KEGG graph object.
Despite being a small database that only contains
the two metabolic pathways
hsa00010 - Glycolysis / Gluconeogenesis, and hsa00640 -
Propanoate metabolism,
it is useful to play around with \code{FELLA}'s
functions. It is also used for internal testing of this package.
}
\examples{
data(FELLA.sample)
}
\keyword{datasets}
|
2c7404a02ff011de2bca1c8a1cf6d939bb43258a
|
07373a07ec45cf2b5b9e6ec97ae85c2355ba4e44
|
/ModelValidation.r
|
cf7fdc5d5e0c82dc38bba63bc4db5563940aa60b
|
[] |
no_license
|
bchasco/squid
|
23ae5c3acee775a6643a287952ae2c3f8a335525
|
feee30a50d71bf9c44539eaa8aeb1252426540f8
|
refs/heads/master
| 2022-02-15T12:47:43.850002
| 2022-01-27T20:37:36
| 2022-01-27T20:37:36
| 229,161,733
| 0
| 0
| null | 2020-05-22T02:43:28
| 2019-12-20T00:39:04
|
HTML
|
UTF-8
|
R
| false
| false
| 1,516
|
r
|
ModelValidation.r
|
ParHat <- fit$ParHat
#7) Temporal correlation
RhoConfig= c("Beta1" = 0 #Temporal corr. encounter covariate intercepts
,"Beta2" = 0 #Temporal corr. for positive catch covariate intercepts
,"Epsilon1"= 0 #Temporal corr. for encounter probability intercepts
,"Epsilon2" = 0) #Temporal corr. for positive catch intercepts
settings <- make_settings(
n_x = n_x
,Region = "california_current"
,purpose = "index2"
,strata.limits = strata.limits
,FieldConfig = FieldConfig
,RhoConfig = RhoConfig
,OverdispersionConfig = OverdispersionConfig
,ObsModel = ObsModel
,knot_method = "samples"
,bias.correct = FALSE
,Options = Options
)
# Generate partitions in data
n_fold <- 10
Partition_i <- sample( 1:n_fold, size=nrow(raw), replace=TRUE )
prednll_f <- rep(NA, n_fold )
# Loop through partitions, refitting each time with a different PredTF_i
n_i <- nrow(raw)
for( fI in 1:n_fold ){
rm(fit_new)
PredTF_i = ifelse( Partition_i==fI, TRUE, FALSE )
fit_new <- fit_model(settings = settings
,Lat_i = raw$Lat
,Lon_i = raw$Lon
,t_i = raw$Year
,c_i = c_iz
,b_i = b_i #Number of squid captured.
,a_i = a_i
,v_i = rep(0,n_i)
,"PredTF_i"=PredTF_i
,"Parameters"=ParHat
,"getsd"=FALSE
)
# Save fit to out-of-bag data
prednll_f[fI] = fit_new$Report$pred_jnll
}
|
e34e61e634365df66b9fe2b91e0f309267b27a35
|
443bfca7f6cc29a2d77278ea12544959ec0f7791
|
/MICE_mediate_ex.R
|
062271ff12e82eee9064efba5551777d8543f386
|
[] |
no_license
|
APoernbacher/Multiple-Imputation-R
|
362465984a1083b25dc4cb8066c88ec0b9ff5a7c
|
f69a1d1d8ec71d2604c53a5b3959bee997b6d15d
|
refs/heads/master
| 2023-03-15T21:45:23.850593
| 2018-06-26T13:21:16
| 2018-06-26T13:21:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,708
|
r
|
MICE_mediate_ex.R
|
### Use multiple imputation to create imputed data and run a mediation
#Created by Jessie-Raye Bauer, Oct. 2017
#Load Packages
library(VIM)
library(mice)
library(lattice)
# Using the built-in airquality dataset
data <- airquality
#create missing data
data[80:81,3] <- rep(NA, 2)
data[4:15,3] <- rep(NA,12)
data[1:5,2] <- rep(NA, 5)
# Removing categorical variables
data <- data[-c(5,6)]
summary(data)
#Ozone Solar.R Wind Temp
#Min. : 1.00 Min. : 7.0 Min. : 1.700 Min. :56.00
#1st Qu.: 18.00 1st Qu.:112.8 1st Qu.: 7.400 1st Qu.:72.00
#Median : 31.50 Median :209.5 Median : 9.700 Median :79.00
#Mean : 42.13 Mean :185.7 Mean : 9.822 Mean :77.88
#3rd Qu.: 63.25 3rd Qu.:258.8 3rd Qu.:11.500 3rd Qu.:85.00
#Max. :168.00 Max. :334.0 Max. :20.700 Max. :97.00
#NA's :37 NA's :11 NA's :14
#-------------------------------------------------------------------------------
# Look for missing > 5% variables
pMiss <- function(x){sum(is.na(x))/length(x)*100}
# Check each column
apply(data,2,pMiss)
# Check each row
apply(data,1,pMiss)
#-------------------------------------------------------------------------------
# Missing data pattern
md.pattern(data)
# Plot of missing data pattern
aggr_plot <- aggr(data, col=c('navyblue','red'), numbers=TRUE, sortVars=TRUE, labels=names(data), cex.axis=.7, gap=3, ylab=c("Histogram of missing data","Pattern"))
# Box plot
marginplot(data[c(1,2)])
#-------------------------------------------------------------------------------
# Impute missing data using mice
#about 10% average missing data, so maxit= 10
tempData <- mice(data,m=5,maxit=10,meth='pmm',seed=500)
summary(tempData)
# Get imputed data (for the Ozone variable)
tempData$imp$Ozone
# Possible imputation models provided by mice() are
methods(mice)
# What imputation method did we use?
tempData$meth
# Get completed datasets (observed and imputed)
completedData <- complete(tempData,1)
summary(completedData)
#-------------------------------------------------------------------------------
# Plots of imputed vs. orginal data
library(lattice)
# Scatterplot Ozone vs all
xyplot(tempData,Ozone ~ Wind+Temp+Solar.R,pch=18,cex=1)
# Density plot original vs imputed dataset
densityplot(tempData)
# Another take on the density: stripplot()
stripplot(tempData, pch = 20, cex = 1.2)
#-------------------------------------------------------------------------------
# IMPUTE
# create imputed dataframe
imp1 <- miceadds::datlist_create(tempData)
#create correlation table
corr_mice = miceadds::micombine.cor(mi.res=tempData )
#-------------------------------------------------------------------------------
# Mediation
##Create your mediation model
mediation <- '
# direct effect
Temp ~ cprime*Ozone
# mediator
Solar.R ~ a*Ozone
Temp ~ b*Solar.R
# indirect effect
ab := a*b
total := cprime + (a*b)
direct:= cprime
'
# analysis based on all imputed datasets
mod6b <- lapply( imp1 , FUN = function(data){
res <- lavaan::sem(mediation , data = data )
return(res)
} )
# extract all parameters
qhat <- lapply( mod6b , FUN = function(ll){
h1 <- lavaan::parameterEstimates(ll)
parnames <- paste0( h1$lhs , h1$op , h1$rhs )
v1 <- h1$est
names(v1) <- parnames
return(v1)
} )
se <- lapply( mod6b , FUN = function(ll){
h1 <- lavaan::parameterEstimates(ll)
parnames <- paste0( h1$lhs , h1$op , h1$rhs )
v1 <- h1$se
names(v1) <- parnames
return(v1)
} )
# use mitml for mediation
se2 <- lapply( se , FUN = function(ss){ ss^2 } ) # input variances
results <- mitml::testEstimates(qhat=qhat, uhat=se2)
#look at your results!
results
|
ab09be21053cafb4e2a09156dfe18486061bbb52
|
66203f6723fc06f00a3c7b92db71fe8e3b875929
|
/cachematrix.R
|
3c617c0710d31d3ebd53fa69a23b9b424da4e432
|
[] |
no_license
|
LokeshMakhija/ProgrammingAssignment2
|
97f16a66514e238e9ebe2d6718a084290566ca8d
|
3b004c4792f6bf885b06cc074b6ebf7ea68f4c70
|
refs/heads/master
| 2020-03-26T11:31:28.059015
| 2018-08-15T13:37:24
| 2018-08-15T13:37:24
| 144,846,926
| 0
| 0
| null | 2018-08-15T11:52:36
| 2018-08-15T11:52:36
| null |
UTF-8
|
R
| false
| false
| 1,038
|
r
|
cachematrix.R
|
## makeCacheMatrix creates a special matrix, given a matrix as an input. It has special functions which
## can cache the inverse of the original matrix through setInv function and returns the inverse value
## when requested through getInv function.
## eg. to run
## x <- makeCacheMatrix(matrix(rnorm(25),5,5))
## cacheSolve(x)
## cacheSolve(x)
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setInv <- function(invr) inv <<- invr
getInv <- function() inv
list(set = set, get = get, setInv = setInv, getInv = getInv)
}
## cacheSolve takes a matrix formed by makeCacheMatrix function. It checks if the inverse of the matrix
## is already in cache. If yes, it returns the value, else calculates the inverse, stores it in cache and
## then returns the value.
cacheSolve <- function(x, ...) {
i <- x$getInv()
if (!is.null(i)){
message("getting cached data")
return(i)
}
data <- x$get()
invr <- solve(data)
x$setInv(invr)
invr
}
|
d11c03f1da441c2b3e71b3e0cda5ccdff1f7e187
|
81ff4f78af4de923a71b1ac05cfebc82fb01818d
|
/CRAN/contrib/spaMM/R/fit_as_ZX.R
|
f9144cd2b66ebd0dfd234edd6b6ce3157ffb9154
|
[] |
no_license
|
PRL-PRG/dyntrace-instrumented-packages
|
9d56a2a101c4bd9bee6bbe2ababe014d08cae1a0
|
6c586a26b8007dc6808865883e1dd7d2a1bf6a04
|
refs/heads/master
| 2020-03-08T15:45:59.296889
| 2018-04-06T09:41:52
| 2018-04-06T09:41:52
| 128,220,794
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 33,034
|
r
|
fit_as_ZX.R
|
.do_damped_WLS <- function(sXaug, zInfo, # fixed descriptors of system to be solved
old_Vscaled_beta,
oldAPHLs,
APHLs_args,
damping,
dampingfactor=2, ## no need to change the input value
ypos,off,GLMMbool,etaFix,constant_u_h_v_h_args,
updateW_ranefS_constant_arglist,
wranefblob,seq_n_u_h,ZAL_scaling,
processed, trace=FALSE, Xscal,mMatrix_method,
phi_est, H_global_scale, n_u_h, ZAL, which_i_affected_rows,
which_LevMar_step
) {
newXscal <- Xscal ## template
initdamping <- damping
gainratio_grad <- zInfo$gainratio_grad
# grad wrt scaled v = d f / d (v/ZAL_scaling) = ZAL_scaling * d f / d v
use_heuristic <- TRUE
while ( TRUE ) {
if (processed$HL[1L]==1L) { ## ML fit
Vscaled_beta <- old_Vscaled_beta
## maximize p_v wrt beta only
if ( which_LevMar_step=="v_b") { ## note tests on summand too !!!!!!!
LevMarblob <- get_from_MME(sXaug=sXaug, which="LevMar_step", LMrhs=zInfo$scaled_grad, damping=damping)
Vscaled_beta <- Vscaled_beta + LevMarblob$dVscaled_beta
} else if ( which_LevMar_step=="b") {
LevMarblob <- get_from_MME(sXaug=sXaug, which="LevMar_step_beta", LMrhs=zInfo$scaled_grad[-seq_n_u_h], damping=damping)
Vscaled_beta[-seq_n_u_h] <- Vscaled_beta[-seq_n_u_h] + LevMarblob$dbeta
} else if ( which_LevMar_step=="v") { ## v_h estimation given beta
LevMarblob <- get_from_MME(sXaug=sXaug, which="LevMar_step_v_h", LMrhs=zInfo$scaled_grad[seq_n_u_h], damping=damping)
Vscaled_beta[seq_n_u_h] <- Vscaled_beta[seq_n_u_h] + LevMarblob$dVscaled
}
} else { ## joint hlik maximization
LevMarblob <- get_from_MME(sXaug=sXaug, which="LevMar_step", LMrhs=zInfo$scaled_grad, damping=damping)
Vscaled_beta <- old_Vscaled_beta + LevMarblob$dVscaled_beta
}
fitted <- drop(Xscal %*% Vscaled_beta) ## length nobs+nr !
fitted[ypos] <- eta <- fitted[ypos] + off
newmuetablob <- .muetafn(eta=eta,BinomialDen=processed$BinomialDen,processed=processed)
neww.resid <- .calc_w_resid(newmuetablob$GLMweights,phi_est)
newweight_X <- .calc_weight_X(neww.resid, H_global_scale) ## sqrt(s^2 W.resid)
if (is.null(etaFix$v_h)) {
v_h <- Vscaled_beta[seq_n_u_h] * ZAL_scaling ## use original scaling!
if (GLMMbool) {
u_h <- v_h
newwranefblob <- wranefblob ## keep input wranefblob since GLMM and lambda_est not changed
} else {
u_h_v_h_from_v_h_args <- c(constant_u_h_v_h_args,list(v_h=v_h))
u_h <- do.call(".u_h_v_h_from_v_h",u_h_v_h_from_v_h_args)
if ( ! is.null(attr(u_h,"v_h"))) { ## second test = if u_h_info$upper.v_h or $lower.v_h non NULL
v_h <- attr(u_h,"v_h")
}
## update functions u_h,v_h
newwranefblob <- do.call(".updateW_ranefS",c(updateW_ranefS_constant_arglist,list(u_h=u_h,v_h=v_h)))
}
} else newwranefblob <- wranefblob
mMatrix_arglist <- list(weight_X=newweight_X, w.ranef=newwranefblob$w.ranef, H_global_scale=H_global_scale)
if ( ! GLMMbool ) {
# newZAL_scaling necessary to get the correct logdet_sqrt_d2hdv2 for newsXaug
newZAL_scaling <- 1/sqrt(newwranefblob$w.ranef*H_global_scale) ## Q^{-1/2}/s
## used only to compute a likelihood, not to update a system to be solved.
if (TRUE) {
## alternative clause shows the meaning. This is distinctly faster.
scaledZAL <- .m_Matrix_times_Dvec(ZAL, newZAL_scaling)
if (inherits(ZAL,"Matrix")) {
# Next line assumes Xscal (IO_ZX) has no @diag component
newXscal@x[which_i_affected_rows] <- scaledZAL@x ## should create an error if some elements are stored in @diag
} else {
newXscal[n_u_h+seq(nrow(scaledZAL)),seq_n_u_h] <- scaledZAL
}
} else newXscal <- .make_Xscal(ZAL, ZAL_scaling = newZAL_scaling, AUGI0_ZX=processed$AUGI0_ZX, n_u_h=n_u_h)
mMatrix_arglist$Xaug <- newXscal
} else mMatrix_arglist$Xaug <- Xscal ##not distinct from the 'resident' Xscal
newsXaug <- do.call(mMatrix_method, mMatrix_arglist)
APHLs_args$sXaug <- newsXaug
APHLs_args$dvdu <- newwranefblob$dvdu
APHLs_args$u_h <- u_h
APHLs_args$mu <- newmuetablob$mu
newAPHLs <- do.call(".calc_APHLs_from_ZX", APHLs_args)
if (processed$HL[1L]==1L) {
if (which_LevMar_step=="v") {
newlik <- newAPHLs[["hlik"]]
oldlik <- oldAPHLs[["hlik"]]
if (damping==0L) {
if (trace) print(paste("IRLS step for v_h, hlik=",newlik))
break
}
} else {
newlik <- newAPHLs[["p_v"]]
oldlik <- oldAPHLs[["p_v"]]
if (damping==0L) {
if (trace) print(paste("IRLS step for (beta,v_h); p_v=",newlik))
break
}
}
} else {
newlik <- newAPHLs[["hlik"]]
oldlik <- oldAPHLs[["hlik"]]
if (damping==0L) {
if (trace) print(paste("IRLS step, hlik=",newlik))
break
}
}
## ELSE
gainratio <- (newlik!=-Inf) ## -Inf occurred in binary probit with extreme eta...
if (gainratio) {
if (processed$HL[1L]==1L) { ## ML fit
if (which_LevMar_step=="v_b") {
tempodvhbeta <- LevMarblob$dVscaled_beta
tempodvhbeta[seq_n_u_h] <- tempodvhbeta[seq_n_u_h]*ZAL_scaling
summand <- tempodvhbeta*(gainratio_grad+ LevMarblob$dampDpD * tempodvhbeta)
} else if (which_LevMar_step=="b") {
summand <- LevMarblob$dbeta*(gainratio_grad[-seq_n_u_h]+ LevMarblob$dampDpD * LevMarblob$dbeta)
} else if (which_LevMar_step=="v") { ## v_h estimation given beta (FIXME can surely be made more exact)
tempodvh <- LevMarblob$dVscaled*ZAL_scaling
summand <- tempodvh*(gainratio_grad[seq_n_u_h]+ LevMarblob$dampDpD * tempodvh)
}
} else { ## joint hlik maximization
summand <- LevMarblob$dVscaled_beta*(gainratio_grad+ LevMarblob$dampDpD * LevMarblob$dVscaled_beta)
}
## The two terms of the summand should be positive. In part. conv_dbetaV*rhs should be positive.
## However, numerical error may lead to <0 or even -Inf
## Further, if there are both -Inf and +Inf elements the sum is NaN.
summand[summand<0] <- 0
denomGainratio <- sum(summand)
dlogL <- newlik-oldlik
conv_logL <- abs(dlogL)/(1+abs(newlik))
gainratio <- 2*dlogL/denomGainratio ## cf computation in MadsenNT04 below 3.14, but generalized for D' != I ; numerator is reversed for maximization
} else { ## 2017/10/16 a patch to prevent a stop in this case, but covers up dubious computations (FIXME)
newlik <- -.Machine$double.xmax
dlogL <- newlik-oldlik
conv_logL <- abs(dlogL)/(1+abs(newlik))
}
if (trace) print(paste("dampingfactor=",dampingfactor,#"innerj=",innerj,
"damping=",damping,"gainratio=",gainratio,"oldlik=",oldlik,"newlik=",newlik))
if (is.nan(gainratio)) {
# if the initial logL is the solution logL, then damping diverges
# it is then possible that some element of dVscaled_beta =0 and some of dampDpD =Inf
# then the summand has some NaN
# At the same time not all elements of dVscaled_beta need be 0 (eg small changes in eta for mu=0 or 1 in binomial models)
# so testing dVscaled_beta is not sufficient to stop the algo
# (LevenbergM is quite slow in such cases)
break
}
if (gainratio > 0) {
## cf Madsen-Nielsen-Tingleff again, and as in levmar library by Lourakis
damping <- damping * max(1/3,1-(2*gainratio-1)^3)
# damping <- min(1000,damping )
break
} else if (dampingfactor>4 ## implies iter>2
&& conv_logL <1e-8 && abs(prev_conv_logL) <1e-8) {
damping <- initdamping ## bc presumably damping has diverged unusefully
break ## apparently flat likelihood; this has occurred when fit_as_ZX used a wrong initial (beta,v_h), but still occurs in /tests
} else { ## UNsuccessful step
prev_conv_logL <- conv_logL
damping <- damping*dampingfactor
dampingfactor <- dampingfactor*2
}
if (damping>1e100) stop("reached damping=1e100")
}
RESU <- list(lik=newlik,APHLs=newAPHLs,damping=damping,sXaug=newsXaug,
fitted=fitted, eta=eta, muetablob=newmuetablob, wranefblob=newwranefblob,
v_h=v_h,u_h=u_h, w.resid=neww.resid)
if ( ! GLMMbool ) {
RESU$ZAL_scaling <- newZAL_scaling
RESU$Xscal <- newXscal
Vscaled_beta[seq_n_u_h] <- v_h/newZAL_scaling ## represent solution in new scaling...
}
RESU$Vscaled_beta <- Vscaled_beta
return(RESU)
}
.solve_IRLS_as_ZX <- function(X.pv,
ZAL,
y, ## could be taken fom processed ?
n_u_h, H_global_scale, lambda_est, muetablob=NULL ,off, maxit.mean, etaFix,
wranefblob, processed,
## supplement for ! LMM
phi_est,
## supplement for for LevenbergM or ! GLMM
eta=NULL, w.resid=NULL,
## supplement for ! GLMM
u_h, v_h, for_init_z_args,
## supplement for LevenbergM
beta_eta,
## supplement for intervals
for_intervals,
trace=FALSE
) {
pforpv <- ncol(X.pv)
nobs <- length(y)
seq_n_u_h <- seq_len(n_u_h)
ypos <- n_u_h+seq_len(nobs)
lcrandfamfam <- attr(processed$rand.families,"lcrandfamfam")
LMMbool <- processed$LMMbool
GLMMbool <- processed$GLMMbool
LevenbergM <- (.determine_LevenbergM(processed$LevenbergM) && is.null(for_intervals))
is_HL1_1 <- (processed$HL[1L]==1L)
which_LevMar_step <- "v_b"
old_relV_beta <- NULL
not_moving <- FALSE
damped_WLS_blob <- NULL
Ftol_LM <- processed$spaMM_tol$Ftol_LM
if ( LevenbergM) {
damping <- 1e-7
loc_Xtol_rel <- 1e-03 ## maybe good compromise between optim accuracy and time.
} else {
damping <- 0L ## indicator for early exit from .do_damped_WLS without a check for increase
loc_Xtol_rel <- processed$spaMM_tol$Xtol_rel/10
}
if ( ! LMMbool) {
constant_zAug_args <- list(n_u_h=n_u_h, nobs=nobs, pforpv=pforpv, y=y, off=off, ZAL=ZAL, processed=processed)
if ( ! GLMMbool) {
constant_init_z_args <- c(list(lcrandfamfam=lcrandfamfam, nobs=nobs, lambda_est=lambda_est, ZAL=ZAL),
# fit_as_ZX args specific for ! GLMM:
for_init_z_args,
#
mget(c("cum_n_u_h","rand.families","stop.on.error"),envir=processed))
constant_u_h_v_h_args <- c(mget(c("cum_n_u_h","rand.families"),envir=processed),
processed$u_h_info, ## elements of u_h_info as elements of constant_u_h_v_h_args
list(lcrandfamfam=lcrandfamfam))
updateW_ranefS_constant_arglist <- c(mget(c("cum_n_u_h","rand.families"),envir=processed),list(lambda=lambda_est))
}
}
##### initial sXaug
ZAL_scaling <- 1/sqrt(wranefblob$w.ranef*H_global_scale) ## Q^{-1/2}/s
Xscal <- .make_Xscal(ZAL, ZAL_scaling = ZAL_scaling,
AUGI0_ZX=processed$AUGI0_ZX,n_u_h=n_u_h)
if (inherits(Xscal,"Matrix")) { # same type as ZAL
## def_sXaug_Eigen_sparse_QR calls lmwith_sparse_QRp(,pivot=FALSE)
## def_sXaug_Eigen_sparse_QRP calls lmwith_sparse_QRp(,pivot=TRUE)
mMatrix_method <- .spaMM.data$options$Matrix_method
#@p[c] must contain the index _in @x_ of the first nonzero element of column c, x[p[c]] in col c and row i[p[c]])
elmts_affected_cols <- seq_len(Xscal@p[n_u_h+1L]) ## corresponds to cols seq_n_u_h
which_i_affected_rows <- which(Xscal@i[elmts_affected_cols]>(n_u_h-1L))
} else {
mMatrix_method <- .spaMM.data$options$matrix_method
which_i_affected_rows <- NULL
}
if ( ! is.null(for_intervals)) {
Vscaled_beta <- c(v_h/ZAL_scaling ,for_intervals$beta_eta)
} else if (LevenbergM) {
Vscaled_beta <- c(v_h/ZAL_scaling ,beta_eta)
} # else is NULL
if (is.null(eta)) { ## NULL input eta allows NULL input muetablob
eta <- off + (Xscal %*% c(v_h/ZAL_scaling ,beta_eta))[ypos]
muetablob <- .muetafn(eta=eta,BinomialDen=processed$BinomialDen,processed=processed)
}
## weight_X and Xscal varies within loop if ! LMM since at least the GLMweights in w.resid change
if ( is.null(w.resid) ) w.resid <- .calc_w_resid(muetablob$GLMweights,phi_est)
weight_X <- .calc_weight_X(w.resid, H_global_scale) ## sqrt(s^2 W.resid)
sXaug <- do.call(mMatrix_method,
list(Xaug=Xscal, weight_X=weight_X, w.ranef=wranefblob$w.ranef, H_global_scale=H_global_scale))
allow_LM_restart <- ( ! LMMbool && ! LevenbergM && is.null(for_intervals) && is.na(processed$LevenbergM["user_LM"]) )
if (allow_LM_restart) {
keep_init <- new.env()
#names_keep <- ls()
names_keep <- c("sXaug","wranefblob","muetablob","u_h","w.resid","eta","v_h","ZAL_scaling","weight_X","Xscal","beta_eta")
for (st in names_keep) keep_init[[st]] <- environment()[[st]]
}
LMcond <- - 10.
################ L O O P ##############
for (innerj in 1:maxit.mean) {
if( ! LevenbergM && allow_LM_restart) { ## FIXME the next step improvement would be
# ./. to keep track of lowest lambda that created problem and use LM by default then
if (innerj>3) {
LMcond <- LMcond + mean(abs_d_relV_beta/(old_abs_d_relV_beta+1e-8))
## cat(mean(abs_d_relV_beta/old_abs_d_relV_beta)," ")
# cat(LMcond/innerj," ")
if (LMcond/innerj>0.5) {
if (trace) cat("!LM")
for (st in names_keep) assign(st,keep_init[[st]])
LevenbergM <- TRUE
Vscaled_beta <- c(v_h/ZAL_scaling ,beta_eta) ## bc initialized only | LevenbergM
damping <- 1e-7
loc_Xtol_rel <- 1e-03 ## maybe good compromise between optim accuracy and time.
damped_WLS_blob <- NULL
allow_LM_restart <- FALSE
}
}
if (innerj>2) old_abs_d_relV_beta <- abs_d_relV_beta
}
##### get the lik of the current state
if ( ! is.null(for_intervals)) {
loc_logLik_args <- list(sXaug=sXaug, processed=processed, phi_est=phi_est,
lambda_est=lambda_est, dvdu=wranefblob$dvdu, u_h=u_h, mu=muetablob$mu)
oldlik <- unlist(do.call(".calc_APHLs_from_ZX",loc_logLik_args)[for_intervals$likfn]) # unlist keeps name
} else {
if (LevenbergM) {
if (is.null(damped_WLS_blob)) {
oldAPHLs <- .calc_APHLs_from_ZX(sXaug=sXaug, processed=processed, phi_est=phi_est, which=processed$p_v_obj,
lambda_est=lambda_est, dvdu=wranefblob$dvdu, u_h=u_h, mu=muetablob$mu)
} else { ## Levenberg and innerj>1
oldAPHLs <- damped_WLS_blob$APHLs
}
}
}
#####
##### RHS
if (LMMbool) {
wzAug <- c(rep(0,n_u_h),(y-off)*weight_X)
} else {
if ( ! GLMMbool) {
# arguments for init_resp_z_corrections_new called in calc_zAug_not_LMM
init_z_args <- c(constant_init_z_args,
list(w.ranef=wranefblob$w.ranef, u_h=u_h, v_h=v_h, dvdu=wranefblob$dvdu,
sXaug=sXaug, w.resid=w.resid))
} else init_z_args <- NULL
calc_zAug_args <- c(constant_zAug_args,
list(eta=eta, muetablob=muetablob, dlogWran_dv_h=wranefblob$dlogWran_dv_h,
sXaug=sXaug, ## .get_qr may be called for Pdiag calculation
w.ranef=wranefblob$w.ranef,
w.resid=w.resid,
init_z_args=init_z_args) )
zInfo <- do.call(".calc_zAug_not_LMM",calc_zAug_args) ## dlogfvdv is 'contained' in $z2
wzAug <- c(zInfo$y2_sscaled/ZAL_scaling, (zInfo$z1_sscaled)*weight_X)
}
## keep name 'w'zAug to emphasize the distinct weightings of zaug and Xaug (should have been so everywhere)
#####
##### improved Vscaled_beta
if ( ! is.null(for_intervals)) {
currentDy <- (for_intervals$fitlik-oldlik)
if (currentDy < -1e-4) .warn_intervalStep(oldlik,for_intervals)
intervalBlob <- .intervalStep_ZX(old_Vscaled_beta=Vscaled_beta,
sXaug=sXaug,szAug=wzAug,
for_intervals=for_intervals,
currentlik=oldlik,currentDy=currentDy)
damped_WLS_blob <- NULL
Vscaled_beta <- intervalBlob$Vscaled_beta
} else if (LevenbergM) { ## excludes IRLS
## (w)zAug is all what is needed for the direct solution of the extended system. in GLMM case
# Hence wZaug contains Phi z_2 including (Phi v^0 +dlogfvdv)/ZAL_scaling (from components of hlik)
## now we want the LHS of a d_beta_v solution
etamo <- eta - off
zInfo$z1_eta <- zInfo$z1-etamo
z1_sscaled_eta <- zInfo$z1_sscaled - etamo # zAug[-seq_n_u_h]-etamo # z_1-sscaled-etamo
if (GLMMbool) {
zInfo$dlogfvdv <- - v_h * wranefblob$w.ranef
} else zInfo$dlogfvdv <- (zInfo$z2 - v_h) * wranefblob$w.ranef
## the gradient for -p_v (or -h), independent of the scaling
if (is.list(w.resid)) {
m_grad_obj <- c( ## drop() avoids c(Matrix..)
m_grad_v <- drop(.crossprod(ZAL, w.resid$w_resid * zInfo$z1_eta) + zInfo$dlogfvdv), # Z'W(z_1-eta)+ dlogfvdv
drop(.crossprod(X.pv, w.resid$w_resid * z1_sscaled_eta)) # X'W(z_1-sscaled-eta)
)
} else {
m_grad_obj <- c( ## drop() avoids c(Matrix..)
m_grad_v <- drop(.crossprod(ZAL, w.resid * zInfo$z1_eta) + zInfo$dlogfvdv), # Z'W(z_1-eta)+ dlogfvdv
drop(.crossprod(X.pv, w.resid * z1_sscaled_eta)) # X'W(z_1-sscaled-eta)
)
}
if (not_moving && is_HL1_1) { ## not_moving TRUE may occur when we are out of solution space. Hence test Mg_solve_g
Mg_solve_g <- get_from_MME(sXaug=sXaug, which="Mg_solve_g", B=m_grad_obj)
if (Mg_solve_g < Ftol_LM/2) {
if (trace>1L) {"break bc Mg_solve_g<1e-6"}
break
}
} ## else not_moving was a break condition elsewhere in code
zInfo$gainratio_grad <- m_grad_obj ## before recaling
# gradient for scaled system from gradient of objective
scaled_grad <- H_global_scale * m_grad_obj
scaled_grad[seq_n_u_h] <- scaled_grad[seq_n_u_h] * ZAL_scaling
zInfo$scaled_grad <- scaled_grad
if (trace>1L ) { ## only tracing
maxs_grad <- c(max(abs(m_grad_obj[seq_n_u_h])),max(abs(m_grad_obj[-seq_n_u_h])))
cat("iter=",innerj,", max(|grad|): v=",maxs_grad[1L],"beta=",maxs_grad[2L],";")
}
constant_APHLs_args <- list(processed=processed, which=processed$p_v_obj, sXaug=sXaug, phi_est=phi_est, lambda_est=lambda_est)
# the following block needs m_grad_v the new m_grad_v hence its position
if (is_HL1_1 && ! is.null(damped_WLS_blob)) {
if (which_LevMar_step=="v") { ##
hlik_stuck <- (damped_WLS_blob$APHLs$hlik < oldAPHLs$hlik + Ftol_LM/10)
if ( ! hlik_stuck) need_v_step <- (get_from_MME(sXaug=damped_WLS_blob$sXaug, which="Mg_invH_g", B=m_grad_v) > Ftol_LM/2)
if ( hlik_stuck || ! need_v_step) { ## LevMar apparently maximized h wrt v after several iterations
## if hlik has not recently moved or has moved but reached a point where the h gradient is negligible
if (trace>2L) print("switch from v to v_b")
old_relV_beta <- relV_beta ## serves to assess convergence !!!!!!!!!!!!!!!!!!!
which_LevMar_step <- "v_b"
} else {
if (trace>2L) print("still v")
## v_h estimation not yet converged, continue with it
}
} else { ## performed one improvement of p_v by new v_b,
# indirect way of checking Mg_solve_g:
# FIXME I made not_moving a sufficent condition fro break below !
if (not_moving) { ## if we reach this point, Mg_solve_g (tested above) was too large, we must be out of solution space
# need_v_step <- TRUE ## implicit meaning
} else {
p_v_stuck <- (damped_WLS_blob$APHLs$p_v < oldAPHLs$p_v + Ftol_LM/10) ## test whether LevMar apparently solved (v,beta) equations after several iterations
if ( ! p_v_stuck) need_v_step <- (get_from_MME(sXaug=damped_WLS_blob$sXaug, which="Mg_invH_g", B=m_grad_v) > Ftol_LM/2)
## we have identified two gradient cases where we must check v: Mg_solve_g>0 or (if estimates have just moved) Mg_invH_g>0
}
if ( not_moving || p_v_stuck || need_v_step) { ## logically we may not need p_v_stuck, but this condition is faster to evaluate
# p_v_stuck is analogous to (not_moving BUT large Mg_solve_g), checking that lik and estimates do not change
if (trace>2L) print("switch from v_b to v")
which_LevMar_step <- "v"
} else {
if (trace>2L) print("still v_b")
}
}
}
damped_WLS_blob <- .do_damped_WLS(sXaug=sXaug, zInfo=zInfo,
old_Vscaled_beta=Vscaled_beta,
oldAPHLs=oldAPHLs,
APHLs_args = constant_APHLs_args,
damping=damping,
ypos=ypos,off=off,
GLMMbool=GLMMbool,etaFix=etaFix,
constant_u_h_v_h_args=constant_u_h_v_h_args,
updateW_ranefS_constant_arglist=updateW_ranefS_constant_arglist,
wranefblob=wranefblob,seq_n_u_h=seq_n_u_h,ZAL_scaling=ZAL_scaling,
processed=processed, Xscal=Xscal,mMatrix_method = mMatrix_method,
phi_est=phi_est, H_global_scale=H_global_scale, n_u_h=n_u_h, ZAL=ZAL,
which_i_affected_rows=which_i_affected_rows,
which_LevMar_step = which_LevMar_step
)
## LevM PQL
if (! is_HL1_1) {
if (damped_WLS_blob$lik < oldAPHLs$hlik) { ## if LevM step failed to find a damping that increases the lik
## This occurs inconspiscuously in the PQL_prefit providing a bad starting point for ML fit
damped_WLS_blob <- NULL
wzAug <- c(zInfo$y2_sscaled/ZAL_scaling, (zInfo$z1_sscaled)*weight_X)
Vscaled_beta <- get_from_MME(sXaug,szAug=wzAug) # vscaled= v scaling so that v has 'scale' H_global_scale
LevenbergM <- FALSE ## D O N O T set it to TRUE again !
}
}
} else { ## IRLS: always accept new v_h_beta
damped_WLS_blob <- NULL
Vscaled_beta <- get_from_MME(sXaug,szAug=wzAug) # vscaled= v scaling so that v has 'scale' H_global_scale
}
######
##### Everything that is needed for
# (1) assessment of convergence: c(v_h*sqrt(wranefblob$w.ranef),beta_eta)
# (2) all return elements are updated as function of the latest Vscaled_beta.
# In particular We need muetablob and (if ! LMM) sXaug, hence a lot of stuff.
# Hence, the following code is useful whether a break occurs or not.
if ( ! is.null(damped_WLS_blob) ) {
Vscaled_beta <- damped_WLS_blob$Vscaled_beta
eta <- damped_WLS_blob$eta
wranefblob <- damped_WLS_blob$wranefblob
v_h <- damped_WLS_blob$v_h
u_h <- damped_WLS_blob$u_h
muetablob <- damped_WLS_blob$muetablob
w.resid <- damped_WLS_blob$w.resid ## !important! cf test-adjacency-corrMatrix.R
# there's no new weight_X in damped_WLS_blob as the weights are purposefully kept constant there
# same for new 'fitted'
sXaug <- damped_WLS_blob$sXaug
if ( ! GLMMbool ) {
Xscal <- damped_WLS_blob$Xscal
ZAL_scaling <- damped_WLS_blob$ZAL_scaling
}
} else {
# Vscaled_beta must have been provided by somethin else than damped_WLS_blob
# drop, not as.vector(): names are then those of (final) eta and mu -> used by predict() when no new data
fitted <- drop(Xscal %*% Vscaled_beta) ## length nobs+nr !
fitted[ypos] <- eta <- fitted[ypos] + off
if (is.null(etaFix$v_h)) {
v_h <- Vscaled_beta[seq_n_u_h] * ZAL_scaling
if (GLMMbool) {
u_h <- v_h ## keep input wranefblob since lambda_est not changed
} else {
u_h_v_h_from_v_h_args <- c(constant_u_h_v_h_args,list(v_h=v_h))
u_h <- do.call(".u_h_v_h_from_v_h",u_h_v_h_from_v_h_args)
if ( ! is.null(attr(u_h,"v_h"))) { ## second test = if u_h_info$upper.v_h or $lower.v_h non NULL
v_h <- attr(u_h,"v_h")
}
## update functions u_h,v_h
wranefblob <- do.call(".updateW_ranefS",c(updateW_ranefS_constant_arglist,list(u_h=u_h,v_h=v_h)))
if ( ! GLMMbool) {
ZAL_scaling <- 1/sqrt(wranefblob$w.ranef*H_global_scale) ## Q^{-1/2}/s
if (TRUE) {
## alternative clause shows the meaning. This is distinctly faster.
scaledZAL <- .m_Matrix_times_Dvec(ZAL, ZAL_scaling)
if (inherits(ZAL,"Matrix")) {
# This block of code assumes Xscal (IO_ZX) has no @diag component
Xscal@x[which_i_affected_rows] <- scaledZAL@x ## should create an error if some elements are stored in @diag
} else {
Xscal[n_u_h+seq(nobs),seq_n_u_h] <- scaledZAL
}
} else Xscal <- .make_Xscal(ZAL, ZAL_scaling = ZAL_scaling, AUGI0_ZX=processed$AUGI0_ZX,n_u_h=n_u_h)
}
}
}
muetablob <- .muetafn(eta=eta,BinomialDen=processed$BinomialDen,processed=processed)
if ( ! LMMbool ) {
## weight_X and Xscal vary within loop if ! LMM since at least the GLMweights in w.resid change
w.resid <- .calc_w_resid(muetablob$GLMweights,phi_est)
weight_X <- .calc_weight_X(w.resid, H_global_scale) ## sqrt(s^2 W.resid)
sXaug <- do.call(mMatrix_method,
list(Xaug=Xscal, weight_X=weight_X, w.ranef=wranefblob$w.ranef, H_global_scale=H_global_scale))
} ## ergo sXaug is not updated for LMM (no need to)
}
beta_eta <- Vscaled_beta[n_u_h+seq_len(pforpv)]
##### assessment of convergence
if (innerj<maxit.mean) {
relV_beta <- c(v_h*sqrt(wranefblob$w.ranef),beta_eta) ## convergence on v_h relative to sqrt(w.ranef)
abs_d_relV_beta <- abs(relV_beta - old_relV_beta)
not_moving <- ( ( ! is.null(old_relV_beta)) && mean(abs_d_relV_beta) < loc_Xtol_rel )
if (is.na(not_moving)) {
if (anyNA(relV_beta)) {
if ( ! is.null(damped_WLS_blob)) {
message(paste("innerj=",innerj,"damping=",damping,"lik=",damped_WLS_blob$lik))
stop("Numerical problem despite Levenberg algorithm being used: complain.")
} else stop("Numerical problem: try control.HLfit=list(LevenbergM=TRUE)")
} else stop("Error in evaluating break condition")
}
if (not_moving) break ## sufficient condition here
if ( ! (is_HL1_1 && LevenbergM)) { ## possible reversal of condition from F to T in LevM PQL !!!!
old_relV_beta <- relV_beta
} ## ELSE old_relV_beta controlled in block for which_LevMar_step !!
} else break
} ################ E N D LOOP ##############
if (trace>1L && (LevenbergM)) { ## only tracing
maxs_grad <- c(max(abs(m_grad_obj[seq_n_u_h])),max(abs(m_grad_obj[-seq_n_u_h])))
cat("iter=",innerj,", max(|grad|): v=",maxs_grad[1L],"beta=",maxs_grad[2L],";")
}
names(beta_eta) <- colnames(X.pv)
if (! is.null(damped_WLS_blob)) {
fitted <- damped_WLS_blob$fitted
weight_X <- damped_WLS_blob$weight_X
}
RESU <- list(sXaug=sXaug,
## used by calc_APHLs_from_ZX: (in particular can use Vscaled values contained in fitted)
fitted=fitted, #zAug=zAug,
weight_X=weight_X, nobs=nobs, pforpv=pforpv, seq_n_u_h=seq_n_u_h, u_h=u_h,
muetablob=muetablob,
lambda_est=lambda_est,
phi_est=phi_est,
## used by other code
beta_eta=beta_eta, w.resid=w.resid, wranefblob=wranefblob,
v_h=v_h, eta=eta, innerj=innerj)
return(RESU)
}
.intervalStep_ZX <- function(old_Vscaled_beta,sXaug,szAug,currentlik,for_intervals,currentDy) {
#print((control.HLfit$intervalInfo$fitlik-currentlik)/(control.HLfit$intervalInfo$MLparm-old_betaV[parmcol]))
## voir code avant 18/10/2014 pour une implem rustique de VenzonM pour debugage
## somewhat more robust algo (FR->FR: still improvable ?), updates according to a quadratic form of lik near max
## then target.dX = (current.dX)*sqrt(target.dY/current.dY) where dX,dY are relative to the ML x and y
## A nice thing of this conception is that if the target lik cannot be approached,
## the inferred x converges to the ML x => this x won't be recognized as a CI bound (important for locoptim)
parmcol_ZX <- for_intervals$parmcol_ZX
Vscaled_beta <- rep(NA,length(old_Vscaled_beta))
if (currentDy <0) {
Vscaled_beta[parmcol_ZX] <- old_Vscaled_beta[parmcol_ZX]
} else {
currentDx <- (old_Vscaled_beta[parmcol_ZX]-for_intervals$MLparm)
targetDy <- (for_intervals$fitlik-for_intervals$targetlik)
Dx <- currentDx*sqrt(targetDy/currentDy)
## pb is if Dx=0 , Dx'=0... and Dx=0 can occur while p_v is still far from the target, because other params have not converged.
## FR->FR patch:
if (currentDy<targetDy) { ## we are close to the ML: we extrapolate a bit more confidently
min_abs_Dx <- for_intervals$asympto_abs_Dparm/1000
} else min_abs_Dx <- 1e-6 ## far from ML: more cautious move our of Dx=0
Dx <- sign(currentDx)*max(abs(Dx),min_abs_Dx)
Vscaled_beta[parmcol_ZX] <- for_intervals$MLparm + Dx
}
locsXaug <- sXaug[,-(parmcol_ZX),drop=FALSE]
locszAug <- as.matrix(szAug-sXaug[,parmcol_ZX]*Vscaled_beta[parmcol_ZX])
Vscaled_beta[-(parmcol_ZX)] <- get_from_MME(locsXaug,szAug=locszAug)
return(list(Vscaled_beta=Vscaled_beta)) # levQ ispresumably always dense
}
.intervalStep_glm <- function(old_beta,sXaug,szAug,currentlik,for_intervals,currentDy) {
#print((control.HLfit$intervalInfo$fitlik-currentlik)/(control.HLfit$intervalInfo$MLparm-old_betaV[parmcol]))
## voir code avant 18/10/2014 pour une implem rustique de VenzonM pour debugage
## somewhat more robust algo (FR->FR: still improvable ?), updates according to a quadratic form of lik near max
## then target.dX = (current.dX)*sqrt(target.dY/current.dY) where dX,dY are relative to the ML x and y
## A nice thing of this conception is that if the target lik cannot be approached,
## the inferred x converges to the ML x => this x won't be recognized as a CI bound (important for locoptim)
parmcol_X <- for_intervals$parmcol_X
beta <- rep(NA,length(old_beta))
if (currentDy <0) {
beta[parmcol_X] <- old_beta[parmcol_X]
} else {
currentDx <- (old_beta[parmcol_X]-for_intervals$MLparm)
targetDy <- (for_intervals$fitlik-for_intervals$targetlik)
Dx <- currentDx*sqrt(targetDy/currentDy)
## pb is if Dx=0 , Dx'=0... and Dx=0 can occur while p_v is still far from the target, because other params have not converged.
## FR->FR patch:
if (currentDy<targetDy) { ## we are close to the ML: we extrapolate a bit more confidently
min_abs_Dx <- for_intervals$asympto_abs_Dparm/1000
} else min_abs_Dx <- 1e-6 ## far from ML: more cautious move our of Dx=0
Dx <- sign(currentDx)*max(abs(Dx),min_abs_Dx)
beta[parmcol_X] <- for_intervals$MLparm + Dx
}
locsXaug <- sXaug[,-(parmcol_X),drop=FALSE]
locszAug <- as.matrix(szAug-sXaug[,parmcol_X]*beta[parmcol_X])
beta[-(parmcol_X)] <- get_from_MME(locsXaug,szAug=locszAug)
return(list(beta=beta)) # levQ ispresumably always dense
}
|
6eea0903be1df93db8f3e45022eb89f57ae449fb
|
d70911c992652597604689ac46a6f069da533e40
|
/cachematrix.R
|
34a3f86e0ae4e90aba5dec14cd183c1aa4286258
|
[] |
no_license
|
josephl/ProgrammingAssignment2
|
2dd39634de0a963a2c81d00f7325ac5342bf0d1e
|
bdc90a10225af05f9681f47159b6476421383d5f
|
refs/heads/master
| 2021-01-17T15:05:34.502763
| 2014-11-23T04:51:35
| 2014-11-23T04:51:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,063
|
r
|
cachematrix.R
|
## Programming Assignment 2
## Joseph Lee
## These functions (makeCacheMatrix, cacheSolve) cache the inverse of a matrix,
## since computing inverses of large matrices can be quite expensive.
## This function creates a special "matrix" object that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setInverse <- function (i) {
inv <<- i
}
getInverse <- function() inv
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## This function computes the inverse of the special "matrix" returned by
## makeCacheMatrix above. If the inverse has already been calculated (and the
## matrix has not changed), then cacheSolve should retrieve the inverse from
## the cache
cacheSolve <- function(x, ...) {
i <- x$getInverse()
if (!is.null(i)) {
message("getting cached inverse")
return(i)
}
data <- x$get()
i <- solve(data)
x$setInverse(i)
i
}
|
13b7b9767ee9df22385a9ac3633b3a07d4f0b932
|
d8a644476b2772a4e327e05a019c5f41a33da224
|
/general_skew_mode-final right place.r
|
79230c4ab847877c61ba898c267594dff39b4796
|
[] |
no_license
|
BaderAlruwaili/R-package-for-merging-of-Skewed-normal-mixtures-
|
bbae5545888394f3dabd404467284db0e4837f3c
|
6bf25d02f2de45c0e5baf5a576671b087cf607dc
|
refs/heads/master
| 2020-04-16T04:26:15.844127
| 2019-01-11T16:04:14
| 2019-01-11T16:04:14
| 165,267,052
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 6,388
|
r
|
general_skew_mode-final right place.r
|
############################################################
#
library(sn)
sn.mode<- function(x,alpha,xi=0,omega=1){
z=(x-xi)/omega
# I am making z as the axis
#skewness
#pnorm,and dnorm of normal distribution
PHI<- pnorm(alpha*z)
phi<- dnorm(alpha*z)
# To find the mode of skew normal distribution by using the first derivation of skew normal distribution
# these parameters of the first derivative of skew normal distribution
# for more information of a , and p please see the pdf file
a<- (-z)*PHI
b<-alpha*phi
f<- a+b
return(f)
}
x=seq(-5,5,by=.1)
plot(z,sn.mode(x,4,0,0),typ="l")
abline(h=0,col=2)
alpha=2
xi=0
omega=1
upper=alpha+1
mymode=uniroot(sn.mode,lower=xi-5,upper=xi+ 5,alpha=alpha,xi=xi,omega=omega)$root
# To check if the mode is in the right place check with other values
#..of alphavictor
cat(mymode)
curve(dsn(x,xi=xi,omega=omega,alpha=alpha),-6,6)
# to change the name of x, and y
curve(dsn(x,xi=xi,omega=omega,alpha=alpha),-6,6,xlab='x',ylab='Density')
#curve(dsn(x,xi=2,alpha=alpha),-3,3)
abline(v=mymode,col=2 )
##Mode and Mean
######### UNIVARIATRE
fun=function(z,lambda=2){
return(0-z*pnorm(lambda*z)+lambda*dnorm(lambda*z))
}
alpha=2
pdf1 <- dmsn(as.matrix(x,ncol=1), 0, 1, alpha=alpha)
plot(x,pdf1,type="l")
pdf1.mean=sqrt(2/pi) * alpha/sqrt(1+alpha^2)
abline(v=pdf1.mean,col=2) fun=function(z,lambda=2){
return(0-z*pnorm(lambda*z)+lambda*dnorm(lambda*z))
}
alpha=4
pdf1 <- dmsn(as.matrix(x,ncol=1), 0, 1, alpha=alpha)
plot(x,pdf1,type="l",xlab='x',ylab='Density')
pdf1.mean=sqrt(2/pi) * alpha/sqrt(1+alpha^2)
pdf1.mean
abline(v=pdf1.mean,col=3)
pdf1.mode=uniroot(fun,lower=0,upper=pdf1.mean,lambda=alpha)$root
pdf1.mode
abline(v=pdf1.mode,col=2)
legend("topright",c("Mode","Mean" ),col=c(2,3),lwd=c(2,1),cex=.9)
par(mfrow=c(1,2))
############ this is the final code for mean and mode of skew normal to gother ################################################
#
library(sn)
myfunction<- function(x,alpha,xi=0,omega=1){
z=(x-xi)/omega
# I am making z as the axis
#skewness
#pnorm,and dnorm of normal distribution
PHI<- pnorm(alpha*z)
phi<- dnorm(alpha*z)
# To find the mode of skew normal distribution by using the first derivation of skew normal distribution
# these parameters of the first derivative of skew normal distribution
# for more information of a , and p please see the pdf file
a<- (-z)*PHI
b<-alpha*phi
f<- a+b
return(f)
}
x=seq(-5,5,by=.1)
plot(z,myfunction(x,4,0,0),typ="l")
abline(h=0,col=2)
alpha=4
xi=0
omega=1
upper=alpha+1
mymode=uniroot(myfunction,lower=xi-5,upper=xi+ 5,alpha=alpha,xi=xi,omega=omega)$root
# To check if the mode is in the right place check with other values
#..of alphavictor
cat(mymode)
#curve(dsn(x,xi=xi,omega=omega,alpha=alpha),-5,5)
# to change the name of x, and y
curve(dsn(x,xi=xi,omega=omega,alpha=alpha),-5,5,xlab='x',ylab='Density')
#curve(dsn(x,xi=2,alpha=alpha),-3,3)
abline(v=mymode,col=2 )
pdf1 <- dmsn(as.matrix(x,ncol=1), 0, 1, alpha=alpha)
# plot(x,pdf1,type="l",xlab='x',ylab='Density')
pdf1.mean=sqrt(2/pi) * alpha/sqrt(1+alpha^2)
pdf1.mean
abline(v=pdf1.mean,col=3)
legend("topright",c("Mode","Mean" ),col=c(2,3),lwd=c(2,1),cex=.9)
# for -
library(sn)
myfunction<- function(x,alpha,xi=0,omega=1){
z=(x-xi)/omega
# I am making z as the axis
#skewness
#pnorm,and dnorm of normal distribution
PHI<- pnorm(alpha*z)
phi<- dnorm(alpha*z)
# To find the mode of skew normal distribution by using the first derivation of skew normal distribution
# these parameters of the first derivative of skew normal distribution
# for more information of a , and p please see the pdf file
a<- (-z)*PHI
b<-alpha*phi
f<- a+b
return(f)
}
x=seq(-5,5,by=.1)
plot(z,myfunction(x,4,0,0),typ="l")
#abline(h=0,col=2)
alpha=-4
xi=0
omega=1
upper=alpha+1
mymode=uniroot(myfunction,lower=xi-5,upper=xi+ 5,alpha=alpha,xi=xi,omega=omega)$root
# To check if the mode is in the right place check with other values
#..of alphavictor
cat(mymode)
#curve(dsn(x,xi=xi,omega=omega,alpha=alpha),-5,5)
# to change the name of x, and y
curve(dsn(x,xi=xi,omega=omega,alpha=alpha),-5,5,xlab='x',ylab='Density')
#curve(dsn(x,xi=2,alpha=alpha),-3,3)
abline(v=mymode,col=2 )
pdf1 <- dmsn(as.matrix(x,ncol=1), 0, 1, alpha=alpha)
# plot(x,pdf1,type="l",xlab='x',ylab='Density')
pdf1.mean=sqrt(2/pi) * alpha/sqrt(1+alpha^2)
pdf1.mean
abline(v=pdf1.mean,col=3)
legend("topright",c("Mode","Mean" ),col=c(2,3),lwd=c(2,1),cex=.9)
# for 0
library(sn)
myfunction<- function(x,alpha,xi=0,omega=1){
z=(x-xi)/omega
# I am making z as the axis
#skewness
#pnorm,and dnorm of normal distribution
PHI<- pnorm(alpha*z)
phi<- dnorm(alpha*z)
# To find the mode of skew normal distribution by using the first derivation of skew normal distribution
# these parameters of the first derivative of skew normal distribution
# for more information of a , and p please see the pdf file
a<- (-z)*PHI
b<-alpha*phi
f<- a+b
return(f)
}
x=seq(-5,5,by=.1)
plot(z,myfunction(x,4,0,0),typ="l")
abline(h=0,col=2)
alpha=0
xi=0
omega=1
upper=alpha+1
mymode=uniroot(myfunction,lower=xi-5,upper=xi+ 5,alpha=alpha,xi=xi,omega=omega)$root
# To check if the mode is in the right place check with other values
#..of alphavictor
cat(mymode)
#curve(dsn(x,xi=xi,omega=omega,alpha=alpha),-5,5)
# to change the name of x, and y
curve(dsn(x,xi=xi,omega=omega,alpha=alpha),-5,5,xlab='x',ylab='Density')
#curve(dsn(x,xi=2,alpha=alpha),-3,3)
abline(v=mymode,col=2 )
legend("topright",c("Mode" ),col=c(2),lwd=c(2,1),cex=.9)
pdf1 <- dmsn(as.matrix(x,ncol=1), 0, 1, alpha=alpha)
plot(x,pdf1,type="l",xlab='x',ylab='Density')
pdf1.mean=sqrt(2/pi) * alpha/sqrt(1+alpha^2)
pdf1.mean
abline(v=pdf1.mean,col=3)
legend("topright",c("Mean" ),col=c(3),lwd=c(2,1),cex=.9)
|
be2776a0cb031b0148d21135e6b77fe7140b825a
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/recexcavAAR/examples/cootrans.Rd.R
|
90042109ef515b8493e7e572c81cc1507cfdb40f
|
[] |
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
| 548
|
r
|
cootrans.Rd.R
|
library(recexcavAAR)
### Name: cootrans
### Title: Tool for transforming local metric coordinates
### Aliases: cootrans
### ** Examples
coord_data <- data.frame(
loc_x = c(1,3,1,3),
loc_y = c(1,1,3,3),
abs_x = c(107.1,107,104.9,105),
abs_y = c(105.1,107,105.1,106.9)
)
data_table <- data.frame(
x = c(1.5,1.2,1.6,2),
y = c(1,5,2.1,2),
type = c("flint","flint","pottery","bone")
)
new_frame <- cootrans(coord_data, c(1,2,3,4), data_table, c(1,2))
check_data <- cootrans(coord_data, c(1,2,3,4), data_table, c(1,2), checking = TRUE)
|
3c7e47da366f94c5637ec38b28b8737606fd6f8e
|
57c3760975cdba7133cd7a8296127d7da6b59c1a
|
/Homework/Jose.Picon_HW3.R
|
352bc2d7ec2830f6e040fd29cb97b31fbbd0b106
|
[] |
no_license
|
josepicon/IST-687
|
8b98d714baab48f6803caaa91b4aee715ae178e1
|
a2ef83f300aaf8ec561a3979b3e997d311b4fc0c
|
refs/heads/master
| 2020-03-30T22:07:40.109720
| 2018-12-17T23:21:37
| 2018-12-17T23:21:37
| 151,655,431
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,131
|
r
|
Jose.Picon_HW3.R
|
#Cleaning/munging dataframes
#Step 1: Create a function (named readStates) to read a CSV file into R
#1: Note that you are to read a URL, not a file local to your computer
readStates <- read.csv(url("http://www2.census.gov/programs-surveys/popest/tables/2010-2011/state/totals/nst-est2011-01.csv"))
#Step 2: Clean the dataset
readStates
#remove rows, make sure there are 51 rows
readStates <- readStates[-c(1:8, 60:66),]
#remove columns, make sure there are only 5 columns
readStates <- readStates[-c(6, 7, 8, 9, 10)]
readStates
#rename columns
colnames(readStates) [1] <- "stateName"
colnames(readStates) [2] <- "base2010"
colnames(readStates) [3] <- "base2011"
colnames(readStates) [4] <- "Jul2010"
colnames(readStates) [5] <- "Jul2011"
readStates
#claen up population data (remove commas)
readStates$base2010 <- gsub("\\,","",readStates$base2010)
readStates$base2010 <- as.numeric(readStates$base2010)
readStates$base2011 <- gsub("\\,","",readStates$base2011)
readStates$base2011 <- as.numeric(readStates$base2011)
readStates$Jul2010 <- gsub("\\,","",readStates$Jul2010)
readStates$Jul2010 <- as.numeric(readStates$Jul2010)
readStates$Jul2011 <- gsub("\\,","",readStates$Jul2011)
readStates$Jul2011 <- as.numeric(readStates$Jul2011)
readStates
#Eliminate periods in state names
readStates$stateName <-gsub("\\.","", readStates$stateName)
readStates
#Step 3: Store and explore the dataset
#store the dataset into a data frame, called dfStates
dfStates <- data.frame(readStates)
dfStates
mean(dfStates$Jul2011)
#Step4: Find the state with the Highest Population
#Based on the July2011 data, what is the population of the state with the highest population? What is the name of that state?
#option1
myFunc3 <- function(x,b){
index <- which.max(x)
rnames <- rownames(b)
state <-rnames[index]
return(state)
}
myFunc3(dfStates$Jul2011, dfStates)
#Sort the data, in increasing order, based on the July2011 data.
dfStates[order(dfStates$Jul2011),]
#Step 5: Expore the distribution of the states
#Write a function that takes two parameters. The first is a vector and the second is a number.
#The function will return the percentage of the elements within the vector that is less than the same (i.e. the cumulative distribution below the value provided).
#For example, if the vector had 5 elements (1,2,3,4,5), with 2 being the number passed into the function, the function would return 0.2 (since 20% of the numbers were below 2).
index1 <- mean(dfStates$Jul2011)
d <- dfStates$Jul2011 #set the list of values for v
myFunc2 <- function(v,z) #x is min value, z is max value
{
h <- v[v>z] #numbers inside the vector greater than the value
e <- length(h) #length of vector with numbers greater than value
l <- length(v) #length of vector d <- (dfStates$Jul2011)
p <- e/l
return(p)
}
myFunc2(d, index1) #call the function and send 1 vetor and 1 value
#option 2, max value, Jul2011 vector
index2 <- max(dfStates$Jul2011)
k <- dfStates$Jul2011
myFunc2(k, index2)
#option3, median value, Jul2011 vector
index3 <- median(dfStates$Jul2011)
n <- dfStates$Jul2011
myFunc2(n, index3)
|
45bb21014d6560e22fe0a1b11ff04da4457f1acf
|
b6b470cdf0fec7037b74858efc64a8adf652a514
|
/Constrained ordination.R
|
d624023b09aa7d5cb84e4cbb47171cd2845dd714
|
[] |
no_license
|
BenjaminGazeau/Quantitative-Ecology
|
9a8b4875b1dd75a5149a3fa03c460c63bd6e6ab0
|
18a02533b057be9a680e4dd206259fadc58e115a
|
refs/heads/master
| 2023-07-01T06:15:54.247930
| 2021-08-03T14:14:12
| 2021-08-03T14:14:12
| 382,034,627
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 6,777
|
r
|
Constrained ordination.R
|
# Load Packages
library(tidyverse)
library(betapart)
library(vegan)
library(gridExtra)
library(grid)
library(gridBase)
library(tidyr)
# Load Data
spp <- read.csv('data/SeaweedsSpp.csv', row.names = 1)
dim(spp) # 58 rows and 847 cols
# Setup Data
# We want to focus on species turnover without a nestedness-resultant influence...
Y.core <- betapart.core(spp) # computes basic qualities needed for computing multiple-site beta diversity measures and pairwise dissimilarity matrices
Y.pair <- beta.pair(Y.core, index.family = "sor") # computes 3 distance matrices accounting for turnover, nestedness-resultant and total dissimilarity
# Let Y1 be the turnover component (beta-sim):
Y1 <- as.matrix(Y.pair$beta.sim)
# Load Env Data
load("data/SeaweedEnv.RData")
dim(env) # 58 rows and 18 cols
# We select only some of the thermal variables; the rest are collinear with the ones we import
E1 <- dplyr::select(env, febMean, febRange, febSD, augMean,
augRange, augSD, annMean, annRange, annSD)
E1 <- decostand(E1, method = "standardize") # Calculate z-scores
# Load Bioregions
# We can parition the data into 4 recognised bioregions and colour code the figure accordingly
bioreg <- read.csv('data/bioregions.csv', header = TRUE)
head(bioreg) # bolton = the bioregion
# Load geographical coordinates for coastal section
sites <- read.csv("data/sites.csv")
sites <- sites[, c(2, 1)] # swaps the cols around so Lon is first, then Lat
head(sites)
dim(sites) # 58 rows and 2 cols
# Start the db-RDA
# fit the full model:
rda_full <- capscale(Y1 ~., E1)
summary(rda_full)
# species scores are missing, since we provided only a distance matrix
# Is the fit significant?
anova(rda_full) # F = 40.88 and p < 0.05 --> yes
# Compute adjusted R-squared:
rda_full_R2 <- RsquareAdj(rda_full)$adj.r.squared
round(rda_full_R2, 2)
# Inertia accounted for by constraints:
round(sum(rda_full$CCA$eig), 2)
# Remaining (unconstrained) inertia:
round(sum(rda_full$CA$eig), 2)
# Total inertia:
round(rda_full$tot.chi, 2)
# What is the variation explained by the full set of environmental variables?
round(sum(rda_full$CCA$eig) / rda_full$tot.chi * 100, 2) # in %
# VIF
# We check for collinearity using variance inflation factors (VIF), and retain a
# subset of non-collinear variables to include in the reduced/final model.
# Commonly, values over 10 indicate redundant constraints, so we can run VIF
# iteratively, each time removing the highest VIF until they are all mostly below 10
vif.cca(rda_full)
# drop annMean
E2 <- dplyr::select(E1, -annMean)
rda_sel1 <- capscale(Y1 ~., E2) # new, temp RDA
vif.cca(rda_sel1)
# drop febMean
E3 <- dplyr::select(E2, -febMean)
rda_sel2 <- capscale(Y1 ~., E3)
vif.cca(rda_sel2)
# this looks acceptable
# We can construct the final model and calculate the significance
rda_final <- rda_sel2
anova(rda_final) # F = 45.68 and p < 0.05
# Which axes are significant?
anova(rda_final, by = 'axis')
# Extract significant variables in E3 that are influential in the final model
(rda_final_axis_test <- anova(rda_final, by = "terms"))
# The significant variables are:
rda_final_ax <- which(rda_final_axis_test[, 4] < 0.05)
rda_final_sign_ax <- colnames(E3[,rda_final_ax])
rda_final_sign_ax
# The adjusted R-squared for the constraints:
round(rda_final_R2 <- RsquareAdj(rda_final)$adj.r.squared, 2)
# Variance explained by reduced (final) model:
round(sum(rda_final$CCA$eig) / rda_final$tot.chi * 100, 2)
# Biplot scores for constraining variables:
scores(rda_final, display = "bp", choices = c(1:2))
# Ordination Diagrams
# Recreating the figure from Smit et al. (2017):
# use scaling = 1 or scaling = 2 for site and species scaling, respectively
rda_final_scrs <- scores(rda_final, display = c("sp", "wa", "lc", "bp"))
# below I plot the wa (site) scores rather than lc (constraints) scores
site_scores <- data.frame(rda_final_scrs$site) # the wa scores
site_scores$bioreg <- bioreg$bolton
site_scores$section <- seq(1:58)
biplot_scores <- data.frame(rda_final_scrs$biplot)
biplot_scores$labels <- rownames(biplot_scores)
biplot_scores_sign <- biplot_scores[biplot_scores$labels %in% rda_final_sign_ax,]
ggplot(data = site_scores, aes(x = CAP1, y = CAP2, colour = bioreg)) +
geom_point(size = 5.0, shape = 24, fill = "white") +
geom_text(aes(label = section), size = 3.0, col = "black") +
geom_label(data = biplot_scores_sign,
aes(CAP1, CAP2, label = rownames(biplot_scores_sign)),
color = "black") +
geom_segment(data = biplot_scores_sign,
aes(x = 0, y = 0, xend = CAP1, yend = CAP2),
arrow = arrow(length = unit(0.2, "cm"), type = "closed"),
color = "lightseagreen", alpha = 1, size = 0.7) +
xlab("CAP1") + ylab("CAP2") +
ggtitle(expression(paste("Significant thermal variables and ", beta[sim]))) +
theme_grey() +
theme(panel.grid.minor = element_blank(),
legend.position = "none",
aspect.ratio = 0.8)
# Dealing with Factor Variables
E4 <- E3
# append the bioregs after the thermal vars
E4$bioreg <- bioreg$bolton
head(E4)
rda_cat <- capscale(Y1 ~., E4)
plot(rda_cat)
# default plot looks okay...
# but not great. Plot the class (factor) centroids in ggplot():
# also extractthe factor centroids for the bioregions
rda_cat_scrs <- scores(rda_cat, display = c("sp", "wa", "lc", "bp", "cn"))
site_scores <- data.frame(rda_cat_scrs$site) # the wa scores
site_scores$bioreg <- bioreg$bolton
site_scores$section <- seq(1:58)
biplot_scores <- data.frame(rda_cat_scrs$biplot)
biplot_scores$labels <- rownames(biplot_scores)
biplot_scores_sign <- biplot_scores[biplot_scores$labels %in% rda_final_sign_ax,]
bioreg_centroids <- data.frame(rda_cat_scrs$centroids)
bioreg_centroids$labels <- rownames(bioreg_centroids)
ggplot(data = site_scores, aes(CAP1, CAP2, colour = bioreg)) +
geom_point(size = 5.0, shape = 24, fill = "white") +
geom_text(aes(label = section), size = 3.0, col = "black") +
geom_label(data = biplot_scores_sign,
aes(CAP1, CAP2, label = rownames(biplot_scores_sign)),
color = "black") +
geom_segment(data = biplot_scores_sign,
aes(x = 0, y = 0, xend = CAP1, yend = CAP2),
arrow = arrow(length = unit(0.2, "cm"), type = "closed"),
color = "lightseagreen", alpha = 1, size = 0.7) +
geom_label(data = bioreg_centroids,
aes(x = CAP1, y = CAP2,
label = labels), size = 4.0,
col = "black", fill = "yellow") +
xlab("CAP1") + ylab("CAP2") +
ggtitle(expression(paste("Significant thermal variables and ", beta[sim]))) +
theme_grey() +
theme(panel.grid.minor = element_blank(),
legend.position = "none",
aspect.ratio = 0.8)
|
a3e92602b0d0cd50ef07e394ae6f913a9ca8dce0
|
6e400e8825aa796f6258ece58a2ea146d02b9711
|
/fj_DT_fullvar.r
|
003ca241f94887af676f36f507e451a43bc05e1c
|
[] |
no_license
|
kmoh19/Weather_Sensor
|
836a8223b883b7e2bfde51cf67b98616d0b119d0
|
d78f5530a344ad5dc7cd5e2fff87f1ffbe107229
|
refs/heads/master
| 2020-12-13T03:25:53.841982
| 2020-01-16T11:13:34
| 2020-01-16T11:13:34
| 234,298,944
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,279
|
r
|
fj_DT_fullvar.r
|
library(rpart)
library(rpart.plot)
weather<-read.csv('C:\\Users\\7222115\\Desktop\\DS_sensor_weather.csv',header=TRUE,sep=',')
weather_nna<-weather %>% na.omit()
weather_nna_nr<-weather_nna[,-11]
weather_nna_nr_rf<-(weather_nna_nr %>% mutate(relative_humidity_pm_rf=relative_humidity_pm>30))[,-10]
weather_nna_nr_rf$relative_humidity_pm_r2<-factor(weather_nna_nr_rf$relative_humidity_pm_rf, levels = c(TRUE,FALSE), labels = c("High","Low"))
weather_nna_nr_rf$relative_humidity_pm_r2 <- relevel(weather_nna_nr_rf$relative_humidity_pm_r2, ref = "Low")
weather_cln<-weather_nna_nr_rf[,-10]
train_ind <- sample(seq_len(nrow(weather_cln)), size = smp_size)
train <- weather_cln[train_ind, ]
test <- weather_cln[-train_ind, ]
weather_mod<-rpart(relative_humidity_pm_r2~.,train,method='class',control= rpart.control(cp=0))
pred<-predict(weather_mod,test,type='class')
confusionMatrix(pred,test$relative_humidity_pm_r2)
rpart.plot(weather_mod, type = 3, box.palette = c("green","red"), fallen.leaves = TRUE)
weather_mod_pruned<-rpart(relative_humidity_pm_r2~.,train,method='class',control= rpart.control(cp=0.1))
pred_pruned<-predict(weather_mod_pruned,test,type='class')
confusionMatrix(pred_pruned,test$relative_humidity_pm_r2)
|
46cf3fc045220674e8a05ba547d56e851bc09240
|
8103eedd31f9d263813495a77cefccb5038eb291
|
/CleanDataScript.R
|
5854cfe1af9d596441ce47aacaa5de2b6e4bdea6
|
[] |
no_license
|
kcp200607/CleanData
|
917e8ac26a182591bc0de81a9081288deab4ddb7
|
a9d0c61e5387b836408fd7c73497924c88d90bb7
|
refs/heads/master
| 2020-04-12T18:21:43.284360
| 2014-06-18T21:09:18
| 2014-06-18T21:09:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,557
|
r
|
CleanDataScript.R
|
sub_test <- read.table("subject_test.txt")
sub_train <- read.table("subject_train.txt")
features <- read.table("features.txt")
y_test <- read.table("y_test.txt")
x_test <- read.table("x_test.txt")
y_train <- read.table("y_train.txt")
x_train <- read.table("x_train.txt")
y_join <- rbind(y_test, y_train)
x_join <- rbind(x_test, x_train)
sub_join <- rbind(sub_test, sub_train)
y_join$V1 <- factor(y_join$V1)
levels(join$V1) <- list( walking = c("1"), walking_upstairs = c("2"), walking_downstairs = c("3"), sitting = c("4"), standing = c("5"), laying = c("6"))
colnames(y_join) = c("activity")
colnames(sub_join) = c("subject")
colnames(x_join)= features[,2]
extract <- function(df){
df_col<- ncol(df)
for (i in seq(1, df_col)){
#cat(names(df)[i])
if (!(grepl("mean", names(df)[i]) | grepl("std", names(df)[i]))){
df<- df[-i]
}
}
df
}
x_join_extrac <- extract(x_join)
tidyData <- cbind(sub_join, y_join, x_join_extrac)
extract2 <- function(df){
df_col<- ncol(df)
for (i in seq(1, df_col)){
#cat(names(df)[i])
if (!(grepl("mean", names(df)[i]))){
df<- df[-i]
}
}
df
}
x_join_extracV2 <- extract2(x_join)
tidyDataV2<- cbind(sub_join, y_join, x_join_extracV2)
|
d3d460d95633676b2376a00ceb29a0e53236678e
|
9fdd3e567cd49d00b1559a627dd865853556d0bc
|
/enveomics.R/man/enve.recplot2.__peakHist.Rd
|
61752857ea3c96ae60d0d3ab743dc3b3b7d7b092
|
[
"Artistic-2.0"
] |
permissive
|
yoyohashao/enveomics
|
ed8fa98dd98d3ef1940f86a9bbcc5f1dc879d135
|
eb4cd3ec4ba4a9479b9fd35048cf8e99a3ff0116
|
refs/heads/master
| 2021-01-14T08:35:12.484687
| 2016-01-13T20:50:27
| 2016-01-13T20:50:27
| 49,878,394
| 1
| 0
| null | 2016-01-18T13:24:46
| 2016-01-18T13:24:45
| null |
UTF-8
|
R
| false
| false
| 360
|
rd
|
enve.recplot2.__peakHist.Rd
|
\name{enve.recplot2.__peakHist}
\alias{enve.recplot2.__peakHist}
\title{enve recplot2 peakHist}
\description{Internal ancilliary function (see `enve.RecPlot2.Peak`).}
\usage{enve.recplot2.__peakHist(x, mids, counts = TRUE)}
\arguments{
\item{x}{
}
\item{mids}{
}
\item{counts}{
}
}
\author{Luis M. Rodriguez-R [aut, cre]}
|
60986766e80d2ebefd86b61ad8cf31e325189ef3
|
d1a360fc9e6f2415d4b9c5a7964d2cb7b4c01e45
|
/Bayesian Baseball 2018/scripts/Modeling/Comparison Models/adaptivepriors.r
|
0973d86f74f4de7e76ad1063852bc71bc72bc83e
|
[] |
no_license
|
blakeshurtz/Bayesian-Baseball
|
8ea89ac5d191c9fb2558ef2776f5e6e71cc88ddc
|
86d0cf8cd8fba05d108c0a7a677de6158f856b1a
|
refs/heads/master
| 2022-01-30T00:14:25.207927
| 2019-07-02T19:34:25
| 2019-07-02T19:34:25
| 146,781,829
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,581
|
r
|
adaptivepriors.r
|
###adaptive priors
c(h, hits_h, double_h, triple_h, HR_h, balls_h, hits_allowed_h, pballs_h, pstrikeouts_h, strikes_h)[home] ~ dmvnormNC(sigma_home,Rho_home),
c(a, hits_a, double_a, triple_a, HR_a, balls_a, hits_allowed_a, pballs_a, pstrikeouts_a, strikes_a)[away] ~ dmvnormNC(sigma_away,Rho_away),
sigma_home ~ dcauchy(0,2),
sigma_away ~ dcauchy(0,2),
Rho_home ~ dlkjcorr(4),
Rho_away ~ dlkjcorr(4),
###adaptive priors for coefficients
h[home] ~ dnorm(h_mu, h_sigma),
h_mu ~ dnorm(0,1),
h_sigma ~ dcauchy(0,2),
a[away] ~ dnorm(a_mu, a_sigma),
a_mu ~ dnorm(0,1)
a_sigma ~ dcauchy(0,2),
###
hits_h ~ dnorm(hits_h_mu, hits_h_sigma),
hits_h_mu ~ dnorm(0,1),
hits_h_sigma ~ dcauchy(0,2),
hits_a ~ dnorm(hits_a_mu, hits_a_sigma),
hits_a_mu ~ dnorm(0,1),
hits_a_sigma ~ dcauchy(0,2),
###
double_h ~ dnorm(double_h_mu, double_h_sigma),
double_h_mu ~ dnorm(0,1),
double_h_sigma ~ dcauchy(0,2),
double_a ~ dnorm(double_a_mu, double_a_sigma),
double_a_mu ~ dnorm(0,1),
double_a_sigma ~ dcauchy(0,2),
###
triple_h ~ dnorm(triple_h_mu, triple_h_sigma),
triple_h_mu ~ dnorm(0,1),
triple_h_sigma ~ dcauchy(0,2),
triple_a ~ dnorm(triple_a_mu, triple_a_sigma),
triple_a_mu ~ dnorm(0,1),
triple_a_sigma ~ dcauchy(0,2),
###
HR_h ~ dnorm(HR_h_mu, HR_h_sigma),
HR_h_mu ~ dnorm(0,1),
HR_h_sigma ~ dcauchy(0,2),
HR_a ~ dnorm(HR_a_mu, HR_a_sigma),
HR_a_mu ~ dnorm(0,1),
HR_a_sigma ~ dcauchy(0,2),
###
balls_h ~ dnorm(balls_h_mu, balls_h_sigma),
balls_h_mu ~ dnorm(0,1),
balls_h_sigma ~ dcauchy(0,2),
balls_a ~ dnorm(balls_a_mu, balls_a_sigma),
balls_a_mu ~ dnorm(0,1),
balls_a_sigma ~ dcauchy(0,2),
###
hits_allowed_h ~ dnorm(hits_allowed_h_mu, hits_allowed_h_sigma),
hits_allowed_h_mu ~ dnorm(0,1),
hits_allowed_h_sigma ~ dcauchy(0,2),
hits_allowed_a ~ dnorm(hits_allowed_a_mu, hits_allowed_a_sigma),
hits_allowed_a_mu ~ dnorm(0,1),
hits_allowed_a_sigma ~ dcauchy(0,2),
###
pballs_h ~ dnorm(pballs_h_mu, pballs_h_sigma),
pballs_h_mu ~ dnorm(0,1),
pballs_h_sigma ~ dcauchy(0,2),
pballs_a ~ dnorm(pballs_a_mu, pballs_a_sigma),
pballs_a_mu ~ dnorm(0,1),
pballs_a_sigma ~ dcauchy(0,2),
###
pstrikeouts_h ~ dnorm(pstrikeouts_h_mu, pstrikeouts_h_sigma),
pstrikeouts_h_mu ~ dnorm(0,1),
pstrikeouts_h_sigma ~ dcauchy(0,2),
pstrikeouts_a ~ dnorm(pstrikeouts_a_mu, pstrikeouts_a_sigma),
pstrikeouts_a_mu ~ dnorm(0,1),
pstrikeouts_a_sigma ~ dcauchy(0,2),
###
strikes_h ~ dnorm(strikes_h_mu, strikes_h_sigma),
strikes_h_mu ~ dnorm(0,1),
strikes_h_sigma ~ dcauchy(0,2),
strikes_a ~ dnorm(strikes_a_mu, strikes_a_sigma),
strikes_a_mu ~ dnorm(0,1),
strikes_a_sigma ~ dcauchy(0,2),'
|
dbe11480b6a5c5c5e776ebab278e5fe6c5872337
|
cdf3707ae58fa058ce220977bd6ff9172a735388
|
/3 Course Deliverables/IST 687 - Introduction to Data Science/Code and Data (California Protected Land Analysis)/Protected Land Areas of CA.R
|
45649e3cecc632ec80c2dc091a10464ac45b2982
|
[] |
no_license
|
lplawless/Applied-Data-Science-Portfolio
|
d26b5dfa01fa9c2b73dacb2acd954a1fbde0b6ca
|
d252d3be7f5311a391b49e590600eae9bc9612a3
|
refs/heads/master
| 2022-12-11T21:49:17.613171
| 2020-09-14T17:42:46
| 2020-09-14T17:42:46
| 282,275,445
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 151,643
|
r
|
Protected Land Areas of CA.R
|
#Index - Double click on the bracketed string and press Ctrl+F and then Enter to jump to that section.
# Load and prep [i001]
# Data Munging [i002]
# Descriptive Analysis [i003]
# Descriptive Charts [i003a]
# Descriptive Maps [i003b]
# Advanced Analysis [i004]
#--------------------------------------Load and prep [i001]--------------------------------------------------------------
#Activate libraries.
require(arulesViz)
require(caret)
require(crayon)
require(dplyr)
require(e1071)
require(GGally)
require(ggcorrplot)
require(ggiraph)
require(ggiraphExtra)
require(ggplot2)
require(ggpubr)
require(gridExtra)
require(kernlab)
require(mapproj)
require(maps)
require(mice)
require(readxl)
require(reshape2)
require(VIM)
#Load the Protected Land Data & Voter Data .csv file.
# ProtectedLand <- read.csv("~/Protected Land.csv")
# Voting <- read.csv("~/Voting.csv")
# Party <- read.csv("~/Party.csv")
# Centers <- read.csv("~/Centers.csv")
ProtectedLand <- read.csv(file.choose())
Voting <- read.csv(file.choose())
Party <- read.csv(file.choose())
Centers <- read.csv(file.choose())
mappingData <- read_excel(file.choose())
#--------------------------------------Data Munging [i002]--------------------------------------------------------------
#Clean Data - Rename columns to make them more understandable.
names(ProtectedLand)[2] <- "year"
names(ProtectedLand)[3] <- "county"
names(ProtectedLand)[4] <- "tract_id"
names(ProtectedLand)[5] <- "census_tract_population"
names(ProtectedLand)[6] <- "average_income"
names(ProtectedLand)[7] <- "median_housing_price"
names(ProtectedLand)[8] <- "county_number"
names(ProtectedLand)[10] <- "distance_to_tract"
names(ProtectedLand)[11] <- "county_population"
names(ProtectedLand)[12] <- "population_density_per_square_mile"
names(ProtectedLand)[18] <- "share_native_american"
names(ProtectedLand)[20] <- "share_pacific_islander"
names(Party)[1] <- "county"
names(Voting)[5] <- "voting_age_pop"
#Clean Data - Remove " County" from the county field. It's redundant and takes up space on visualizations.
# gsub() replaces the 1st arguement with the 2nd arguement while looking through the 3rd arguement.
ProtectedLand$county <- gsub(" County", "", ProtectedLand$county)
#Merge Party Data
ProtectedLand <- merge(ProtectedLand, Voting, by = "gisjoin")
ProtectedLand <- merge(ProtectedLand, Party, by.x = "county", by.y = "county")
ProtectedLand <- merge(ProtectedLand, Centers, by = "gisjoin")
# ####Using R Mice Package to impute missing values [average_income column]####
#
# ###Step 1: Confirm the existence of 'NA's within a column
#
# any(is.na(ProtectedLand$average_income)) ###Returns 'TRUE' Specifically, rows 1918, 2234, 2248, 2819, 4103 and 4213 are 'NA's.
#
# ###Step 2: Create a data.frame of at least two columns to work with
#
# miceAverage_Income <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$average_income)
#
# #####Step 3: Probably redundant of Step 1 above, but interesting nonetheless. This function creates a 'pattern' graphic
# ######that illustrates the number of rows in our dummy df with 0 missing values and the rows with 1 missing values.
#
# md.pattern(miceAverage_Income)
#
# #####Step 4: The R mice function develops potential imputed values for 'NA's using various types of regression.
# imputed_miceAverage_Income <- mice(miceAverage_Income, m=5, method = 'pmm', seed = 101)
#
# ######Step 5: We use the R Mice's 'compete' function to choose the results regression method (here, method '3')
# ######to be imputed in place of the 'NA's
#
# miceAverage_Income <- complete(imputed_miceAverage_Income,3)
#
# ###### Step 6: We replace the old average_income column values with the column that contains the six imputed values to replace 'NA's
# ProtectedLand$average_income <- miceAverage_Income$ProtectedLand.average_income
#
# #####Step 7: We confirm the absence of 'NA's within the replacement column
#
# any(is.na(ProtectedLand$average_income))
# ProtectedLand$average_income [1918] ##### For example, we see that the 'NA' formerly in row 1918 has been replaced with###
# ### with '31418'
# #Clearing unneeded object
# rm(imputed_miceAverage_Income)
# rm(miceAverage_Income)
#
# ######Using R Mice Package to impute missing values [median_housing_price]
#
# any(is.na(ProtectedLand$median_housing_price))
#
# miceMedianHousingPrice <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$median_housing_price)
# md.pattern(miceMedianHousingPrice)
# imputed_miceMedianHousingPrice <- mice(miceMedianHousingPrice, m=5, method = 'pmm', seed = 101)
# miceMedianHousingPrice <- complete(imputed_miceMedianHousingPrice,3)
# ProtectedLand$median_housing_price <- miceMedianHousingPrice$ProtectedLand.median_housing_price
#
# any(is.na(ProtectedLand$median_housing_price))
#
# #Clearing unneeded object
# rm(imputed_miceMedianHousingPrice)
# rm(miceMedianHousingPrice)
#
# ######Using R Mice Package to impute missing values [share_white]
#
# any(is.na(ProtectedLand$share_white))
#
# miceshare_white <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$share_white)
# md.pattern(miceshare_white)
# imputed_miceshare_white <- mice(miceshare_white, m=5, method = 'pmm', seed = 101)
# miceshare_white <- complete(imputed_miceshare_white,3)
# ProtectedLand$share_white <- miceshare_white$ProtectedLand.share_white
#
# any(is.na(ProtectedLand$share_white))
#
# #Clearing unneeded object
# rm(imputed_miceshare_white)
# rm(miceshare_white)
#
# ######Using R Mice Package to impute missing values [share_black]
#
# any(is.na(ProtectedLand$share_black))
#
# miceshare_black <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$share_black)
# md.pattern(miceshare_black)
# imputed_miceshare_black <- mice(miceshare_black, m=5, method = 'pmm', seed = 101)
# miceshare_black <- complete(imputed_miceshare_black,3)
# ProtectedLand$share_black <- miceshare_black$ProtectedLand.share_black
#
# any(is.na(ProtectedLand$share_black))
#
# #Clearing unneeded object
# rm(imputed_miceshare_black)
# rm(miceshare_black)
#
# ######Using R Mice Package to impute missing values [share_native_american]
#
# any(is.na(ProtectedLand$share_native_american))
#
# miceshare_native_american <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$share_native_american)
# md.pattern(miceshare_native_american)
# imputed_miceshare_native_american <- mice(miceshare_native_american, m=5, method = 'pmm', seed = 101)
# miceshare_native_american <- complete(imputed_miceshare_native_american,3)
# ProtectedLand$share_native_american <- miceshare_native_american$ProtectedLand.share_native_american
#
# any(is.na(ProtectedLand$share_native_american))
#
# #Clearing unneeded object
# rm(imputed_miceshare_native_american)
# rm(miceshare_native_american)
#
# ######Using R Mice Package to impute missing values [share_asian]
#
# any(is.na(ProtectedLand$share_asian))
#
# miceshare_asian <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$share_asian)
# md.pattern(miceshare_asian)
# imputed_miceshare_asian <- mice(miceshare_asian, m=5, method = 'pmm', seed = 101)
# miceshare_asian <- complete(imputed_miceshare_asian,3)
# ProtectedLand$share_asian <- miceshare_asian$ProtectedLand.share_asian
#
# any(is.na(ProtectedLand$share_asian))
#
# #Clearing unneeded object
# rm(imputed_miceshare_asian)
# rm(miceshare_asian)
#
# ######Using R Mice Package to impute missing values [share_pacific_islander]
#
# any(is.na(ProtectedLand$share_pacific_islander))
#
# miceshare_pacific_islander <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$share_pacific_islander)
# md.pattern(miceshare_pacific_islander)
# imputed_miceshare_pacific_islander <- mice(miceshare_pacific_islander, m=5, method = 'pmm', seed = 101)
# miceshare_pacific_islander <- complete(imputed_miceshare_pacific_islander,3)
# ProtectedLand$share_pacific_islander <- miceshare_pacific_islander$ProtectedLand.share_pacific_islander
#
# any(is.na(ProtectedLand$share_pacific_islander))
#
# #Clearing unneeded object
# rm(imputed_miceshare_pacific_islander)
# rm(miceshare_pacific_islander)
#
# ######Using R Mice Package to impute missing values [share_other]
#
# any(is.na(ProtectedLand$share_other))
#
# miceshare_other <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$share_other)
# md.pattern(miceshare_other)
# imputed_miceshare_other <- mice(miceshare_other, m=5, method = 'pmm', seed = 101)
# miceshare_other <- complete(imputed_miceshare_other,3)
# ProtectedLand$share_other <- miceshare_other$ProtectedLand.share_other
#
# any(is.na(ProtectedLand$share_other))
#
# #Clearing unneeded object
# rm(imputed_miceshare_other)
# rm(miceshare_other)
#
# ######Using R Mice Package to impute missing values [share_2plus]
#
# any(is.na(ProtectedLand$share_2plus))
#
# miceshare_2plus <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$share_2plus)
# md.pattern(miceshare_2plus)
# imputed_miceshare_2plus <- mice(miceshare_2plus, m=5, method = 'pmm', seed = 101)
# miceshare_2plus <- complete(imputed_miceshare_2plus,3)
# ProtectedLand$share_2plus <- miceshare_2plus$ProtectedLand.share_2plus
#
# any(is.na(ProtectedLand$share_2plus))
#
# #Clearing unneeded object
# rm(imputed_miceshare_2plus)
# rm(miceshare_2plus)
#
# ######Using R Mice Package to impute missing values [share_hispanic]
#
# any(is.na(ProtectedLand$share_hispanic))
#
# miceshare_hispanic <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$share_hispanic)
# md.pattern(miceshare_hispanic)
# imputed_miceshare_hispanic <- mice(miceshare_hispanic, m=5, method = 'pmm', seed = 101)
# miceshare_hispanic <- complete(imputed_miceshare_hispanic,3)
# ProtectedLand$share_hispanic <- miceshare_hispanic$ProtectedLand.share_hispanic
#
# any(is.na(ProtectedLand$share_hispanic))
#
# #Clearing unneeded object
# rm(imputed_miceshare_hispanic)
# rm(miceshare_hispanic)
#
# ######Using R Mice Package to impute missing values [lessthanHS]
#
# any(is.na(ProtectedLand$lessthanHS))
#
# micelessthanHS <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$lessthanHS)
# md.pattern(micelessthanHS)
# imputed_micelessthanHS <- mice(micelessthanHS, m=5, method = 'pmm', seed = 101)
# micelessthanHS <- complete(imputed_micelessthanHS,3)
# ProtectedLand$lessthanHS <- micelessthanHS$ProtectedLand.lessthanHS
#
# any(is.na(ProtectedLand$lessthanHS))
#
# #Clearing unneeded object
# rm(imputed_micelessthanHS)
# rm(micelessthanHS)
#
# ######Using R Mice Package to impute missing values [HSdiploma]
#
# any(is.na(ProtectedLand$HSdiploma))
#
# miceHSdiploma <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$HSdiploma)
# md.pattern(miceHSdiploma)
# imputed_miceHSdiploma <- mice(miceHSdiploma, m=5, method = 'pmm', seed = 101)
# miceHSdiploma <- complete(imputed_miceHSdiploma,3)
# ProtectedLand$HSdiploma <- miceHSdiploma$ProtectedLand.HSdiploma
#
# any(is.na(ProtectedLand$HSdiploma))
#
# #Clearing unneeded object
# rm(imputed_miceHSdiploma)
# rm(miceHSdiploma)
#
# ######Using R Mice Package to impute missing values [someCollege]
#
# any(is.na(ProtectedLand$someCollege))
#
# micesomeCollege <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$someCollege)
# md.pattern(micesomeCollege)
# imputed_someCollege <- mice(micesomeCollege, m=5, method = 'pmm', seed = 101)
# micesomeCollege <- complete(imputed_someCollege,3)
# ProtectedLand$someCollege <- micesomeCollege$ProtectedLand.someCollege
#
# any(is.na(ProtectedLand$someCollege))
#
# #Clearing unneeded object
# rm(imputed_someCollege)
# rm(micesomeCollege)
#
# ######Using R Mice Package to impute missing values [Associates]
#
# any(is.na(ProtectedLand$Associates))
#
# miceAssociates <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$Associates)
# md.pattern(miceAssociates)
# imputed_Associates <- mice(miceAssociates, m=5, method = 'pmm', seed = 101)
# miceAssociates <- complete(imputed_Associates,3)
# ProtectedLand$Associates <- miceAssociates$ProtectedLand.Associates
#
# any(is.na(ProtectedLand$Associates))
#
# #Clearing unneeded object
# rm(imputed_Associates)
# rm(miceAssociates)
#
# ######Using R Mice Package to impute missing values [Bachelors]
#
# any(is.na(ProtectedLand$Bachelors))
#
# miceBachelors <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$Bachelors)
# md.pattern(miceBachelors)
# imputed_Bachelors <- mice(miceBachelors, m=5, method = 'pmm', seed = 101)
# miceBachelors <- complete(imputed_Bachelors,3)
# ProtectedLand$Bachelors <- miceBachelors$ProtectedLand.Bachelors
#
# any(is.na(ProtectedLand$Bachelors))
#
# #Clearing unneeded object
# rm(imputed_Bachelors)
# rm(miceBachelors)
#
# ######Using R Mice Package to impute missing values [Masters]
#
# any(is.na(ProtectedLand$Masters))
#
# miceMasters <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$Masters)
# md.pattern(miceMasters)
# imputed_Masters <- mice(miceMasters, m=5, method = 'pmm', seed = 101)
# miceMasters <- complete(imputed_Masters,3)
# ProtectedLand$Masters <- miceMasters$ProtectedLand.Masters
#
# any(is.na(ProtectedLand$Masters))
#
# #Clearing unneeded object
# rm(imputed_Masters)
# rm(miceMasters)
#
# ######Using R Mice Package to impute missing values [Professional]
#
# any(is.na(ProtectedLand$Professional))
#
# miceProfessional <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$Professional)
# md.pattern(miceProfessional)
# imputed_Professional <- mice(miceProfessional, m=5, method = 'pmm', seed = 101)
# miceProfessional <- complete(imputed_Professional,3)
# ProtectedLand$Professional <- miceProfessional$ProtectedLand.Professional
#
# any(is.na(ProtectedLand$Professional))
#
# #Clearing unneeded object
# rm(imputed_Professional)
# rm(miceProfessional)
#
# ######Using R Mice Package to impute missing values [Doctorate]
#
# any(is.na(ProtectedLand$Doctorate))
#
# miceDoctorate <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$Doctorate)
# md.pattern(miceDoctorate)
# imputed_Doctorate <- mice(miceDoctorate, m=5, method = 'pmm', seed = 101)
# miceDoctorate <- complete(imputed_Doctorate,3)
# ProtectedLand$Doctorate <- miceDoctorate$ProtectedLand.Doctorate
#
# any(is.na(ProtectedLand$Doctorate))
#
# #Clearing unneeded object
# rm(imputed_Doctorate)
# rm(miceDoctorate)
#
# ######Using R Mice Package to impute missing values [Voted]
# any(is.na(ProtectedLand$Voted))
#
# miceVoted <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$Voted)
# md.pattern(miceVoted)
# imputed_Voted <- mice(miceVoted, m=5, method = 'pmm', seed = 101)
# miceVoted <- complete(imputed_Voted,3)
# ProtectedLand$Voted <- miceVoted$ProtectedLand.Voted
#
# any(is.na(ProtectedLand$Voted))
#
# #Clearing unneeded object
# rm(imputed_Voted)
# rm(miceVoted)
#
# ######Using R Mice Package to impute missing values [Registered]
# any(is.na(ProtectedLand$Registered))
#
# miceRegistered <- data.frame(ProtectedLand$census_tract_population, ProtectedLand$Registered)
# md.pattern(miceRegistered)
# imputed_Registered <- mice(miceRegistered, m=5, method = 'pmm', seed = 101)
# miceRegistered <- complete(imputed_Registered,3)
# ProtectedLand$Registered <- miceRegistered$ProtectedLand.Registered
#
# any(is.na(ProtectedLand$Registered))
#
# #Clearing unneeded object
# rm(imputed_Registered)
# rm(miceRegistered)
#
# # Clear the "Values" section
# rm(list=ls.str(mode='numeric'))
#--------------------------------------Descriptive Analysis [i003]--------------------------------------------------------------
#Generate a vector of unique counties
uniqueCounty <- unique(ProtectedLand$county)
# Create new fields calculating the population of the tract id based on ethnicity
ProtectedLand$number_white <- round(ProtectedLand$census_tract_population * ProtectedLand$share_white,0)
ProtectedLand$number_black <- round(ProtectedLand$census_tract_population * ProtectedLand$share_black,0)
ProtectedLand$number_native_american <- round(ProtectedLand$census_tract_population * ProtectedLand$share_native_american,0)
ProtectedLand$number_asian <- round(ProtectedLand$census_tract_population * ProtectedLand$share_asian,0)
ProtectedLand$number_pacific_islander <- round(ProtectedLand$census_tract_population * ProtectedLand$share_pacific_islander,0)
ProtectedLand$number_other <- round(ProtectedLand$census_tract_population * ProtectedLand$share_other,0)
ProtectedLand$number_2plus <- round(ProtectedLand$census_tract_population * ProtectedLand$share_2plus,0)
ProtectedLand$number_hispanic <- round(ProtectedLand$census_tract_population * ProtectedLand$share_hispanic,0)
# Create new fields calculating the population of the tract id based on education
ProtectedLand$number_lessthanHS <- round(ProtectedLand$census_tract_population * ProtectedLand$lessthanHS,0)
ProtectedLand$number_hsDiploma <- round(ProtectedLand$census_tract_population * ProtectedLand$HSdiploma,0)
ProtectedLand$number_someCollege <- round(ProtectedLand$census_tract_population * ProtectedLand$someCollege,0)
ProtectedLand$number_Associates <- round(ProtectedLand$census_tract_population * ProtectedLand$Associates,0)
ProtectedLand$number_Bachelors <- round(ProtectedLand$census_tract_population * ProtectedLand$Bachelors,0)
ProtectedLand$number_Masters <- round(ProtectedLand$census_tract_population * ProtectedLand$Masters,0)
ProtectedLand$number_Professional <- round(ProtectedLand$census_tract_population * ProtectedLand$Professional,0)
ProtectedLand$number_Doctorate <- round(ProtectedLand$census_tract_population * ProtectedLand$Doctorate,0)
# Create new fields calculating the population of the tract id based on education
ProtectedLand$number_Registered <- round(ProtectedLand$Registered * ProtectedLand$Registered....of.Eligible.,0)
ProtectedLand$number_Democrat <- round(ProtectedLand$Registered * ProtectedLand$Democratic....of.Eligible.,0)
ProtectedLand$number_Republican <- round(ProtectedLand$Registered * ProtectedLand$Republican....of.Eligible.,0)
ProtectedLand$number_Independent <- round(ProtectedLand$Registered * ProtectedLand$American.Independent....of.Eligible.,0)
ProtectedLand$number_Green <- round(ProtectedLand$Registered * ProtectedLand$Green....of.Eligible.,0)
ProtectedLand$number_Libertarian <- round(ProtectedLand$Registered * ProtectedLand$Libertarian....of.Eligible.,0)
ProtectedLand$number_PeaceAndFreedom <- round(ProtectedLand$Registered * ProtectedLand$Peace.and.Freedom....of.Eligible.,0)
ProtectedLand$number_Party_Other <- round(ProtectedLand$Registered * ProtectedLand$Other....of.Eligible.,0)
ProtectedLand$number_Party_Declined <- round(ProtectedLand$Registered * ProtectedLand$Decline.to.State....of.Eligible.,0)
# Create a function that generates a new data frame that houses all descriptive stats
myDescriptiveStats <- data.frame()
getDescriptiveStats <- function(){
for ( iter in 1:length(uniqueCounty)) {
myCounty <- uniqueCounty[iter]
mean_ct_pop <- round(mean(ProtectedLand$census_tract_population[ProtectedLand$county==myCounty]),0)
median_ct_pop <- round(median(ProtectedLand$census_tract_population[ProtectedLand$county==myCounty]),0)
min_ct_pop <- round(min(ProtectedLand$census_tract_population[ProtectedLand$county==myCounty]),0)
max_ct_pop <- round(max(ProtectedLand$census_tract_population[ProtectedLand$county==myCounty]),0)
mean_income <- round(mean(ProtectedLand$average_income[ProtectedLand$county==myCounty]),0)
median_income <- round(median(ProtectedLand$average_income[ProtectedLand$county==myCounty]),0)
min_income <- round(min(ProtectedLand$average_income[ProtectedLand$county==myCounty]),0)
max_income <- round(max(ProtectedLand$average_income[ProtectedLand$county==myCounty]),0)
mean_housing_price <- round(mean(ProtectedLand$median_housing_price[ProtectedLand$county==myCounty]),0)
median_housing_price <- round(median(ProtectedLand$median_housing_price[ProtectedLand$county==myCounty]),0)
min_housing_price <- round(min(ProtectedLand$median_housing_price[ProtectedLand$county==myCounty]),0)
max_housing_price <- round(max(ProtectedLand$median_housing_price[ProtectedLand$county==myCounty]),0)
mean_white_pop <- round(mean(ProtectedLand$number_white[ProtectedLand$county==myCounty]),0)
median_white_pop <- round(median(ProtectedLand$number_white[ProtectedLand$county==myCounty]),0)
min_white_pop <- round(min(ProtectedLand$number_white[ProtectedLand$county==myCounty]),0)
max_white_pop <- round(max(ProtectedLand$number_white[ProtectedLand$county==myCounty]),0)
mean_black_pop <- round(mean(ProtectedLand$number_black[ProtectedLand$county==myCounty]),0)
median_black_pop <- round(median(ProtectedLand$number_black[ProtectedLand$county==myCounty]),0)
min_black_pop <- round(min(ProtectedLand$number_black[ProtectedLand$county==myCounty]),0)
max_black_pop <- round(max(ProtectedLand$number_black[ProtectedLand$county==myCounty]),0)
mean_native_american_pop <- round(mean(ProtectedLand$number_native_american[ProtectedLand$county==myCounty]),0)
median_native_american_pop <- round(median(ProtectedLand$number_native_american[ProtectedLand$county==myCounty]),0)
min_native_american_pop <- round(min(ProtectedLand$number_native_american[ProtectedLand$county==myCounty]),0)
max_native_american_pop <- round(max(ProtectedLand$number_native_american[ProtectedLand$county==myCounty]),0)
mean_asian_pop <- round(mean(ProtectedLand$number_asian[ProtectedLand$county==myCounty]),0)
median_asian_pop <- round(median(ProtectedLand$number_asian[ProtectedLand$county==myCounty]),0)
min_asian_pop <- round(min(ProtectedLand$number_asian[ProtectedLand$county==myCounty]),0)
max_asian_pop <- round(max(ProtectedLand$number_asian[ProtectedLand$county==myCounty]),0)
mean_pacific_islander_pop <- round(mean(ProtectedLand$number_pacific_islander[ProtectedLand$county==myCounty]),0)
median_pacific_islander_pop <- round(median(ProtectedLand$number_pacific_islander[ProtectedLand$county==myCounty]),0)
min_pacific_islander_pop <- round(min(ProtectedLand$number_pacific_islander[ProtectedLand$county==myCounty]),0)
max_pacific_islander_pop <- round(max(ProtectedLand$number_pacific_islander[ProtectedLand$county==myCounty]),0)
mean_other_pop <- round(mean(ProtectedLand$number_other[ProtectedLand$county==myCounty]),0)
median_other_pop <- round(median(ProtectedLand$number_other[ProtectedLand$county==myCounty]),0)
min_other_pop <- round(min(ProtectedLand$number_other[ProtectedLand$county==myCounty]),0)
max_other_pop <- round(max(ProtectedLand$number_other[ProtectedLand$county==myCounty]),0)
mean_2plus_pop <- round(mean(ProtectedLand$number_2plus[ProtectedLand$county==myCounty]),0)
median_2plus_pop <- round(median(ProtectedLand$number_2plus[ProtectedLand$county==myCounty]),0)
min_2plus_pop <- round(min(ProtectedLand$number_2plus[ProtectedLand$county==myCounty]),0)
max_2plus_pop <- round(max(ProtectedLand$number_2plus[ProtectedLand$county==myCounty]),0)
mean_lessthanHS <- round(mean(ProtectedLand$number_lessthanHS[ProtectedLand$county==myCounty]),0)
median_lessthanHS <- round(mean(ProtectedLand$number_lessthanHS[ProtectedLand$county==myCounty]),0)
min_lessthanHS <- round(min(ProtectedLand$number_lessthanHS[ProtectedLand$county==myCounty]),0)
max_lessthanHS <- round(max(ProtectedLand$number_lessthanHS[ProtectedLand$county==myCounty]),0)
mean_hsDiploma <- round(mean(ProtectedLand$number_hsDiploma[ProtectedLand$county==myCounty]),0)
median_hsDiploma <- round(mean(ProtectedLand$number_hsDiploma[ProtectedLand$county==myCounty]),0)
min_hsDiploma <- round(min(ProtectedLand$number_hsDiploma[ProtectedLand$county==myCounty]),0)
max_hsDiploma <- round(max(ProtectedLand$number_hsDiploma[ProtectedLand$county==myCounty]),0)
mean_someCollege <- round(mean(ProtectedLand$number_someCollege[ProtectedLand$county==myCounty]),0)
median_someCollege <- round(mean(ProtectedLand$number_someCollege[ProtectedLand$county==myCounty]),0)
min_someCollege <- round(min(ProtectedLand$number_someCollege[ProtectedLand$county==myCounty]),0)
max_someCollege <- round(max(ProtectedLand$number_someCollege[ProtectedLand$county==myCounty]),0)
mean_Associates <- round(mean(ProtectedLand$number_Associates[ProtectedLand$county==myCounty]),0)
median_Associates <- round(mean(ProtectedLand$number_Associates[ProtectedLand$county==myCounty]),0)
min_Associates <- round(min(ProtectedLand$number_Associates[ProtectedLand$county==myCounty]),0)
max_Associates <- round(max(ProtectedLand$number_Associates[ProtectedLand$county==myCounty]),0)
mean_Bachelors <- round(mean(ProtectedLand$number_Bachelors[ProtectedLand$county==myCounty]),0)
median_Bachelors <- round(mean(ProtectedLand$number_Bachelors[ProtectedLand$county==myCounty]),0)
min_Bachelors <- round(min(ProtectedLand$number_Bachelors[ProtectedLand$county==myCounty]),0)
max_Bachelors <- round(max(ProtectedLand$number_Bachelors[ProtectedLand$county==myCounty]),0)
mean_Masters <- round(mean(ProtectedLand$number_Masters[ProtectedLand$county==myCounty]),0)
median_Masters <- round(mean(ProtectedLand$number_Masters[ProtectedLand$county==myCounty]),0)
min_Masters <- round(min(ProtectedLand$number_Masters[ProtectedLand$county==myCounty]),0)
max_Masters <- round(max(ProtectedLand$number_Masters[ProtectedLand$county==myCounty]),0)
mean_Professional <- round(mean(ProtectedLand$number_Professional[ProtectedLand$county==myCounty]),0)
median_Professional <- round(mean(ProtectedLand$number_Professional[ProtectedLand$county==myCounty]),0)
min_Professional <- round(min(ProtectedLand$number_Professional[ProtectedLand$county==myCounty]),0)
max_Professional <- round(max(ProtectedLand$number_Professional[ProtectedLand$county==myCounty]),0)
mean_Doctorate <- round(mean(ProtectedLand$number_Doctorate[ProtectedLand$county==myCounty]),0)
median_Doctorate <- round(mean(ProtectedLand$number_Doctorate[ProtectedLand$county==myCounty]),0)
min_Doctorate <- round(min(ProtectedLand$number_Doctorate[ProtectedLand$county==myCounty]),0)
max_Doctorate <- round(max(ProtectedLand$number_Doctorate[ProtectedLand$county==myCounty]),0)
mean_Voted <- round(mean(ProtectedLand$Voted[ProtectedLand$county==myCounty]),0)
median_Voted <- round(mean(ProtectedLand$Voted[ProtectedLand$county==myCounty]),0)
min_Voted <- round(min(ProtectedLand$Voted[ProtectedLand$county==myCounty]),0)
max_Voted <- round(max(ProtectedLand$Voted[ProtectedLand$county==myCounty]),0)
mean_Registered <- round(mean(ProtectedLand$Registered[ProtectedLand$county==myCounty]),0)
median_Registered <- round(mean(ProtectedLand$Registered[ProtectedLand$county==myCounty]),0)
min_Registered <- round(min(ProtectedLand$Registered[ProtectedLand$county==myCounty]),0)
max_Registered <- round(max(ProtectedLand$Registered[ProtectedLand$county==myCounty]),0)
mean_voting_age_pop <- round(mean(ProtectedLand$voting_age_pop[ProtectedLand$county==myCounty]),0)
median_voting_age_pop <- round(mean(ProtectedLand$voting_age_pop[ProtectedLand$county==myCounty]),0)
min_voting_age_pop <- round(min(ProtectedLand$voting_age_pop[ProtectedLand$county==myCounty]),0)
max_voting_age_pop <- round(max(ProtectedLand$voting_age_pop[ProtectedLand$county==myCounty]),0)
mean_number_democrat <- round(mean(ProtectedLand$number_Democrat[ProtectedLand$county==myCounty]),0)
median_number_democrat <- round(mean(ProtectedLand$number_Democrat[ProtectedLand$county==myCounty]),0)
min_number_democrat <- round(min(ProtectedLand$number_Democrat[ProtectedLand$county==myCounty]),0)
max_number_democrat <- round(max(ProtectedLand$number_Democrat[ProtectedLand$county==myCounty]),0)
mean_number_republican <- round(mean(ProtectedLand$number_Republican[ProtectedLand$county==myCounty]),0)
median_number_republican <- round(mean(ProtectedLand$number_Republican[ProtectedLand$county==myCounty]),0)
min_number_republican <- round(min(ProtectedLand$number_Republican[ProtectedLand$county==myCounty]),0)
max_number_republican <- round(max(ProtectedLand$number_Republican[ProtectedLand$county==myCounty]),0)
mean_number_independent <- round(mean(ProtectedLand$number_Independent[ProtectedLand$county==myCounty]),0)
median_number_independent <- round(mean(ProtectedLand$number_Independent[ProtectedLand$county==myCounty]),0)
min_number_independent <- round(min(ProtectedLand$number_Independent[ProtectedLand$county==myCounty]),0)
max_number_independent <- round(max(ProtectedLand$number_Independent[ProtectedLand$county==myCounty]),0)
mean_number_green <- round(mean(ProtectedLand$number_Green[ProtectedLand$county==myCounty]),0)
median_number_green <- round(mean(ProtectedLand$number_Green[ProtectedLand$county==myCounty]),0)
min_number_green <- round(min(ProtectedLand$number_Green[ProtectedLand$county==myCounty]),0)
max_number_green <- round(max(ProtectedLand$number_Green[ProtectedLand$county==myCounty]),0)
mean_number_libertarian <- round(mean(ProtectedLand$number_Libertarian[ProtectedLand$county==myCounty]),0)
median_number_libertarian <- round(mean(ProtectedLand$number_Libertarian[ProtectedLand$county==myCounty]),0)
min_number_libertarian <- round(min(ProtectedLand$number_Libertarian[ProtectedLand$county==myCounty]),0)
max_number_libertarian <- round(max(ProtectedLand$number_Libertarian[ProtectedLand$county==myCounty]),0)
mean_number_peaceandfreedom <- round(mean(ProtectedLand$number_PeaceAndFreedom[ProtectedLand$county==myCounty]),0)
median_number_peaceandfreedom <- round(mean(ProtectedLand$number_PeaceAndFreedom[ProtectedLand$county==myCounty]),0)
min_number_peaceandfreedom <- round(min(ProtectedLand$number_PeaceAndFreedom[ProtectedLand$county==myCounty]),0)
max_number_peaceandfreedom <- round(max(ProtectedLand$number_PeaceAndFreedom[ProtectedLand$county==myCounty]),0)
mean_number_party_other <- round(mean(ProtectedLand$number_Party_Other[ProtectedLand$county==myCounty]),0)
median_number_party_other <- round(mean(ProtectedLand$number_Party_Other[ProtectedLand$county==myCounty]),0)
min_number_party_other <- round(min(ProtectedLand$number_Party_Other[ProtectedLand$county==myCounty]),0)
max_number_party_other <- round(max(ProtectedLand$number_Party_Other[ProtectedLand$county==myCounty]),0)
mean_number_party_declined <- round(mean(ProtectedLand$number_Party_Declined[ProtectedLand$county==myCounty]),0)
median_number_party_declined <- round(mean(ProtectedLand$number_Party_Declined[ProtectedLand$county==myCounty]),0)
min_number_party_declined <- round(min(ProtectedLand$number_Party_Declined[ProtectedLand$county==myCounty]),0)
max_number_party_declined <- round(max(ProtectedLand$number_Party_Declined[ProtectedLand$county==myCounty]),0)
newRow <- data.frame(county=myCounty,
mean_ct_pop, median_ct_pop, min_ct_pop, max_ct_pop,
mean_income, median_income, min_income, max_income,
mean_housing_price, median_housing_price, min_housing_price, max_housing_price,
mean_white_pop,median_white_pop,min_white_pop,max_white_pop,
mean_black_pop,median_black_pop,min_black_pop,max_black_pop,
mean_native_american_pop,median_native_american_pop,min_native_american_pop,max_native_american_pop,
mean_asian_pop,median_asian_pop,min_asian_pop,max_asian_pop,
mean_pacific_islander_pop,median_pacific_islander_pop,min_pacific_islander_pop,max_pacific_islander_pop,
mean_other_pop,median_other_pop,min_other_pop,max_other_pop,
mean_2plus_pop,median_2plus_pop,min_2plus_pop,max_2plus_pop,
mean_lessthanHS, median_lessthanHS, min_lessthanHS, max_lessthanHS,
mean_hsDiploma, median_hsDiploma, min_hsDiploma, max_hsDiploma,
mean_someCollege, median_someCollege, min_someCollege, max_someCollege,
mean_Associates, median_Associates, min_Associates, max_Associates,
mean_Bachelors, median_Bachelors, min_Bachelors, max_Bachelors,
mean_Masters, median_Masters, min_Masters, max_Masters,
mean_Professional, median_Professional, min_Professional, max_Professional,
mean_Doctorate, median_Doctorate, min_Doctorate, max_Doctorate,
mean_Voted, median_Voted, min_Voted, max_Voted,
mean_Registered, median_Registered, min_Registered, max_Registered,
mean_voting_age_pop, median_voting_age_pop, min_voting_age_pop, max_voting_age_pop,
mean_number_democrat, median_number_democrat, min_number_democrat, max_number_democrat,
mean_number_republican, median_number_republican, min_number_republican, max_number_republican,
mean_number_independent, median_number_independent, min_number_independent, max_number_independent,
mean_number_green, median_number_green, min_number_green, max_number_green,
mean_number_libertarian, median_number_libertarian, min_number_libertarian, max_number_libertarian,
mean_number_peaceandfreedom, median_number_peaceandfreedom, min_number_peaceandfreedom, max_number_peaceandfreedom,
mean_number_party_other, median_number_party_other, min_number_party_other, max_number_party_other,
mean_number_party_declined, median_number_party_declined, min_number_party_declined, max_number_party_declined
)
myDescriptiveStats <<- rbind(myDescriptiveStats,newRow)
}
}
getDescriptiveStats()
#----------------------------------------Descriptive Charts [i003a]----------------------------------------
#Generate lolipop chart to show population distribution by county
# Create a subset of data and save it to a dataframe
myPopTotalsByCounty <- ProtectedLand[,c("county","county_population")]
# Deduplicate the rows
myPopTotalsByCounty <- myPopTotalsByCounty[!duplicated(myPopTotalsByCounty[, c("county","county_population")]), ]
# Reset the row names
row.names(myPopTotalsByCounty) <- NULL
# Plot the data
theme_set(theme_bw())
ggplot(myPopTotalsByCounty, aes(x=county, y=county_population)) +
geom_point(size=3) +
geom_segment(aes(x=county, xend=county, y=0, yend=county_population)) +
labs(title="Population vs County", caption="LA county accounts for ~27% of Californias population.") +
theme(axis.text.x=element_text(angle=65, hjust=1, vjust=1))
#Generate box charts to visualize ethnic and education dispersion in California
# Create a subset of data and save it to a dataframe
myEthnicData <- ProtectedLand[,c("number_white","number_black",
"number_native_american","number_asian",
"number_pacific_islander","number_other",
"number_2plus","number_hispanic")]
myEducationData <- ProtectedLand[,c("number_lessthanHS","number_hsDiploma",
"number_someCollege","number_Associates",
"number_Bachelors","number_Masters",
"number_Professional","number_Doctorate")]
# Melt the data for easier plotting
myMeltedEthnicData <- melt(data=myEthnicData,measure.vars = c("number_white","number_black",
"number_native_american","number_asian",
"number_pacific_islander","number_other",
"number_2plus","number_hispanic"))
myMeltedEducationData <- melt(data=myEducationData,measure.vars = c("number_lessthanHS","number_hsDiploma",
"number_someCollege","number_Associates",
"number_Bachelors","number_Masters",
"number_Professional","number_Doctorate"))
# Relabel column headers and remove "number_"
names(myMeltedEthnicData)[1] <- "Ethnicity"
names(myMeltedEthnicData)[2] <- "Population"
myMeltedEthnicData$Ethnicity <- gsub("number_", "", myMeltedEthnicData$Ethnicity)
names(myMeltedEducationData)[1] <- "Education"
names(myMeltedEducationData)[2] <- "Population"
myMeltedEducationData$Education <- gsub("number_", "", myMeltedEducationData$Education)
# Make additional column so plot order mimics dataframe column order
myMeltedEthnicData$Ethnicity2 <- factor(myMeltedEthnicData$Ethnicity, c("white","black",
"native_american","asian",
"pacific_islander","other",
"2plus","hispanic"))
myMeltedEducationData$Education2 <- factor(myMeltedEducationData$Education, c("lessthanHS","hsDiploma",
"someCollege","Associates",
"Bachelors","Masters",
"Professional","Doctorate"))
# Box-plot ethnicity, education and income in california
ethnicBoxData <- ggplot(data=myMeltedEthnicData, aes(x=Ethnicity2,y=Population,color=Ethnicity))
ethnicBoxData + geom_boxplot(size=1) + theme(legend.position = "none", plot.title=element_text(hjust=0.5)) +
labs(x="race",y="population") + ggtitle("population vs race")
print("White and hispanic population distributions are very similar with white groups having a slightly
higher median with one notable outlier enclave (Los Angeles).")
educationBoxData <- ggplot(data=myMeltedEducationData, aes(x=Education2,y=Population,color=Education))
educationBoxData + geom_boxplot(size=1) + theme(legend.position = "none", plot.title=element_text(hjust=0.5)) +
labs(x="education",y="population") + ggtitle("population vs education level")
print("Educational dispersion is very similar between high school diploma and some college, with Bachelors
and less than high school showing greater dispersion and less consistancy around the median.")
meanAverageIncome <- data.frame(round(mean(ProtectedLand$average_income, na.rm = T),0))
names(meanAverageIncome)[1] <- "average_income"
incomeBoxData <- ggplot(data=ProtectedLand, aes(x="",y=average_income))
incomeBoxData + geom_boxplot(size=1) +
stat_summary(fun.y = mean, geom = "point", shape=23, size=4) +
geom_text(data = meanAverageIncome, aes(label = average_income), nudge_x = .03, vjust=-0.5) +
theme(legend.position = "none", plot.title=element_text(hjust=0.5)) +
labs(x="",y="average income") + ggtitle("average income dispersion in california")
print("Most people in California make between $20,000 and $40,000 on average. There is a considerable spread of average salaries.")
#----------------------------------------Descriptive Maps [i003b]----------------------------------------
mappingData<-data.frame(mappingData)
###Registered to eligible voters [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$registered_to_eligible)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$registered_to_eligible))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Registered to Eligible Voters (Dist2Tract)",fill="% Registered to Eligible Voters")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Registered to eligible voters [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$registered_to_eligible)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$registered_to_eligible))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+labs(title = "Registered to Eligible Voters (ldist)", fill="% Registered to Eligible Voters")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Democratic to registered voters [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$democratic_to_registered)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$democratic_to_registered))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Democratic to Registered Voters (Dist2Tract)",fill="% Democratic to Registered Voters")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Democratic to registered voters [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$democratic_to_registered)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$democratic_to_registered))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+labs(title = "Democratic to Registered Voters (ldist)", fill="% Democratic to Registered Voters")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Republican to registered voters [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$republican_to_registered)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$republican_to_registered))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Republican to Registered Voters (Dist2Tract)",fill="% Republican to Registered Voters")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Republican to registered voters [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$republican_to_registered)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$republican_to_registered))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Republican to Registered Voters (ldist)", fill="% Republican to Registered Voters")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###No Party to registered voters [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$noparty_to_registered)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$noparty_to_registered))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "No Party to Registered Voters (Dist2Tract)",fill="% No Party to Registered Voters")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###No Party to registered voters [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$noparty_to_registered)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$noparty_to_registered))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "No Party to Registered Voters (ldist)", fill="% No Party to Registered Voters")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Average Income [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$avgincome)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$avgincome))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Average Income (Dist2Tract)",fill="Average Income")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Average Income [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$avgincome)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$avgincome))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Average Income (ldist)", fill="Average Income")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Median Housing Price [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$med_housing)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$med_housing))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Median Housing Price (Dist2Tract)",fill="Median Housing Price")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Median Housing Price[county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$med_housing)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$med_housing))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Median Housing Price (ldist)", fill="Median Housing Price")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###County Population [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$Cpop)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$Cpop))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "County Population (Dist2Tract)",fill="Median Housing Price")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###County Population [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$Cpop)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$Cpop))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "County Population (ldist)", fill="County Population")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Population Density [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$popdens)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$popdens))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Population Density (Dist2Tract)",fill="Population Density")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Population Density [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$popdens)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$popdens))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Population Density (ldist)", fill="Population Density")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Share White [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$share_white)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$share_white))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Share White (Dist2Tract)",fill="Share White")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Share White [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$share_white)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$share_white))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Share White (ldist)", fill="Share White")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Share Black [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$share_black)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$share_black))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Share Black (Dist2Tract)",fill="Share Black")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Share Black [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$share_black)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$share_black))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Share Black (ldist)", fill="Share Black")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Share Hispanic [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$share_hispanic)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$share_hispanic))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Share Hispanic (Dist2Tract)",fill="Share Hispanic")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Share Hispanic [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$share_hispanic)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$share_hispanic))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Share Hispanic (ldist)", fill="Share Hispanic")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Share Asian [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$share_asian)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$share_asian))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Share Asian (Dist2Tract)",fill="Share Asian")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
#Share Asian[county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$share_asian)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$share_asian))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Share Asian (ldist)", fill="Share Asian")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Less than HS Education [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$lessthanHS)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$lessthanHS))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Less than HS Education (Dist2Tract)",fill="Less than HS Education")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
#Less than HS Education [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$lessthanHS)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$lessthanHS))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Less than HS Education (ldist)", fill="Less than HS Education")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Professional Degrees [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$Professional)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$Professional))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Professional Degrees (Dist2Tract)",fill="Professional Degrees")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
#Professional Degrees [county_ldist]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$Professional)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$Professional))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Professional Degrees (ldist)", fill="Professional Degrees")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Doctorate [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$Doctorate)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$Doctorate))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_dist2tract, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_dist2tract", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Doctorate (Dist2Tract)",fill="Doctorate")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
###Doctorate [county_dist2tract]
ww <- ggplot(mappingData, aes(x=long, y=lat, group=group, fill = mappingData$Doctorate)) + geom_polygon(colour="black")+ coord_map('polyconic')
xx <- ww+scale_fill_gradient2(low="#559999", mid="grey90", high="#BB650B", midpoint=median(mappingData$Doctorate))
yy <- xx +geom_point( data=mappingData, aes(x=long, y=lat, size = mappingData$county_ldist, color="hotpink2", alpha = 0.1)) + scale_size_continuous(name="mappingData$county_ldist", range = c(1,10)) + guides(colour=FALSE, alpha=FALSE) #dots
zz <- yy+scale_fill_viridis_c()+labs(title = "Doctorate (ldist)",fill="Doctorate")
zz + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),rect = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), plot.title=element_text(hjust=0.5))
#--------------------------------------Advanced Analysis [i004]--------------------------------------------------------------
hist(ProtectedLand$distance_to_tract)
hist(ProtectedLand$ldist)
print("Using the log of distance instead of the regular distance variable normalizes the data, allowing for more accurate linear models.")
# 1. Can we show inequality in access to protected land areas?
# 1a. Is there a difference in access for people in rural versus suburban versus urban counties?
model1a <- lm(ldist ~ urban + suburb, ProtectedLand)
summary(model1a)
print("1a. Urban and suburban counties have increased access to protected land areas compared to rural areas. The model has a near-0 p-value and an adjusted R-squared of 11.21%. Suburban county census tracts see a exp(-1.13181)-1 = 67.75% increase in access and urban county census tracts see a 78.48% increase in access.")
model1a_urban <- ggplot(model1a$model, aes_string(x = names(model1a$model)[2], y = names(model1a$model)[1])) + geom_point(colour="lightblue", alpha = 0.01) + geom_abline(intercept = coef(model1a)[1], slope = coef(model1a)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1a_suburb <- ggplot(model1a$model, aes_string(x = names(model1a$model)[3], y = names(model1a$model)[1])) + geom_point(colour="springgreen4", alpha = 0.01) + geom_abline(intercept = coef(model1a)[1], slope = coef(model1a)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1a_urban, model1a_suburb, nrow=2, top="Increased access for urban and suburban areas compared to rural areas")
# 1ai. Is there a relationship between rural, suburban, and urban incomes?
model1ai <- lm(average_income ~ urban + suburb, ProtectedLand)
summary(model1ai)
print("1ai. The model is significant and has an adjusted R-squared value of 2.784%. Both coefficients are significant, showing an increase of approximately $10,000 for urban and $4,500 for suburban in average income over rural incomes.")
model1ai_urban <- ggplot(model1ai$model, aes_string(x = names(model1ai$model)[2], y = names(model1ai$model)[1])) + geom_point(colour="lightblue", alpha = 0.01) + geom_abline(intercept = coef(model1ai)[1], slope = coef(model1ai)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1ai_suburb <- ggplot(model1ai$model, aes_string(x = names(model1ai$model)[3], y = names(model1ai$model)[1])) + geom_point(colour="springgreen4", alpha = 0.01) + geom_abline(intercept = coef(model1ai)[1], slope = coef(model1ai)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1ai_urban, model1ai_suburb, nrow=2, top="Increased income for urban and suburban areas compared to rural areas")
# 1aia. Does that factor into median housing price?
model1aia <- lm(median_housing_price ~ average_income + urban + suburb, ProtectedLand)
summary(model1aia)
print("1aia. The model is significant and has an adjusted R-squared of 66.23%. Average income and urban locations seem to be the primary drivers of housing prices in California, although suburban housing prices are also much higher.")
model1aia_avgInc <- ggplot(model1aia$model, aes_string(x = names(model1aia$model)[2], y = names(model1aia$model)[1])) + geom_point(colour="lightblue", alpha = 0.1) + geom_abline(intercept = coef(model1aia)[1], slope = coef(model1aia)[2], colour="black", size=1)
model1aia_urban <- ggplot(model1aia$model, aes_string(x = names(model1aia$model)[3], y = names(model1aia$model)[1])) + geom_point(colour="springgreen4", alpha = 0.01) + geom_abline(intercept = coef(model1aia)[1], slope = coef(model1aia)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1aia_suburb <- ggplot(model1aia$model, aes_string(x = names(model1aia$model)[4], y = names(model1aia$model)[1])) + geom_point(colour="firebrick", alpha = 0.01) + geom_abline(intercept = coef(model1aia)[1], slope = coef(model1aia)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1aia_avgInc, model1aia_urban, model1aia_suburb, nrow=3, top="Increased median housing price for urban and suburban areas compared to rural areas")
# 1b. Is there a relationship between race and access?
model1b <- lm(ldist ~ share_black + share_hispanic + share_asian + share_native_american + share_pacific_islander + share_2plus + share_other, ProtectedLand)
summary(model1b)
print("1b. The model is significant and has an adjusted R-squared of 9.437%. Most race/ethnicity coefficients are statistically significant and show slightly increased access compared to white populations. Of notable exception is that Native American populations see highly decreased access (increased distance), which is expected since Native land is not included in the group of designated protected lands.")
model1b_black <- ggplot(model1b$model, aes_string(x = names(model1b$model)[2], y = names(model1b$model)[1])) + geom_point(colour="pink", alpha = 0.1) + geom_abline(intercept = coef(model1b)[1], slope = coef(model1b)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1b_hispanic <- ggplot(model1b$model, aes_string(x = names(model1b$model)[3], y = names(model1b$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1b)[1], slope = coef(model1b)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1b_asian <- ggplot(model1b$model, aes_string(x = names(model1b$model)[4], y = names(model1b$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model1b)[1], slope = coef(model1b)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1b_na <- ggplot(model1b$model, aes_string(x = names(model1b$model)[5], y = names(model1b$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1b)[1], slope = coef(model1b)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1b_pi <- ggplot(model1b$model, aes_string(x = names(model1b$model)[6], y = names(model1b$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1b)[1], slope = coef(model1b)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1b_2plus <- ggplot(model1b$model, aes_string(x = names(model1b$model)[7], y = names(model1b$model)[1])) + geom_point(colour="lightblue", alpha = 0.1) + geom_abline(intercept = coef(model1b)[1], slope = coef(model1b)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1b_other <- ggplot(model1b$model, aes_string(x = names(model1b$model)[8], y = names(model1b$model)[1])) + geom_point(colour="springgreen4", alpha = 0.1) + geom_abline(intercept = coef(model1b)[1], slope = coef(model1b)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1b_black, model1b_hispanic, model1b_asian, model1b_na, model1b_pi, model1b_2plus, model1b_other, nrow=4, top="Most racial groups show slightly increased access to protected lands compared to white people")
# 1bi. Is there a relationship between race and income?
model1bi <- lm(average_income ~ share_black + share_hispanic + share_asian + share_native_american + share_pacific_islander + share_2plus + share_other, ProtectedLand)
summary(model1bi)
print("1bi. The model is significant and has an adjusted R-squared of 54.05%. All minority racial/ethnic populations have lower average incomes compared to white populations except those that identify as other. The coefficients can be interpreted as a 1 percentage point (0.01) increase in the population share of a racial/ethnic minority in a census tract will show a $[coefficient value] change in census tract average income.")
model1bi_black <- ggplot(model1bi$model, aes_string(x = names(model1bi$model)[2], y = names(model1bi$model)[1])) + geom_point(colour="pink", alpha = 0.1) + geom_abline(intercept = coef(model1bi)[1], slope = coef(model1bi)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1bi_hispanic <- ggplot(model1bi$model, aes_string(x = names(model1bi$model)[3], y = names(model1bi$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1bi)[1], slope = coef(model1bi)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1bi_asian <- ggplot(model1bi$model, aes_string(x = names(model1bi$model)[4], y = names(model1bi$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model1bi)[1], slope = coef(model1bi)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1bi_na <- ggplot(model1bi$model, aes_string(x = names(model1bi$model)[5], y = names(model1bi$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1bi)[1], slope = coef(model1bi)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1bi_pi <- ggplot(model1bi$model, aes_string(x = names(model1bi$model)[6], y = names(model1bi$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1bi)[1], slope = coef(model1bi)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1bi_2plus <- ggplot(model1bi$model, aes_string(x = names(model1bi$model)[7], y = names(model1bi$model)[1])) + geom_point(colour="lightblue", alpha = 0.1) + geom_abline(intercept = coef(model1bi)[1], slope = coef(model1bi)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1bi_other <- ggplot(model1bi$model, aes_string(x = names(model1bi$model)[8], y = names(model1bi$model)[1])) + geom_point(colour="springgreen4", alpha = 0.1) + geom_abline(intercept = coef(model1bi)[1], slope = coef(model1bi)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
grid.arrange(model1bi_black,model1bi_hispanic,model1bi_asian,model1bi_na,model1bi_pi,model1bi_2plus,model1bi_other, nrow=4, top="All minority groups have lower average incomes compared to their white counterparts")
# 1bii. Is there a relationship between race and housing price?
model1bii <- lm(median_housing_price ~ share_black + share_hispanic + share_asian + share_native_american + share_pacific_islander + share_2plus + share_other, ProtectedLand)
summary(model1bii)
print("1bii. The model is significant and has an adjusted R-squared of 39.59%. All minority racial/ethnic populations have lower median housing prices compared to white populations except those that identify as Asian or other. The coefficients can be interpreted as a 1 percentage point (0.01) increase in the population share of a racial/ethnic minority in a census tract will show a $[coefficient value] change in census tract median housing price.")
model1bii_black <- ggplot(model1bii$model, aes_string(x = names(model1bii$model)[2], y = names(model1bii$model)[1])) + geom_point(colour="pink", alpha = 0.1) + geom_abline(intercept = coef(model1bii)[1], slope = coef(model1bii)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1bii_hispanic <- ggplot(model1bii$model, aes_string(x = names(model1bii$model)[3], y = names(model1bii$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1bii)[1], slope = coef(model1bii)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1bii_asian <- ggplot(model1bii$model, aes_string(x = names(model1bii$model)[4], y = names(model1bii$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model1bii)[1], slope = coef(model1bii)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1bii_na <- ggplot(model1bii$model, aes_string(x = names(model1bii$model)[5], y = names(model1bii$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1bii)[1], slope = coef(model1bii)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1bii_pi <- ggplot(model1bii$model, aes_string(x = names(model1bii$model)[6], y = names(model1bii$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1bii)[1], slope = coef(model1bii)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1bii_2plus <- ggplot(model1bii$model, aes_string(x = names(model1bii$model)[7], y = names(model1bii$model)[1])) + geom_point(colour="lightblue", alpha = 0.1) + geom_abline(intercept = coef(model1bii)[1], slope = coef(model1bii)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1bii_other <- ggplot(model1bii$model, aes_string(x = names(model1bii$model)[8], y = names(model1bii$model)[1])) + geom_point(colour="springgreen4", alpha = 0.1) + geom_abline(intercept = coef(model1bii)[1], slope = coef(model1bii)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
grid.arrange(model1bii_black,model1bii_hispanic,model1bii_asian,model1bii_na,model1bii_pi,model1bii_2plus,model1bii_other, nrow=4, top="Most minority groups have lower median housing prices compared to white populations")
# 1c. Is there a relationship between education and access?
model1c <- lm(ldist ~ HSdiploma + someCollege + Associates + Bachelors + Masters + Professional + Doctorate, ProtectedLand)
summary(model1c)
print("1c. The model is significant and has an adjusted R-squared of 4.446%. All of the coefficients are positive (decreased access compared to less than High School) except Bachelors and Doctorate, and most are significant except Masters and Doctorate. Notably, professional degree holders have significantly decreased access compared to other education groups.")
model1c_HSdiploma <- ggplot(model1c$model, aes_string(x = names(model1c$model)[2], y = names(model1c$model)[1])) + geom_point(colour="pink", alpha = 0.1) + geom_abline(intercept = coef(model1c)[1], slope = coef(model1c)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1c_someCollege <- ggplot(model1c$model, aes_string(x = names(model1c$model)[3], y = names(model1c$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1c)[1], slope = coef(model1c)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1c_Associates <- ggplot(model1c$model, aes_string(x = names(model1c$model)[4], y = names(model1c$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model1c)[1], slope = coef(model1c)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1c_Bachelors <- ggplot(model1c$model, aes_string(x = names(model1c$model)[5], y = names(model1c$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1c)[1], slope = coef(model1c)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1c_Masters <- ggplot(model1c$model, aes_string(x = names(model1c$model)[6], y = names(model1c$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1c)[1], slope = coef(model1c)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1c_Professional <- ggplot(model1c$model, aes_string(x = names(model1c$model)[7], y = names(model1c$model)[1])) + geom_point(colour="lightblue", alpha = 0.1) + geom_abline(intercept = coef(model1c)[1], slope = coef(model1c)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1c_Doctorate <- ggplot(model1c$model, aes_string(x = names(model1c$model)[8], y = names(model1c$model)[1])) + geom_point(colour="springgreen4", alpha = 0.1) + geom_abline(intercept = coef(model1c)[1], slope = coef(model1c)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1c_HSdiploma,model1c_someCollege,model1c_Associates,model1c_Bachelors,model1c_Masters,model1c_Professional,model1c_Doctorate, nrow=4, top="Most education levels have decreased access to protected land")
# 1ci. Is there a relationship between education and income?
model1ci <- lm(average_income ~ HSdiploma + someCollege + Associates + Bachelors + Masters + Professional + Doctorate, ProtectedLand)
summary(model1ci)
print("1c. The model is significant and has an adjusted R-squared of 78.06%. Most of the coefficients are significant except Associates, with all showing an increase in income (compared to less than High School) except Doctorate.")
model1ci_HSdiploma <- ggplot(model1ci$model, aes_string(x = names(model1ci$model)[2], y = names(model1ci$model)[1])) + geom_point(colour="pink", alpha = 0.1) + geom_abline(intercept = coef(model1ci)[1], slope = coef(model1ci)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1ci_someCollege <- ggplot(model1ci$model, aes_string(x = names(model1ci$model)[3], y = names(model1ci$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1ci)[1], slope = coef(model1ci)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1ci_Associates <- ggplot(model1ci$model, aes_string(x = names(model1ci$model)[4], y = names(model1ci$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model1ci)[1], slope = coef(model1ci)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1ci_Bachelors <- ggplot(model1ci$model, aes_string(x = names(model1ci$model)[5], y = names(model1ci$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1ci)[1], slope = coef(model1ci)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1ci_Masters <- ggplot(model1ci$model, aes_string(x = names(model1ci$model)[6], y = names(model1ci$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1ci)[1], slope = coef(model1ci)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1ci_Professional <- ggplot(model1ci$model, aes_string(x = names(model1ci$model)[7], y = names(model1ci$model)[1])) + geom_point(colour="lightblue", alpha = 0.1) + geom_abline(intercept = coef(model1ci)[1], slope = coef(model1ci)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
model1ci_Doctorate <- ggplot(model1ci$model, aes_string(x = names(model1ci$model)[8], y = names(model1ci$model)[1])) + geom_point(colour="springgreen4", alpha = 0.1) + geom_abline(intercept = coef(model1ci)[1], slope = coef(model1ci)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("avg_income")
grid.arrange(model1ci_HSdiploma,model1ci_someCollege,model1ci_Associates,model1ci_Bachelors,model1ci_Masters,model1ci_Professional,model1ci_Doctorate, nrow=4, top="Most education levels show increased average income compared to less than HS education")
# 1cii. Is there a relationship between education and housing price?
model1cii <- lm(median_housing_price ~ HSdiploma + someCollege + Associates + Bachelors + Masters + Professional + Doctorate, ProtectedLand)
summary(model1cii)
print("1c. The model is significant and has an adjusted R-squared of 65.71%. All coefficients are significant except Doctorate, which has a p-value of 0.2902. Compared to less the High School, Bachelors, Masters and Professional dregrees see increases in median housing price, while high school diploma, some college, Associates, and Doctorate show decreases in median housing price.")
model1cii_HSdiploma <- ggplot(model1cii$model, aes_string(x = names(model1cii$model)[2], y = names(model1cii$model)[1])) + geom_point(colour="pink", alpha = 0.1) + geom_abline(intercept = coef(model1cii)[1], slope = coef(model1cii)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1cii_someCollege <- ggplot(model1cii$model, aes_string(x = names(model1cii$model)[3], y = names(model1cii$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1cii)[1], slope = coef(model1cii)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1cii_Associates <- ggplot(model1cii$model, aes_string(x = names(model1cii$model)[4], y = names(model1cii$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model1cii)[1], slope = coef(model1cii)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1cii_Bachelors <- ggplot(model1cii$model, aes_string(x = names(model1cii$model)[5], y = names(model1cii$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1cii)[1], slope = coef(model1cii)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1cii_Masters <- ggplot(model1cii$model, aes_string(x = names(model1cii$model)[6], y = names(model1cii$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1cii)[1], slope = coef(model1cii)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1cii_Professional <- ggplot(model1cii$model, aes_string(x = names(model1cii$model)[7], y = names(model1cii$model)[1])) + geom_point(colour="lightblue", alpha = 0.1) + geom_abline(intercept = coef(model1cii)[1], slope = coef(model1cii)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
model1cii_Doctorate <- ggplot(model1cii$model, aes_string(x = names(model1cii$model)[8], y = names(model1cii$model)[1])) + geom_point(colour="springgreen4", alpha = 0.1) + geom_abline(intercept = coef(model1cii)[1], slope = coef(model1cii)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1)) + ylab("med_hse_pr")
grid.arrange(model1cii_HSdiploma,model1cii_someCollege,model1cii_Associates,model1cii_Bachelors,model1cii_Masters,model1cii_Professional,model1cii_Doctorate, nrow=4, top="Bachelors, Masters and Professional levels of education show increased median housing prices")
# 1d. What are primary indicators of access, all else constant?
model1d <- lm(ldist ~ average_income + median_housing_price + urban + suburb + share_black + share_hispanic + share_asian + share_native_american + share_pacific_islander + share_2plus + share_other + HSdiploma + someCollege + Associates + Bachelors + Masters + Professional + Doctorate, ProtectedLand)
summary(model1d)
print("1d. The model is significant and has an adjusted R-squared of 15.88%. The significant variables are average income, median housing price, urban, suburban, all race/ethnicity variables except other, high school diploma, Bachelors, and Doctorate degrees.")
model1d_average_income <- ggplot(model1d$model, aes_string(x = names(model1d$model)[2], y = names(model1d$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[2], colour="black", size=1)
model1d_median_housing_price <- ggplot(model1d$model, aes_string(x = names(model1d$model)[3], y = names(model1d$model)[1])) + geom_point(colour="coral", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[3], colour="black", size=1)
model1d_urban <- ggplot(model1d$model, aes_string(x = names(model1d$model)[4], y = names(model1d$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_suburb <- ggplot(model1d$model, aes_string(x = names(model1d$model)[5], y = names(model1d$model)[1])) + geom_point(colour="chartreuse4", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_black <- ggplot(model1d$model, aes_string(x = names(model1d$model)[6], y = names(model1d$model)[1])) + geom_point(colour="cadetblue", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_hispanic <- ggplot(model1d$model, aes_string(x = names(model1d$model)[7], y = names(model1d$model)[1])) + geom_point(colour="burlywood", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_asian <- ggplot(model1d$model, aes_string(x = names(model1d$model)[8], y = names(model1d$model)[1])) + geom_point(colour="brown2", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_na <- ggplot(model1d$model, aes_string(x = names(model1d$model)[9], y = names(model1d$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[9], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_pi <- ggplot(model1d$model, aes_string(x = names(model1d$model)[10], y = names(model1d$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[10], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_2plus <- ggplot(model1d$model, aes_string(x = names(model1d$model)[11], y = names(model1d$model)[1])) + geom_point(colour="bisque3", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[11], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_other <- ggplot(model1d$model, aes_string(x = names(model1d$model)[12], y = names(model1d$model)[1])) + geom_point(colour="aquamarine3", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[12], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_HSdiploma <- ggplot(model1d$model, aes_string(x = names(model1d$model)[13], y = names(model1d$model)[1])) + geom_point(colour="dodgerblue", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[13], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_someCollege <- ggplot(model1d$model, aes_string(x = names(model1d$model)[14], y = names(model1d$model)[1])) + geom_point(colour="goldenrod1", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[14], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_Associates <- ggplot(model1d$model, aes_string(x = names(model1d$model)[15], y = names(model1d$model)[1])) + geom_point(colour="forestgreen", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[15], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_Bachelors <- ggplot(model1d$model, aes_string(x = names(model1d$model)[16], y = names(model1d$model)[1])) + geom_point(colour="indianred1", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[16], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_Masters <- ggplot(model1d$model, aes_string(x = names(model1d$model)[17], y = names(model1d$model)[1])) + geom_point(colour="khaki", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[17], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_Professional <- ggplot(model1d$model, aes_string(x = names(model1d$model)[18], y = names(model1d$model)[1])) + geom_point(colour="tomato", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[18], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1d_Doctorate <- ggplot(model1d$model, aes_string(x = names(model1d$model)[19], y = names(model1d$model)[1])) + geom_point(colour="thistle", alpha = 0.1) + geom_abline(intercept = coef(model1d)[1], slope = coef(model1d)[19], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1d_average_income, model1d_median_housing_price, model1d_urban, model1d_suburb, model1d_black, model1d_hispanic, model1d_asian, model1d_na, model1d_pi, model1d_2plus, model1d_other, model1d_HSdiploma, model1d_someCollege, model1d_Associates, model1d_Bachelors, model1d_Masters, model1d_Professional, model1d_Doctorate, nrow=4, top="Access to protected land with all variables accounted for")
model1dRace <- lm(ldist ~ average_income + median_housing_price + urban + suburb + share_black + share_hispanic + share_asian + share_native_american + share_pacific_islander + share_2plus + share_other, ProtectedLand)
summary(model1dRace)
model1dRace_average_income <- ggplot(model1dRace$model, aes_string(x = names(model1dRace$model)[2], y = names(model1dRace$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1dRace)[1], slope = coef(model1dRace)[2], colour="black", size=1)
model1dRace_median_housing_price <- ggplot(model1dRace$model, aes_string(x = names(model1dRace$model)[3], y = names(model1dRace$model)[1])) + geom_point(colour="coral", alpha = 0.1) + geom_abline(intercept = coef(model1dRace)[1], slope = coef(model1dRace)[3], colour="black", size=1)
model1dRace_urban <- ggplot(model1dRace$model, aes_string(x = names(model1dRace$model)[4], y = names(model1dRace$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model1dRace)[1], slope = coef(model1dRace)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRace_suburb <- ggplot(model1dRace$model, aes_string(x = names(model1dRace$model)[5], y = names(model1dRace$model)[1])) + geom_point(colour="chartreuse4", alpha = 0.1) + geom_abline(intercept = coef(model1dRace)[1], slope = coef(model1dRace)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRace_black <- ggplot(model1dRace$model, aes_string(x = names(model1dRace$model)[6], y = names(model1dRace$model)[1])) + geom_point(colour="cadetblue", alpha = 0.1) + geom_abline(intercept = coef(model1dRace)[1], slope = coef(model1dRace)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRace_hispanic <- ggplot(model1dRace$model, aes_string(x = names(model1dRace$model)[7], y = names(model1dRace$model)[1])) + geom_point(colour="burlywood", alpha = 0.1) + geom_abline(intercept = coef(model1dRace)[1], slope = coef(model1dRace)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRace_asian <- ggplot(model1dRace$model, aes_string(x = names(model1dRace$model)[8], y = names(model1dRace$model)[1])) + geom_point(colour="brown2", alpha = 0.1) + geom_abline(intercept = coef(model1dRace)[1], slope = coef(model1dRace)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRace_na <- ggplot(model1dRace$model, aes_string(x = names(model1dRace$model)[9], y = names(model1dRace$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1dRace)[1], slope = coef(model1dRace)[9], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRace_pi <- ggplot(model1dRace$model, aes_string(x = names(model1dRace$model)[10], y = names(model1dRace$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1dRace)[1], slope = coef(model1dRace)[10], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRace_2plus <- ggplot(model1dRace$model, aes_string(x = names(model1dRace$model)[11], y = names(model1dRace$model)[1])) + geom_point(colour="bisque3", alpha = 0.1) + geom_abline(intercept = coef(model1dRace)[1], slope = coef(model1dRace)[11], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRace_other <- ggplot(model1dRace$model, aes_string(x = names(model1dRace$model)[12], y = names(model1dRace$model)[1])) + geom_point(colour="aquamarine3", alpha = 0.1) + geom_abline(intercept = coef(model1dRace)[1], slope = coef(model1dRace)[12], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1dRace_average_income, model1dRace_median_housing_price, model1dRace_urban, model1dRace_suburb, model1dRace_black, model1dRace_hispanic, model1dRace_asian, model1dRace_na, model1dRace_pi, model1dRace_2plus, model1dRace_other, nrow=4, top="Access to protected land with all variables accounted for except education level")
model1dEdu <- lm(ldist ~ average_income + median_housing_price + urban + suburb + HSdiploma + someCollege + Associates + Bachelors + Masters + Professional + Doctorate, ProtectedLand)
summary(model1dEdu)
model1dEdu_average_income <- ggplot(model1dEdu$model, aes_string(x = names(model1dEdu$model)[2], y = names(model1dEdu$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1dEdu)[1], slope = coef(model1dEdu)[2], colour="black", size=1)
model1dEdu_median_housing_price <- ggplot(model1dEdu$model, aes_string(x = names(model1dEdu$model)[3], y = names(model1dEdu$model)[1])) + geom_point(colour="coral", alpha = 0.1) + geom_abline(intercept = coef(model1dEdu)[1], slope = coef(model1dEdu)[3], colour="black", size=1)
model1dEdu_urban <- ggplot(model1dEdu$model, aes_string(x = names(model1dEdu$model)[4], y = names(model1dEdu$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model1dEdu)[1], slope = coef(model1dEdu)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dEdu_suburb <- ggplot(model1dEdu$model, aes_string(x = names(model1dEdu$model)[5], y = names(model1dEdu$model)[1])) + geom_point(colour="chartreuse4", alpha = 0.1) + geom_abline(intercept = coef(model1dEdu)[1], slope = coef(model1dEdu)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dEdu_HSdiploma <- ggplot(model1dEdu$model, aes_string(x = names(model1dEdu$model)[6], y = names(model1dEdu$model)[1])) + geom_point(colour="dodgerblue", alpha = 0.1) + geom_abline(intercept = coef(model1dEdu)[1], slope = coef(model1dEdu)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dEdu_someCollege <- ggplot(model1dEdu$model, aes_string(x = names(model1dEdu$model)[7], y = names(model1dEdu$model)[1])) + geom_point(colour="goldenrod1", alpha = 0.1) + geom_abline(intercept = coef(model1dEdu)[1], slope = coef(model1dEdu)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dEdu_Associates <- ggplot(model1dEdu$model, aes_string(x = names(model1dEdu$model)[8], y = names(model1dEdu$model)[1])) + geom_point(colour="forestgreen", alpha = 0.1) + geom_abline(intercept = coef(model1dEdu)[1], slope = coef(model1dEdu)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dEdu_Bachelors <- ggplot(model1dEdu$model, aes_string(x = names(model1dEdu$model)[9], y = names(model1dEdu$model)[1])) + geom_point(colour="indianred1", alpha = 0.1) + geom_abline(intercept = coef(model1dEdu)[1], slope = coef(model1dEdu)[9], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dEdu_Masters <- ggplot(model1dEdu$model, aes_string(x = names(model1dEdu$model)[10], y = names(model1dEdu$model)[1])) + geom_point(colour="khaki", alpha = 0.1) + geom_abline(intercept = coef(model1dEdu)[1], slope = coef(model1dEdu)[10], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dEdu_Professional <- ggplot(model1dEdu$model, aes_string(x = names(model1dEdu$model)[11], y = names(model1dEdu$model)[1])) + geom_point(colour="tomato", alpha = 0.1) + geom_abline(intercept = coef(model1dEdu)[1], slope = coef(model1dEdu)[11], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dEdu_Doctorate <- ggplot(model1dEdu$model, aes_string(x = names(model1dEdu$model)[12], y = names(model1dEdu$model)[1])) + geom_point(colour="thistle", alpha = 0.1) + geom_abline(intercept = coef(model1dEdu)[1], slope = coef(model1dEdu)[12], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1dEdu_average_income, model1dEdu_median_housing_price, model1dEdu_urban, model1dEdu_suburb, model1dEdu_HSdiploma, model1dEdu_someCollege, model1dEdu_Associates, model1dEdu_Bachelors, model1dEdu_Masters, model1dEdu_Professional, model1dEdu_Doctorate, nrow=4, top="Access to protected land with all variables accounted for except race")
print("What if we only look at urban/suburban areas, where unused green land areas--whether protected or not--are more scarce?")
ProtectedLandNonRural <- ProtectedLand[ProtectedLand$rural != 1,]
ProtectedLandUrban <- ProtectedLand[ProtectedLand$urban == 1,]
ProtectedLandSuburban <- ProtectedLand[ProtectedLand$suburb == 1,]
ProtectedLandRural <- ProtectedLand[ProtectedLand$rural == 1,]
model1dNonRural <- lm(ldist ~ average_income + median_housing_price + urban + share_black + share_hispanic + share_asian + share_native_american + share_pacific_islander + share_2plus + share_other + HSdiploma + someCollege + Associates + Bachelors + Masters + Professional + Doctorate, ProtectedLandNonRural)
summary(model1dNonRural)
model1dNonRural_average_income <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[2], y = names(model1dNonRural$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[2], colour="black", size=1)
model1dNonRural_median_housing_price <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[3], y = names(model1dNonRural$model)[1])) + geom_point(colour="coral", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[3], colour="black", size=1)
model1dNonRural_urban <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[4], y = names(model1dNonRural$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_black <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[5], y = names(model1dNonRural$model)[1])) + geom_point(colour="cadetblue", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_hispanic <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[6], y = names(model1dNonRural$model)[1])) + geom_point(colour="burlywood", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_asian <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[7], y = names(model1dNonRural$model)[1])) + geom_point(colour="brown2", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_na <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[8], y = names(model1dNonRural$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_pi <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[9], y = names(model1dNonRural$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[9], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_2plus <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[10], y = names(model1dNonRural$model)[1])) + geom_point(colour="bisque3", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[10], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_other <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[11], y = names(model1dNonRural$model)[1])) + geom_point(colour="aquamarine3", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[11], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_HSdiploma <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[12], y = names(model1dNonRural$model)[1])) + geom_point(colour="dodgerblue", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[12], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_someCollege <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[13], y = names(model1dNonRural$model)[1])) + geom_point(colour="goldenrod1", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[13], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_Associates <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[14], y = names(model1dNonRural$model)[1])) + geom_point(colour="forestgreen", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[14], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_Bachelors <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[15], y = names(model1dNonRural$model)[1])) + geom_point(colour="indianred1", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[15], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_Masters <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[16], y = names(model1dNonRural$model)[1])) + geom_point(colour="khaki", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[16], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_Professional <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[17], y = names(model1dNonRural$model)[1])) + geom_point(colour="tomato", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[17], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dNonRural_Doctorate <- ggplot(model1dNonRural$model, aes_string(x = names(model1dNonRural$model)[18], y = names(model1dNonRural$model)[1])) + geom_point(colour="thistle", alpha = 0.1) + geom_abline(intercept = coef(model1dNonRural)[1], slope = coef(model1dNonRural)[18], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1dNonRural_average_income, model1dNonRural_median_housing_price, model1dNonRural_urban, model1dNonRural_black, model1dNonRural_hispanic, model1dNonRural_asian, model1dNonRural_na, model1dNonRural_pi, model1dNonRural_2plus, model1dNonRural_other, model1dNonRural_HSdiploma, model1dNonRural_someCollege, model1dNonRural_Associates, model1dNonRural_Bachelors, model1dNonRural_Masters, model1dNonRural_Professional, model1dNonRural_Doctorate, nrow=4, top="Access to protected land with all variables accounted for except rural areas")
model1dUrban <- lm(ldist ~ average_income + median_housing_price + share_black + share_hispanic + share_asian + share_native_american + share_pacific_islander + share_2plus + share_other + HSdiploma + someCollege + Associates + Bachelors + Masters + Professional + Doctorate, ProtectedLandUrban)
summary(model1dUrban)
model1dUrban_average_income <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[2], y = names(model1dUrban$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[2], colour="black", size=1)
model1dUrban_median_housing_price <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[3], y = names(model1dUrban$model)[1])) + geom_point(colour="coral", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[3], colour="black", size=1)
model1dUrban_black <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[4], y = names(model1dUrban$model)[1])) + geom_point(colour="cadetblue", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_hispanic <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[5], y = names(model1dUrban$model)[1])) + geom_point(colour="burlywood", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_asian <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[6], y = names(model1dUrban$model)[1])) + geom_point(colour="brown2", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_na <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[7], y = names(model1dUrban$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_pi <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[8], y = names(model1dUrban$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_2plus <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[9], y = names(model1dUrban$model)[1])) + geom_point(colour="bisque3", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[9], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_other <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[10], y = names(model1dUrban$model)[1])) + geom_point(colour="aquamarine3", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[10], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_HSdiploma <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[11], y = names(model1dUrban$model)[1])) + geom_point(colour="dodgerblue", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[11], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_someCollege <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[12], y = names(model1dUrban$model)[1])) + geom_point(colour="goldenrod1", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[12], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_Associates <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[13], y = names(model1dUrban$model)[1])) + geom_point(colour="forestgreen", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[13], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_Bachelors <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[14], y = names(model1dUrban$model)[1])) + geom_point(colour="indianred1", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[14], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_Masters <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[15], y = names(model1dUrban$model)[1])) + geom_point(colour="khaki", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[15], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_Professional <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[16], y = names(model1dUrban$model)[1])) + geom_point(colour="tomato", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[16], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dUrban_Doctorate <- ggplot(model1dUrban$model, aes_string(x = names(model1dUrban$model)[17], y = names(model1dUrban$model)[1])) + geom_point(colour="thistle", alpha = 0.1) + geom_abline(intercept = coef(model1dUrban)[1], slope = coef(model1dUrban)[17], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1dUrban_average_income, model1dUrban_median_housing_price, model1dUrban_black, model1dUrban_hispanic, model1dUrban_asian, model1dUrban_na, model1dUrban_pi, model1dUrban_2plus, model1dUrban_other, model1dUrban_HSdiploma, model1dUrban_someCollege, model1dUrban_Associates, model1dUrban_Bachelors, model1dUrban_Masters, model1dUrban_Professional, model1dUrban_Doctorate, nrow=4, top="Access to protected land with all variables accounted for in urban areas")
model1dSuburban <- lm(ldist ~ average_income + median_housing_price + share_black + share_hispanic + share_asian + share_native_american + share_pacific_islander + share_2plus + share_other + HSdiploma + someCollege + Associates + Bachelors + Masters + Professional + Doctorate, ProtectedLandSuburban)
summary(model1dSuburban)
model1dSuburban_average_income <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[2], y = names(model1dSuburban$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[2], colour="black", size=1)
model1dSuburban_median_housing_price <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[3], y = names(model1dSuburban$model)[1])) + geom_point(colour="coral", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[3], colour="black", size=1)
model1dSuburban_black <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[4], y = names(model1dSuburban$model)[1])) + geom_point(colour="cadetblue", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_hispanic <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[5], y = names(model1dSuburban$model)[1])) + geom_point(colour="burlywood", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_asian <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[6], y = names(model1dSuburban$model)[1])) + geom_point(colour="brown2", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_na <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[7], y = names(model1dSuburban$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_pi <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[8], y = names(model1dSuburban$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_2plus <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[9], y = names(model1dSuburban$model)[1])) + geom_point(colour="bisque3", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[9], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_other <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[10], y = names(model1dSuburban$model)[1])) + geom_point(colour="aquamarine3", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[10], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_HSdiploma <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[11], y = names(model1dSuburban$model)[1])) + geom_point(colour="dodgerblue", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[11], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_someCollege <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[12], y = names(model1dSuburban$model)[1])) + geom_point(colour="goldenrod1", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[12], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_Associates <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[13], y = names(model1dSuburban$model)[1])) + geom_point(colour="forestgreen", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[13], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_Bachelors <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[14], y = names(model1dSuburban$model)[1])) + geom_point(colour="indianred1", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[14], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_Masters <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[15], y = names(model1dSuburban$model)[1])) + geom_point(colour="khaki", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[15], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_Professional <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[16], y = names(model1dSuburban$model)[1])) + geom_point(colour="tomato", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[16], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dSuburban_Doctorate <- ggplot(model1dSuburban$model, aes_string(x = names(model1dSuburban$model)[17], y = names(model1dSuburban$model)[1])) + geom_point(colour="thistle", alpha = 0.1) + geom_abline(intercept = coef(model1dSuburban)[1], slope = coef(model1dSuburban)[17], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1dSuburban_average_income, model1dSuburban_median_housing_price, model1dSuburban_black, model1dSuburban_hispanic, model1dSuburban_asian, model1dSuburban_na, model1dSuburban_pi, model1dSuburban_2plus, model1dSuburban_other, model1dSuburban_HSdiploma, model1dSuburban_someCollege, model1dSuburban_Associates, model1dSuburban_Bachelors, model1dSuburban_Masters, model1dSuburban_Professional, model1dSuburban_Doctorate, nrow=4, top="Access to protected land with all variables accounted for in suburban areas")
model1dRural <- lm(ldist ~ average_income + median_housing_price + share_black + share_hispanic + share_asian + share_native_american + share_pacific_islander + share_2plus + share_other + HSdiploma + someCollege + Associates + Bachelors + Masters + Professional + Doctorate, ProtectedLandRural)
summary(model1dRural)
model1dRural_average_income <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[2], y = names(model1dRural$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[2], colour="black", size=1)
model1dRural_median_housing_price <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[3], y = names(model1dRural$model)[1])) + geom_point(colour="coral", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[3], colour="black", size=1)
model1dRural_black <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[4], y = names(model1dRural$model)[1])) + geom_point(colour="cadetblue", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_hispanic <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[5], y = names(model1dRural$model)[1])) + geom_point(colour="burlywood", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_asian <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[6], y = names(model1dRural$model)[1])) + geom_point(colour="brown2", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_na <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[7], y = names(model1dRural$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_pi <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[8], y = names(model1dRural$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_2plus <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[9], y = names(model1dRural$model)[1])) + geom_point(colour="bisque3", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[9], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_other <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[10], y = names(model1dRural$model)[1])) + geom_point(colour="aquamarine3", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[10], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_HSdiploma <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[11], y = names(model1dRural$model)[1])) + geom_point(colour="dodgerblue", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[11], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_someCollege <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[12], y = names(model1dRural$model)[1])) + geom_point(colour="goldenrod1", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[12], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_Associates <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[13], y = names(model1dRural$model)[1])) + geom_point(colour="forestgreen", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[13], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_Bachelors <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[14], y = names(model1dRural$model)[1])) + geom_point(colour="indianred1", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[14], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_Masters <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[15], y = names(model1dRural$model)[1])) + geom_point(colour="khaki", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[15], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_Professional <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[16], y = names(model1dRural$model)[1])) + geom_point(colour="tomato", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[16], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model1dRural_Doctorate <- ggplot(model1dRural$model, aes_string(x = names(model1dRural$model)[17], y = names(model1dRural$model)[1])) + geom_point(colour="thistle", alpha = 0.1) + geom_abline(intercept = coef(model1dRural)[1], slope = coef(model1dRural)[17], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model1dRural_average_income, model1dRural_median_housing_price, model1dRural_black, model1dRural_hispanic, model1dRural_asian, model1dRural_na, model1dRural_pi, model1dRural_2plus, model1dRural_other, model1dRural_HSdiploma, model1dRural_someCollege, model1dRural_Associates, model1dRural_Bachelors, model1dRural_Masters, model1dRural_Professional, model1dRural_Doctorate, nrow=4, top="Access to protected land with all variables accounted for in rural areas")
print("Looking at non-rural areas (urban and suburban combined), we see that a combination of median housing price and average income, when taken with appropriate magnitudes, would oftentimes indicate increased access for higher-income communities (overall negative effect on distance) over lower-income communities. We also see mostly negative coefficients (decreased distance and thus increased access) for more educated communities, compared to mostly positive coefficients (increased distance and thus decreased access) for less educated communities. Therefore, while we cannot establish racial inequality in access to protected lands in urban and suburban areas, we can reasonably state that there is income and education-related inequality.")
# 2. If there is inequality, what might reduce it?
print("2. Since protected land areas are commonly established through local and state government groups, departments, or officials, we will investigate the relationship between voter participation, party affiliation, and protected land areas.")
ProtectedLand$registration <- ProtectedLand$Registered/ProtectedLand$voting_age_pop
ProtectedLand$participation <- ProtectedLand$Voted/ProtectedLand$voting_age_pop
ProtectedLandNonRural$registration <- ProtectedLandNonRural$Registered/ProtectedLandNonRural$voting_age_pop
ProtectedLandNonRural$participation <- ProtectedLandNonRural$Voted/ProtectedLandNonRural$voting_age_pop
# 2a. Does access increase with voter registration?
model2a <- lm(ldist ~ registration, ProtectedLandNonRural)
summary(model2a)
print("2a. The coefficient indicates that in non-rural California, as voter registration (proportion of voting age population that is registered to vote) increases, distance to protected land decreases (increased access).")
ggplot(ProtectedLandNonRural, aes(x=registration,y=ldist)) + geom_point(alpha = 0.05) + geom_smooth(method="lm") + labs(title="Distance to protected land decreases as voter registration increases") + theme(plot.title = element_text(hjust = 0.5), panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + annotate("text", x = 1.5, y = 2.5, label = paste("Slope =", round(coef(model2a)[2],5), "\nP =", round(summary(model2a)$coef[2,4],4), "\nAdj. R2 = ", round(summary(model2a)$adj.r.squared,7)), colour="red")
# 2b. Does access increase with voter participation?
model2b <- lm(ldist ~ participation, ProtectedLandNonRural)
summary(model2b)
print("2b. This coefficient indicates that in non-rural California, as voter participation (proportion of voting age population that voted in the last election) increases, distance to protected land also increases (decreased access).")
ggplot(ProtectedLandNonRural, aes(x=participation,y=ldist)) + geom_point(alpha = 0.05) + geom_smooth(method="lm") + labs(title="Distance to protected land increases as voter participation increases") + theme(plot.title = element_text(hjust = 0.5), panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + annotate("text", x = 1, y = 2.5, label = paste("Slope =", round(coef(model2b)[2],5), "\nP =", round(summary(model2b)$coef[2,4],4), "\nAdj. R2 = ", round(summary(model2b)$adj.r.squared,7)), colour="red")
model2bi <- lm(ldist ~ registration + participation, ProtectedLandNonRural)
summary(model2bi)
print("This model shows the same coefficient signs from previous models at high levels of significance, indicating that higher voter registration and lower voter participation would be associated with increased access to protected land areas. Speculatively, this may indicate that voter engagement (interacting with local officials and politics in ways other than voting) may impact local protected areas more so than voter just participation.")
model2bi_registration <- ggplot(model2bi$model, aes_string(x = names(model2bi$model)[2], y = names(model2bi$model)[1])) + geom_point(colour="gold", alpha = 0.05) + geom_abline(intercept = coef(model2bi)[1], slope = coef(model2bi)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,2))
model2bi_participation <- ggplot(model2bi$model, aes_string(x = names(model2bi$model)[3], y = names(model2bi$model)[1])) + geom_point(colour="skyblue", alpha = 0.05) + geom_abline(intercept = coef(model2bi)[1], slope = coef(model2bi)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,2))
grid.arrange(model2bi_registration,model2bi_participation,nrow=2, top="Increased registration and less participation show an decreased distance to protected land")
# 2c. Does access depend on county-wide party affiliation?
model2c <- lm(ldist ~ Ratio.Dem.Rep, ProtectedLand)
summary(model2c)
print("2c. The variable Ratio.Dem.Rep represents the ratio of the proportion of registered Democrats to the proportion of registered Republicans at the county level. This model indicates that as the ratio increases by county (more registered Democrats compared to registered Republicans), the distance to protected land decreases for census tracts in that county.")
ggplot(ProtectedLand, aes(x=Ratio.Dem.Rep,y=ldist)) + geom_point(alpha = 0.05) + geom_smooth(method="lm") + labs(title="Distance to protected land decreases with increased registered Democrats") + theme(plot.title = element_text(hjust = 0.5), panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + annotate("text", x = 4.5, y = 2.5, label = paste("Slope =", round(coef(model2c)[2],5), "\nP =", round(summary(model2c)$coef[2,4],4), "\nAdj. R2 = ", round(summary(model2c)$adj.r.squared,7)), colour="red")
# 2ci. If there is a relationship, does it still exist when considering population density classification (rural, suburban, urban)?
model2ciNonRural <- lm(ldist ~ Ratio.Dem.Rep, ProtectedLandNonRural)
summary(model2ciNonRural)
model2ciUrban <- lm(ldist ~ Ratio.Dem.Rep, ProtectedLandUrban)
summary(model2ciUrban)
model2ciSuburban <- lm(ldist ~ Ratio.Dem.Rep, ProtectedLandSuburban)
summary(model2ciSuburban)
model2ciRural <- lm(ldist ~ Ratio.Dem.Rep, ProtectedLandRural)
summary(model2ciRural)
print("2ci. This relationship persists through all population density segments we have examined in this data set.")
model2ciNonRuralPlot <- ggplot(ProtectedLandNonRural, aes(x=Ratio.Dem.Rep,y=ldist)) + geom_point(alpha = 0.05) + geom_smooth(method="lm") + xlab("Ratio.Dem.Rep (Nonrural)")
model2ciUrbanPlot <- ggplot(ProtectedLandUrban, aes(x=Ratio.Dem.Rep,y=ldist)) + geom_point(alpha = 0.05) + geom_smooth(method="lm") + xlab("Ratio.Dem.Rep (Urban)")
model2ciSuburbanPlot <- ggplot(ProtectedLandSuburban, aes(x=Ratio.Dem.Rep,y=ldist)) + geom_point(alpha = 0.05) + geom_smooth(method="lm") + xlab("Ratio.Dem.Rep (Suburban)")
model2ciRuralPlot <- ggplot(model2ciRural, aes(x=Ratio.Dem.Rep,y=ldist)) + geom_point(alpha = 0.05) + geom_smooth(method="lm") + xlab("Ratio.Dem.Rep (Rural)")
grid.arrange(model2ciNonRuralPlot,model2ciUrbanPlot,model2ciSuburbanPlot,model2ciRuralPlot,nrow=2, top="Irrespective of population density classification, distance to protected land decreases with increased registered Democrats")
# 2d. Are there relationships between voter participation/registration and other demographic characteristics?
# 2di. Race/ethnicity?
model2diReg <- lm(registration ~ share_black + share_hispanic + share_asian + share_native_american + share_pacific_islander + share_2plus + share_other, ProtectedLandNonRural)
summary(model2diReg)
model2diPart <- lm(participation ~ share_black + share_hispanic + share_asian + share_native_american + share_pacific_islander + share_2plus + share_other, ProtectedLandNonRural)
summary(model2diPart)
print("2di. All minority populations show decreased voter registration and decreased voter participation compared to white populations in non-rural counties of California.")
model2diReg_black <- ggplot(model2diReg$model, aes_string(x = names(model2diReg$model)[2], y = names(model2diReg$model)[1])) + geom_point(colour="pink", alpha = 0.1) + geom_abline(intercept = coef(model2diReg)[1], slope = coef(model2diReg)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diReg_hispanic <- ggplot(model2diReg$model, aes_string(x = names(model2diReg$model)[3], y = names(model2diReg$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model2diReg)[1], slope = coef(model2diReg)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diReg_asian <- ggplot(model2diReg$model, aes_string(x = names(model2diReg$model)[4], y = names(model2diReg$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model2diReg)[1], slope = coef(model2diReg)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diReg_na <- ggplot(model2diReg$model, aes_string(x = names(model2diReg$model)[5], y = names(model2diReg$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model2diReg)[1], slope = coef(model2diReg)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diReg_pi <- ggplot(model2diReg$model, aes_string(x = names(model2diReg$model)[6], y = names(model2diReg$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model2diReg)[1], slope = coef(model2diReg)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diReg_2plus <- ggplot(model2diReg$model, aes_string(x = names(model2diReg$model)[7], y = names(model2diReg$model)[1])) + geom_point(colour="lightblue", alpha = 0.1) + geom_abline(intercept = coef(model2diReg)[1], slope = coef(model2diReg)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diReg_other <- ggplot(model2diReg$model, aes_string(x = names(model2diReg$model)[8], y = names(model2diReg$model)[1])) + geom_point(colour="springgreen4", alpha = 0.1) + geom_abline(intercept = coef(model2diReg)[1], slope = coef(model2diReg)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model2diReg_black, model2diReg_hispanic, model2diReg_asian, model2diReg_na, model2diReg_pi, model2diReg_2plus, model2diReg_other, nrow=4, top="All minority populations show decreased voter registration compared to white populations")
model2diPart_black <- ggplot(model2diPart$model, aes_string(x = names(model2diPart$model)[2], y = names(model2diPart$model)[1])) + geom_point(colour="pink", alpha = 0.1) + geom_abline(intercept = coef(model2diPart)[1], slope = coef(model2diPart)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diPart_hispanic <- ggplot(model2diPart$model, aes_string(x = names(model2diPart$model)[3], y = names(model2diPart$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model2diPart)[1], slope = coef(model2diPart)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diPart_asian <- ggplot(model2diPart$model, aes_string(x = names(model2diPart$model)[4], y = names(model2diPart$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model2diPart)[1], slope = coef(model2diPart)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diPart_na <- ggplot(model2diPart$model, aes_string(x = names(model2diPart$model)[5], y = names(model2diPart$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model2diPart)[1], slope = coef(model2diPart)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diPart_pi <- ggplot(model2diPart$model, aes_string(x = names(model2diPart$model)[6], y = names(model2diPart$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model2diPart)[1], slope = coef(model2diPart)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diPart_2plus <- ggplot(model2diPart$model, aes_string(x = names(model2diPart$model)[7], y = names(model2diPart$model)[1])) + geom_point(colour="lightblue", alpha = 0.1) + geom_abline(intercept = coef(model2diPart)[1], slope = coef(model2diPart)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diPart_other <- ggplot(model2diPart$model, aes_string(x = names(model2diPart$model)[8], y = names(model2diPart$model)[1])) + geom_point(colour="springgreen4", alpha = 0.1) + geom_abline(intercept = coef(model2diPart)[1], slope = coef(model2diPart)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model2diPart_black, model2diPart_hispanic, model2diPart_asian, model2diPart_na, model2diPart_pi, model2diPart_2plus, model2diPart_other, nrow=4, top="All minority populations show decreased voter participation compared to white populations")
# 2dii. Education?
model2diiReg <- lm(registration ~ HSdiploma + someCollege + Associates + Bachelors + Masters + Professional + Doctorate, ProtectedLandNonRural)
summary(model2diiReg)
model2diiPart <- lm(participation ~ HSdiploma + someCollege + Associates + Bachelors + Masters + Professional + Doctorate, ProtectedLandNonRural)
summary(model2diiPart)
print("2dii. As education level increases, so does voter registration and voter turnout, except for communities with higher proportions of Doctorates, where we see turnout and participation levels much lower than all other education levels.")
model2diiReg_HSdiploma <- ggplot(model2diiReg$model, aes_string(x = names(model2diiReg$model)[2], y = names(model2diiReg$model)[1])) + geom_point(colour="pink", alpha = 0.1) + geom_abline(intercept = coef(model2diiReg)[1], slope = coef(model2diiReg)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiReg_someCollege <- ggplot(model2diiReg$model, aes_string(x = names(model2diiReg$model)[3], y = names(model2diiReg$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model2diiReg)[1], slope = coef(model2diiReg)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiReg_Associates <- ggplot(model2diiReg$model, aes_string(x = names(model2diiReg$model)[4], y = names(model2diiReg$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model2diiReg)[1], slope = coef(model2diiReg)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiReg_Bachelors <- ggplot(model2diiReg$model, aes_string(x = names(model2diiReg$model)[5], y = names(model2diiReg$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model2diiReg)[1], slope = coef(model2diiReg)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiReg_Masters <- ggplot(model2diiReg$model, aes_string(x = names(model2diiReg$model)[6], y = names(model2diiReg$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model2diiReg)[1], slope = coef(model2diiReg)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiReg_Professional <- ggplot(model2diiReg$model, aes_string(x = names(model2diiReg$model)[7], y = names(model2diiReg$model)[1])) + geom_point(colour="lightblue", alpha = 0.1) + geom_abline(intercept = coef(model2diiReg)[1], slope = coef(model2diiReg)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiReg_Doctorate <- ggplot(model2diiReg$model, aes_string(x = names(model2diiReg$model)[8], y = names(model2diiReg$model)[1])) + geom_point(colour="springgreen4", alpha = 0.1) + geom_abline(intercept = coef(model2diiReg)[1], slope = coef(model2diiReg)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model2diiReg_HSdiploma,model2diiReg_someCollege,model2diiReg_Associates,model2diiReg_Bachelors,model2diiReg_Masters,model2diiReg_Professional,model2diiReg_Doctorate, nrow=4, top="Higher levels of education typically lead to higher levels of voter registration")
model2diiPart_HSdiploma <- ggplot(model2diiPart$model, aes_string(x = names(model2diiPart$model)[2], y = names(model2diiPart$model)[1])) + geom_point(colour="pink", alpha = 0.1) + geom_abline(intercept = coef(model2diiPart)[1], slope = coef(model2diiPart)[2], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiPart_someCollege <- ggplot(model2diiPart$model, aes_string(x = names(model2diiPart$model)[3], y = names(model2diiPart$model)[1])) + geom_point(colour="cornflowerblue", alpha = 0.1) + geom_abline(intercept = coef(model2diiPart)[1], slope = coef(model2diiPart)[3], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiPart_Associates <- ggplot(model2diiPart$model, aes_string(x = names(model2diiPart$model)[4], y = names(model2diiPart$model)[1])) + geom_point(colour="chocolate", alpha = 0.1) + geom_abline(intercept = coef(model2diiPart)[1], slope = coef(model2diiPart)[4], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiPart_Bachelors <- ggplot(model2diiPart$model, aes_string(x = names(model2diiPart$model)[5], y = names(model2diiPart$model)[1])) + geom_point(colour="slateblue", alpha = 0.1) + geom_abline(intercept = coef(model2diiPart)[1], slope = coef(model2diiPart)[5], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiPart_Masters <- ggplot(model2diiPart$model, aes_string(x = names(model2diiPart$model)[6], y = names(model2diiPart$model)[1])) + geom_point(colour="firebrick", alpha = 0.1) + geom_abline(intercept = coef(model2diiPart)[1], slope = coef(model2diiPart)[6], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiPart_Professional <- ggplot(model2diiPart$model, aes_string(x = names(model2diiPart$model)[7], y = names(model2diiPart$model)[1])) + geom_point(colour="lightblue", alpha = 0.1) + geom_abline(intercept = coef(model2diiPart)[1], slope = coef(model2diiPart)[7], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
model2diiPart_Doctorate <- ggplot(model2diiPart$model, aes_string(x = names(model2diiPart$model)[8], y = names(model2diiPart$model)[1])) + geom_point(colour="springgreen4", alpha = 0.1) + geom_abline(intercept = coef(model2diiPart)[1], slope = coef(model2diiPart)[8], colour="black", size=1) + coord_cartesian(xlim=c(0,1))
grid.arrange(model2diiPart_HSdiploma,model2diiPart_someCollege,model2diiPart_Associates,model2diiPart_Bachelors,model2diiPart_Masters,model2diiPart_Professional,model2diiPart_Doctorate, nrow=4, top="Higher levels of education typically lead to higher levels of voter participation")
# 2diii. Income?
model2diiiReg <- lm(registration ~ average_income, ProtectedLandNonRural)
summary(model2diiiReg)
model2diiiPart <- lm(participation ~ average_income, ProtectedLandNonRural)
summary(model2diiiPart)
print("2diii. As income increases, so does voter registration and voter participation.")
ggplot(ProtectedLandNonRural, aes(x=average_income,y=registration)) + geom_point(alpha = 0.05) + geom_smooth(method="lm") + labs(title="Increased average income shows increased voter registration") + theme(plot.title = element_text(hjust = 0.5), panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + annotate("text", x = 100000, y = 1.5, label = paste("Slope =", coef(model2diiiReg)[2], "\nP =", round(summary(model2diiiReg)$coef[2,4],4), "\nAdj. R2 = ", round(summary(model2diiiReg)$adj.r.squared,7)), colour="red")
ggplot(ProtectedLandNonRural, aes(x=average_income,y=participation)) + geom_point(alpha = 0.05) + geom_smooth(method="lm") + labs(title="Increased average income shows increased voter participation") + theme(plot.title = element_text(hjust = 0.5), panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + annotate("text", x = 100000, y = 1.1, label = paste("Slope =", coef(model2diiiPart)[2], "\nP =", round(summary(model2diiiPart)$coef[2,4],4), "\nAdj. R2 = ", round(summary(model2diiiPart)$adj.r.squared,7)), colour="red")
# 2div. Housing price?
model2divReg <- lm(registration ~ median_housing_price, ProtectedLandNonRural)
summary(model2divReg)
model2divPart <- lm(participation ~ median_housing_price, ProtectedLandNonRural)
summary(model2divPart)
print("2div. As median housing price increases, so does voter registration and voter participation.")
ggplot(ProtectedLandNonRural, aes(x=median_housing_price,y=registration)) + geom_point(alpha = 0.05) + geom_smooth(method="lm") + labs(title="Increased median housing price shows increased voter registration") + theme(plot.title = element_text(hjust = 0.5), panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + annotate("text", x = 750000, y = 1.5, label = paste("Slope =", coef(model2divReg)[2], "\nP =", round(summary(model2divReg)$coef[2,4],4), "\nAdj. R2 = ", round(summary(model2divReg)$adj.r.squared,7)), colour="red")
ggplot(ProtectedLandNonRural, aes(x=median_housing_price,y=participation)) + geom_point(alpha = 0.05) + geom_smooth(method="lm") + labs(title="Increased median housing price shows increased voter participation") + theme(plot.title = element_text(hjust = 0.5), panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + annotate("text", x = 750000, y = 1, label = paste("Slope =", coef(model2divPart)[2], "\nP =", round(summary(model2divPart)$coef[2,4],4), "\nAdj. R2 = ", round(summary(model2divPart)$adj.r.squared,7)), colour="red")
print("Voter registration, a significant indicator of access to protected land areas by census tract, is reduced in certain communities of color, less educated communities, and lower income communities. Voter participation is similarly impacted in disadvantaged communities, but we do not see increased voter participation have the same association with access. With this knowledge, and without direct intervention to designate protected land areas in disadvantaged communities, we would suggest focusing on increasing voter registration in those communities as a gateway for increased voter engagement. That being said, direct intervention may be necessary, as disadvantaged communities often have more difficulty engaging with politics (lack of flexible working hours, inaccessibility to engagement opportunities).")
# 3. Can we use a small set of variables to identify non-rural census tracts where voter engagement (registration) is low and efforts to improve it would be most beneficial to the community?
model3Data <- na.omit(ProtectedLandNonRural)
randIndex <- sample(1:dim(model3Data)[1])
cutpoint <- floor(2*dim(model3Data)[1]/3)
trainData <- model3Data[randIndex[1:cutpoint],]
testData <- model3Data[randIndex[(cutpoint+1):dim(model3Data)[1]],]
trainData$lowReg[trainData$registration < mean(model3Data$registration)] <- 1
trainData$lowReg[trainData$registration >= mean(model3Data$registration)] <- 0
testData$lowReg[testData$registration < mean(model3Data$registration)] <- 1
testData$lowReg[testData$registration >= mean(model3Data$registration)] <- 0
trainData$lowReg <- as.factor(trainData$lowReg)
testData$lowReg <- as.factor(testData$lowReg)
model3 <- ksvm(lowReg ~ median_housing_price + average_income + lessthanHS + Ratio.Dem.Rep, data = trainData, kernel = "rbfdot", kpar = "automatic", C = 5, cross = 3, prob.model = TRUE)
model3
model3Pred <- predict(model3, testData)
testComp <- data.frame(testData, model3Pred)
correctPercent <- length(which(testComp$lowReg == testComp$model3Pred))/length(testComp$lowReg)
correctPercent
testComp$PredWrong[testComp$lowReg == testComp$model3Pred] <- 0
testComp$PredWrong[testComp$lowReg != testComp$model3Pred] <- 1
testComp$PredWrong <- as.factor(testComp$PredWrong)
model3plot <- ggplot(testComp) + geom_point(aes(y=average_income, x=lessthanHS, size=PredWrong, color=lowReg, shape=model3Pred)) + labs(title="Identifying non-rural areas where voter registration is low") + theme(plot.title = element_text(hjust = 0.5))
model3plot
print("Using ksvm, we can use the data we have available to identify non-rural census tracts where voter engagement (registration) is low. Efforts to improve it would be most beneficial to the community and improve access to protected lands.")
|
8348c392fd9bbe1be8b5766c058d3f47e6840737
|
08a2a7468e3f09e803afb74616b9c37fd4f05335
|
/R/server-side.R
|
9acecd0fdc2fa1859f0293d792bc02c869bbed6d
|
[
"MIT"
] |
permissive
|
ginberg/brochure
|
8b2e9fb6551d045730fb3e14f6950ebafb583d2e
|
33a1c2fe59e5ec43cb800bc0864eb388638eefd9
|
refs/heads/main
| 2023-03-05T00:43:56.760095
| 2021-02-23T07:11:48
| 2021-02-23T07:11:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 314
|
r
|
server-side.R
|
#' Do a server side redirection
#'
#' @param to the destination of the redirection
#' @param session shiny session object, default is `shiny::getDefaultReactiveDomain()`
#'
#' @export
server_redirect <- function(
to,
session = shiny::getDefaultReactiveDomain()
){
session$sendCustomMessage("redirect", to)
}
|
64f300ee3e37d1572ed819eac16d3d3841d7a6c6
|
150ddbd54cf97ddf83f614e956f9f7133e9778c0
|
/man/delin.Rd
|
8d893e16a3e15ec96fbff8d26f7e4686d608f68d
|
[
"CC-BY-4.0"
] |
permissive
|
debruine/webmorphR
|
1119fd3bdca5be4049e8793075b409b7caa61aad
|
f46a9c8e1f1b5ecd89e8ca68bb6378f83f2e41cb
|
refs/heads/master
| 2023-04-14T22:37:58.281172
| 2022-08-14T12:26:57
| 2022-08-14T12:26:57
| 357,819,230
| 6
| 4
|
CC-BY-4.0
| 2023-02-23T04:56:01
| 2021-04-14T07:47:17
|
R
|
UTF-8
|
R
| false
| true
| 985
|
rd
|
delin.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/delin.R
\name{delin}
\alias{delin}
\title{Manually delineate images}
\usage{
delin(stimuli)
}
\arguments{
\item{stimuli}{list of stimuli}
}
\value{
list of stimuli with new templates
}
\description{
Adjust the templates in a shiny interface. This will overwrite existing templates.
}
\examples{
if (interactive()) {
# adjust existing delineations
stimuli <- demo_stim() |> delin()
# create new delineations from scratch
stimuli <- demo_stim() |> remove_tems() |> delin()
}
}
\seealso{
Template functions
\code{\link{auto_delin}()},
\code{\link{average_tem}()},
\code{\link{centroid}()},
\code{\link{change_lines}()},
\code{\link{draw_tem}()},
\code{\link{features}()},
\code{\link{get_point}()},
\code{\link{remove_tem}()},
\code{\link{require_tems}()},
\code{\link{same_tems}()},
\code{\link{squash_tem}()},
\code{\link{subset_tem}()},
\code{\link{tem_def}()},
\code{\link{viz_tem_def}()}
}
\concept{tem}
|
015aa2b7e044e80ff66c561995706dc11c921db3
|
29585dff702209dd446c0ab52ceea046c58e384e
|
/REAT/R/locq.R
|
a447b4215d2a8118b5587640c8ed20b8705c4c5c
|
[] |
no_license
|
ingted/R-Examples
|
825440ce468ce608c4d73e2af4c0a0213b81c0fe
|
d0917dbaf698cb8bc0789db0c3ab07453016eab9
|
refs/heads/master
| 2020-04-14T12:29:22.336088
| 2016-07-21T14:01:14
| 2016-07-21T14:01:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 205
|
r
|
locq.R
|
locq <-
function (e_ij, e_j, e_i, e) {
if (e_ij > e_j) { return (NA) }
if (e_i > e) { return (NA) }
if (e_j > e) { return (NA) }
s_ij <- e_ij/e_i
s_j <- e_j/e
LQ <- s_ij/s_j
return(LQ)
}
|
138c056bc141eb710f0fffda90277cdf9823ad99
|
2b76e72f3e46d2fa85721b1a6ff4bdbb71c40f04
|
/man/csv_to_sheet.Rd
|
99758b516818dd1a687132afa0def16b46bdcccb
|
[
"MIT"
] |
permissive
|
elias-jhsph/rsmartsheet
|
ae7f1a8531ce2225417d3444d3de213152c169d5
|
18bff1da9dce5acdaff07a3da49c5fe4827c4d98
|
refs/heads/master
| 2021-07-07T09:57:20.373524
| 2021-05-10T17:57:50
| 2021-05-10T17:57:50
| 236,876,103
| 8
| 6
| null | null | null | null |
UTF-8
|
R
| false
| true
| 545
|
rd
|
csv_to_sheet.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Smartsheet-R-sdk.R
\name{csv_to_sheet}
\alias{csv_to_sheet}
\title{Create New Smartsheet}
\usage{
csv_to_sheet(file_path, all_text_number = FALSE)
}
\arguments{
\item{file_path}{a path which locates the csv and provides the name}
}
\value{
returns nothing
}
\description{
Create New Smartsheet
}
\examples{
\dontrun{
csv_to_sheet("a_folder/maybe_another_folder/sheet_name.csv", 123456789)
csv_to_sheet("a_folder/maybe_another_folder/sheet_name.csv", "123456789")
}
}
|
653b892c2980eb843eeff190396a0eaafbf5132d
|
c83d3adcad7bdf5043935a3ecb22277bdb0ff5f0
|
/HW1/HW1.r
|
ff465448886c2c5d5324d5ece82bd3ae96b832a0
|
[] |
no_license
|
Ninada-U/Math-189
|
0477ed893703c6a828f0ae7c5c2c79bcc0a1280a
|
bf0131ea302470c80df2c46a0f3802af54a9be10
|
refs/heads/master
| 2022-06-04T02:38:00.078783
| 2020-05-04T01:48:23
| 2020-05-04T01:48:23
| 256,535,545
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,026
|
r
|
HW1.r
|
library(ggplot2)
# read in data
bb = read.table('babies.txt', header=1)
bb$smoke[bb$smoke == 0] <- "Non-smoker"
bb$smoke[bb$smoke == 1] <- "Smoker"
bb <- bb[bb$smoke!=9,]
# remove extreme outliers
bb <- bb[bb$smoke!=9,]
bb <- bb[bb$weight<750,]
bb <- bb[bb$height<75,]
bb <- bb[bb$age<50,]
bb <- bb[bb$gestation<500,]
# boxplot data
bb = rbind(ns, s)
p = ggplot(bb, aes(x=smoke, y=bwt, group=smoke)) + geom_boxplot()
p + labs(title="Baby Weights in Smoking vs Non-smoking Mothers",
x="Mother's Smoking Status",
y="Baby Weight (oz)")
# print mean and sd for smokers and non-smokers
cat("non-smoker\n")
cat("mean", mean(ns$bwt), '\n')
cat("sd", sd(ns$bwt), '\n')
cat("smoker\n")
cat("mean", mean(s$bwt), '\n')
cat("sd", sd(s$bwt))
# Q-Q Plot
qqnorm(s$bwt, pch = 1, frame=FALSE, main="Smoker")
qqline(s$bwt, col="steelblue", lwd=2)
# split data into non-smokers and smokers
ns<-bb[bb$smoke=="Non-smoker",]
s<-bb[bb$smoke=="Smoker",]
# filter smokers and non-smokers by 'box whisker' method
Q1 = summary(ns$bwt)['1st Qu.']
Q3 = summary(ns$bwt)['3rd Qu.']
IQR = Q3-Q1
min_cutoff = Q1 - (1.5*IQR)
max_cutoff = Q3 + (1.5*IQR)
ns<-ns[ns$bwt > min_cutoff, ]
ns<-ns[ns$bwt < max_cutoff, ]
Q1 = summary(s$bwt)['1st Qu.']
Q3 = summary(s$bwt)['3rd Qu.']
IQR = Q3-Q1
min_cutoff = Q1 - (1.5*IQR)
max_cutoff = Q3 + (1.5*IQR)
s<-s[s$weight > min_cutoff, ]
s<-s[s$weight < max_cutoff, ]
# create histogram
p = ggplot(bb, aes(bwt, fill=smoke)) + geom_histogram(alpha=.5, aes(y=..density..), position='identity')
p + labs(title="Density of Baby Weights in Smoking vs Non-smoking Mothers",
x="Baby Weight (oz)",
y="Density")
# generate gestational periods table
means <- list()
sds <- list()
for (i in 32:46) {
week_lower = i
week_upper = i + 1
day_lower = week_lower * 7
day_upper = week_upper * 7
t <- ns[ns$gestation < day_upper, ]
mean <- sum(t$bwt) / nrow(t)
means[i] <- mean
sd <- sd(t$bwt)
sds[i] <- sd
cat("week", i, ":", mean, "sd:", sd, "\n")
}
|
21cd31896287805860a3e33d6159671a827388de
|
4a953f8360e02b48c8fc0cce3247ce85461386e2
|
/man/physics.Rd
|
40a3b941720780a99050f4aebaf4dad062e2dadd
|
[] |
no_license
|
cran/alr3
|
70aa935c50ea155544e3753638b8ecf14389578a
|
e0417610cc7ecf5d1fd4900d831a7bf8ea18c492
|
refs/heads/master
| 2021-01-16T00:27:48.401071
| 2018-06-22T20:05:11
| 2018-06-22T20:05:11
| 17,694,346
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 930
|
rd
|
physics.Rd
|
\name{physics}
\alias{physics}
\alias{physics1}
\docType{data}
\title{Physics data}
\description{
The file physics constains results for \eqn{\pi^+}{pi+} meson as input and
\eqn{\pi^+}{pi+} meson as
output. physics1 is for \eqn{\pi^-}{pi-} to \eqn{\pi^-}{pi-}.
}
\format{This data frame contains the following columns:
\describe{
\item{x}{
Inverse total energy
}
\item{y}{
Scattering cross-section/sec
}
\item{SD}{
Standard deviation
}
}
}
\source{
Weisberg, H., Beier, H., Brody, H., Patton, R., Raychaudhari, K., Takeda, H.,
Thern, R. and Van Berg, R. (1978).
s-dependence of proton fragmentation by hadrons. II. Incident laboratory
momenta, 30--250 GeV/c. \emph{Physics Review D}, 17, 2875--2887. }
\references{Weisberg, S. (2005). \emph{Applied Linear Regression}, 3rd edition. New York: Wiley, Section 5.1.1.}
\examples{
head(physics1)
}
\keyword{datasets}
|
b8f25b321e7c97ed1dea2219bda19f5c6e43ae0e
|
540f7014a92ebaf0f6d9a0d0365bc806c2c33b88
|
/ca4EnrichVsFold.r
|
fb41489fa35f4170dd6e44bb3a5b9125fb9fdc4f
|
[
"MIT"
] |
permissive
|
cembrowskim/hipposeq
|
7b550ea4ec0a1c5833cab7966c6c45df8c623022
|
4b6d2d1af76e580da24eed703ed554f582868faf
|
refs/heads/master
| 2021-01-10T13:33:40.792302
| 2016-04-28T17:42:03
| 2016-04-28T17:42:03
| 54,387,642
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,391
|
r
|
ca4EnrichVsFold.r
|
####################################################################################
#
# Mark Cembrowski, Janelia Research Campus, April 8 2015
#
# This script looks for the number of mossy cell-enriched transcripts relative
# to neighbouring DG GCs and CA3 PCs.
#
####################################################################################
ca4EnrichVsFold <- function(fpkmThres=10){
theFolds <- c(2:10)
df <- as.data.frame(matrix(nrow=theFolds,ncol=3))
theMask <- setdiff(colnames(fpkmPoolMat),c('dg_d','ca4','ca3_d'))
for (ii in 1:length(theFolds)){
numDgEnrich <- length(enrichedGenes('dg_d',fpkmThres=fpkmThres,
foldThres=theFolds[ii],avgPass=T,mask=theMask))
numCa4Enrich <- length(enrichedGenes('ca4',fpkmThres=fpkmThres,
foldThres=theFolds[ii],avgPass=T,mask=theMask))
numCa3Enrich <- length(enrichedGenes('ca3_d',fpkmThres=fpkmThres,
foldThres=theFolds[ii],avgPass=T,mask=theMask))
df[ii,] <- c(numDgEnrich,numCa4Enrich,numCa3Enrich)
}
df <- cbind(theFolds,df)
colnames(df) <- c('theFolds','dg','ca4','ca3')
# Plot.
gg <- ggplot(df,aes(x=theFolds))
gg <- gg + geom_line(aes(y=dg),colour='red')
gg <- gg + geom_line(aes(y=ca4),colour='magenta')
gg <- gg + geom_line(aes(y=ca3),colour='green')
gg <- gg + theme_bw()
gg <- gg + expand_limits(y=0)
gg <- gg + xlab('Fold difference') + ylab('Number of genes')
print(gg)
invisible(df)
}
|
7d006c9ac9177bb1604a9385e04f2b325eaa2717
|
60d40635d000c7a7ef0b8774da34ab3c29d6502e
|
/misc/visu/draw_cumulative.R
|
e2e29b7a5f27260010a0836a27a281890953aa9c
|
[] |
no_license
|
obps/obps
|
8d6ce068ab5b802937ad6b8105367703105e4ed5
|
01df6619cc3d96fe821a6650979fa9f8031e9bdb
|
refs/heads/master
| 2020-12-31T06:47:01.030245
| 2017-03-31T07:57:56
| 2017-03-31T07:57:56
| 86,603,881
| 1
| 0
| null | 2017-03-29T16:16:07
| 2017-03-29T16:16:07
| null |
UTF-8
|
R
| false
| false
| 6,909
|
r
|
draw_cumulative.R
|
#!/usr/bin/env Rscript
'usage: tool.R <input_file> ... [-o <output_pdf>] [-l <lineinput>]
tool.R -h | --help
options:
<input_file> The input data.
-o <output_pdf> Output file in case of pdf/tikz/png output.
-l <lineinput> lineinput.
-h , --help Show this screen.
' -> doc
library(docopt)
args<- docopt(doc)
print(args)
args$r=as.numeric(args$r)
args$H=as.numeric(args$H)
png(file=args$o,width=1800,height=800)
library('TTR')
library('gridExtra')
library('ggplot2')
library('reshape2')
library('plyr')
theme_bw_tuned<-function()
{
return(theme_bw() +theme(
plot.title = element_text(face="bold", size=10),
axis.title.x = element_text(face="bold", size=10),
axis.title.y = element_text(face="bold", size=10, angle=90),
axis.text.x = element_text(size=10),
axis.text.y = element_text(size=10),
panel.grid.minor = element_blank(),
legend.key = element_rect(colour="white"))
)
}
swf_read <- function(f)
{
df <- read.table(f,comment.char=';')
print(f)
names(df) <- c('job_id','submit_time','wait_time','run_time','proc_alloc','cpu_time_used','mem_used','proc_req','time_req','mem_req','status','user_id','group_id','exec_id','queue_id','partition_id','previous_job_id','think_time')
return(df)
}
flow <- function(swf){
nbefore = nrow(data)
data = data[which(!is.na(data$wait_time)),]
if( nbefore != nrow(data))
print(paste("There were", nbefore-nrow(data), "jobs with corrupted wait time or run time"))
return(data$wait_time)
}
utilization <- function( data,utilization_start=0 )
{
data = arrange(data, submit_time)
# get start time and stop time of the jobs
start <- data$submit_time + data$wait_time
stop <- data$submit_time + data$wait_time + data$run_time
# because jobs still running have an -1 runtime
stop[which(data$run_time == -1 & data$wait_time != -1)] = max(stop)
# because jobs not schedlued yet have an -1 runtime and wait time
stop[which(data$run_time == -1 & data$wait_time == -1)] = max(stop)
start[which(data$run_time == -1 & data$wait_time == -1)] = max(stop)
first_sub = min(data$submit_time)
first_row = data.frame(timestamp=first_sub, cores_instant=utilization_start)
# link events with cores number (+/-)
startU <- cbind(start, data$proc_alloc)
endU <- cbind(stop, -data$proc_alloc)
# make one big dataframe
U <- rbind(startU, endU)
colnames(U) <- c("timestamp","cores_instant")
U <- rbind(as.data.frame(first_row), U)
U <- as.data.frame(U)
# merge duplicate rows by summing the cores nb modifications
U <- aggregate(U$cores_instant, list(timestamp=U$timestamp), sum)
# make a cumulative sum over the dataframe
U <- cbind(U[,1],cumsum(U[,2])) # TODO: if goes under '0', maybe try something for discovering the utilization offset... difficult
colnames(U) <- c("timestamp","cores_used")
U <- as.data.frame(U)
# return the dataframe
return(U)
}
timestamp_to_date <- function(timestamp){
return(as.POSIXct(timestamp, origin="1970-01-01 01:00.00", tz="Europe/Paris"))
}
queue_size<- function(swf)
{
# get start time of the jobs
start <- swf$submit_time + swf$wait_time
# link events with cores number (+/-)
submits <- cbind(swf$submit_time, swf$proc_req)
starts <- cbind(start, -swf$proc_req)
# submits <- cbind(swf$submit_time, swf$proc_alloc)
# starts <- cbind(start, -swf$proc_alloc)
# because jobs still queued have an -1 wait_time
starts[which(swf$wait_time == -1)] = max(starts) + 1
# make one big dataframe
U <- rbind(submits, starts)
colnames(U) <- c("timestamp","cores_instant")
U <- as.data.frame(U)
# merge duplicate rows by summing the cores nb modifications
U <- aggregate(U$cores_instant, list(timestamp=U$timestamp), sum)
# make a cumulative sum over the dataframe
U <- cbind(U[,1],cumsum(U[,2]))
colnames(U) <- c("timestamp","cores_queued")
U <- as.data.frame(U)
# add a new column: dates
U <- cbind(U, timestamp_to_date(U$timestamp))
colnames(U) <- c("timestamp","cores_queued","date")
U <- as.data.frame(U)
# return the dataframe
U
}
dfs=data.frame()
dfsq=data.frame()
for (swf_filename in args$input_file){
data=swf_read(swf_filename)
data$values=as.numeric(flow(data))
d=data[order(data$submit_time),]
data$csum=cumsum(as.numeric(data$values))
cum=data$csum
time=data$submit_time
ema=EMA(data$value,n=nrow(data)/100)
values=data$values
values=values[order(time)]
r=data.frame(cumsumbsld=cum,
emabsld=ema,
wvalues=values,
time=time,
type=basename(swf_filename))
table <- utilization(data)
table <- as.data.frame(table)
table$time=table$timestamp
table$cores_ema=EMA(n=nrow(data)/1000,table$cores_used[order(table$time)])
r<-merge(r,table,by="time")
r<-r[order(time),]
queue = queue_size(data)
queue$type=basename(swf_filename)
dfsq=rbind(dfsq,queue)
dfs=rbind(dfs,r)
}
dfs=dfs[which(!is.na(dfs$timestamp)),]
dfsq$time=dfsq$timestamp
mintime=min(dfs$time)
maxtime=max(dfs$time)
timespan=maxtime-mintime
df1 <- melt(dfs, measure.vars = c("wvalues","emabsld", "cores_used","cumsumbsld"))
df2 <- melt(dfsq, measure.vars = c("cores_queued"))
keeps <- c("time","value","variable","type")
dff=rbind(df1[keeps],df2[keeps])
dff$variable <- factor(dff$variable,
levels = c("emabsld",
"cores_used",
"cumsumbsld",
"wvalues",
"cores_queued"),
labels = c("flow m.a.",
"Cores Used",
"cum. flow",
"wvalues",
"Cores Queued"))
brk=seq(mintime,maxtime,timespan/(20))
li = read.table(args$l)
names(li) <- c("v1")
ggplot() +
geom_step(data=subset(dff, variable=="cum. flow"),
aes(x = time, y = value, color = type)) +
geom_vline(data=li, aes(xintercept = v1)) +
scale_x_continuous(breaks = brk)+
scale_color_brewer("File",palette="Dark2")+
xlab("Time (seconds)") +
theme_bw_tuned() +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
axis.title.y=element_blank(),
strip.text.y = element_text(size=8, face="bold"),
strip.background = element_rect(colour="White", fill="#FFFFFF"))
#png(file=args$b,width=1800,height=800)
##summary(dff)
#df2=subset(dff, variable=="wvalues")
#df2=df2[which(df2$variable=="wvalues"),]
#df2$week= df2$time %/% 604800
#df2$week=as.numeric(df2$week)
#df2$value=as.numeric(df2$value)
##summary(df2)
#df3 = aggregate(value ~ week * type,df2,mean)
#print(df3)
#ggplot() +
#geom_line(data=df3,aes(x=week,y=value,color=type)) +
#geom_line(data=df3,aes(x=week,y=value,color=type)) +
#theme_bw_tuned()
|
2182f9cb41c1d21bdf80834b78718d6522ea42b1
|
2d34708b03cdf802018f17d0ba150df6772b6897
|
/googledeploymentmanageralpha.auto/man/ResourceUpdate.error.Rd
|
0bc0641e6c1f9eec394ebfe2240296ba7b8d3d84
|
[
"MIT"
] |
permissive
|
GVersteeg/autoGoogleAPI
|
8b3dda19fae2f012e11b3a18a330a4d0da474921
|
f4850822230ef2f5552c9a5f42e397d9ae027a18
|
refs/heads/master
| 2020-09-28T20:20:58.023495
| 2017-03-05T19:50:39
| 2017-03-05T19:50:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 956
|
rd
|
ResourceUpdate.error.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/deploymentmanager_objects.R
\name{ResourceUpdate.error}
\alias{ResourceUpdate.error}
\title{ResourceUpdate.error Object}
\usage{
ResourceUpdate.error(ResourceUpdate.error.errors = NULL, errors = NULL)
}
\arguments{
\item{ResourceUpdate.error.errors}{The \link{ResourceUpdate.error.errors} object or list of objects}
\item{errors}{[Output Only] The array of errors encountered while processing this operation}
}
\value{
ResourceUpdate.error object
}
\description{
ResourceUpdate.error Object
}
\details{
Autogenerated via \code{\link[googleAuthR]{gar_create_api_objects}}
[Output Only] If errors are generated during update of the resource, this field will be populated.
}
\seealso{
Other ResourceUpdate functions: \code{\link{ResourceUpdate.error.errors}},
\code{\link{ResourceUpdate.warnings.data}},
\code{\link{ResourceUpdate.warnings}},
\code{\link{ResourceUpdate}}
}
|
991c6879300a361c31aeb45524fb6deccb26fcb9
|
a135835b38ef0f196012b594bc7fe7856722159f
|
/man/fit.networkBasedSVM.Rd
|
86d02ce3307d9efa80ad8c7ee687a08f6716ca97
|
[] |
no_license
|
cran/pathClass
|
6365bec2abcde76934dc80dcdb7d957724e1a221
|
c9fe63704541d30300697f310caf53abe01b71b7
|
refs/heads/master
| 2021-01-10T21:38:46.012952
| 2013-06-25T00:00:00
| 2013-06-25T00:00:00
| 17,698,371
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,376
|
rd
|
fit.networkBasedSVM.Rd
|
\name{fit.networkBasedSVM}
\alias{fit.networkBasedSVM}
\title{Implementation of the network-based Support Vector Machine introduced by Yanni Zhu et al., 2009.}
\usage{
fit.networkBasedSVM(exps, y, DEBUG = FALSE, n.inner = 3,
scale = c("center", "scale"), sd.cutoff = 1,
lambdas = 10^(-2:4), adjacencyList)
}
\arguments{
\item{exps}{a p x n matrix of expression measurements
with p samples and n genes.}
\item{y}{a factor of length p comprising the class
labels.}
\item{DEBUG}{should debugging information be plotted.}
\item{n.inner}{number of fold for the inner
cross-validation.}
\item{scale}{a character vector defining if the data
should be centered and/or scaled. Possible values are
\emph{center} and/or \emph{scale}. Defaults to
\code{c('center', 'scale')}.}
\item{sd.cutoff}{a cutoff on the standard deviation (sd)
of genes. Only genes with sd > sd.cutoff stay in the
analysis.}
\item{lambdas}{a set of values for lambda regularization
parameter of the L\eqn{_\infty}-Norm. Which, if properly
chosen, eliminates factors that are completely irrelevant
to the response, what in turn leads to a factor-wise
(subnetwork-wise) feature selection. The 'best' lambda is
found by an inner-cross validation.}
\item{adjacencyList}{a adjacency list representing the
network structure. The list can be generated from a
adjacency matrix by using the function
\code{\link{as.adjacencyList}}}
}
\value{
a networkBasedSVM object containing \item{features}{the
selected features} \item{lambda.performance}{overview how
different values of lambda performed in the inner cross
validation} \item{fit}{the fitted network based SVM
model}
}
\description{
\code{mapping} must be a data.frame with at least two
columns. The column names have to be
\code{c('probesetID','graphID')}. Where 'probesetID' is
the probeset ID present in the expression matrix (i.e.
\code{colnames(x)}) and 'graphID' is any ID that
represents the nodes in the diffusionKernel (i.e.
\code{colnames(diffusionKernel)} or
\code{rownames(diffusionKernel)}). The purpose of the
this mapping is that a gene or protein in the network
might be represented by more than one probe set on the
chip. Therefore, the algorithm must know which
genes/protein in the network belongs to which probeset on
the chip.
}
\examples{
\dontrun{
library(Biobase)
data(sample.ExpressionSet)
x <- t(exprs(sample.ExpressionSet))
y <- factor(pData(sample.ExpressionSet)$sex)
# create the mapping
library('hgu95av2.db')
mapped.probes <- mappedkeys(hgu95av2REFSEQ)
refseq <- as.list(hgu95av2REFSEQ[mapped.probes])
times <- sapply(refseq, length)
mapping <- data.frame(probesetID=rep(names(refseq), times=times), graphID=unlist(refseq),
row.names=NULL, stringsAsFactors=FALSE)
mapping <- unique(mapping)
library(pathClass)
data(adjacency.matrix)
matched <- matchMatrices(x=x, adjacency=adjacency.matrix, mapping=mapping)
ad.list <- as.adjacencyList(matched$adjacency)
res.nBSVM <- crossval(matched$x, y, theta.fit=fit.networkBasedSVM, folds=3, repeats=1, DEBUG=TRUE,
parallel=FALSE, adjacencyList=ad.list, lambdas=10^(-1:2), sd.cutoff=50)
}
}
\author{
Marc Johannes \email{JohannesMarc@gmail.com}
}
\references{
Zhu Y. et al. (2009). Network-based support vector
machine for classification of microarray samples.
\emph{BMC Bioinformatics}
}
|
610736fc938d2c806a54458693dc841c9f4c6de6
|
73b297f2e53e18fc7a3d52de4658fede00a0319c
|
/man/orderArray.Rd
|
54a894c1a26fe84827bf097180197b5f186d5021
|
[
"MIT"
] |
permissive
|
bentyeh/r_bentyeh
|
4f5d0f403dceffb450bd77d8ff87adcaa6c222da
|
971c63f4ec1486366e0fe07fc705c0589ac7ea39
|
refs/heads/master
| 2023-02-06T19:10:18.055017
| 2020-07-21T18:18:48
| 2020-07-21T18:18:48
| 281,471,203
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 1,713
|
rd
|
orderArray.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utils.R
\name{orderArray}
\alias{orderArray}
\title{Order each dimension of array by hierarchical clustering.}
\usage{
orderArray(
ar,
dims = NULL,
metric = "cor",
method = "complete",
cor_use = "pairwise.complete.obs",
cor_method = "pearson",
return_hclust = FALSE
)
}
\arguments{
\item{ar}{\code{array}.}
\item{dims}{\code{vector, integer}. Dimensions to order. If NULL, all dims are ordered.}
\item{metric}{\code{character}. Distance metric by which to compare hyperplanes along dimension.
Hyperplanes are flattened into vectors for comparison. Support \code{"cor"} ((1 - r) / 2) or
any \link[stats]{dist} method.}
\item{method}{\code{character}. Any \link[stats]{hclust} agglomeration method.}
\item{cor_use}{\code{character}. Only applicable if \code{metric = "cor"}. \code{use} argument of
\link[stats]{cor}.}
\item{cor_method}{\code{character}. Only applicable if \code{metric = "cor"}. \code{method}
argument of \link[stats]{cor}.}
\item{return_hclust}{\code{logical}. Return list of hclust objects for ordered dimensions.}
}
\value{
\code{list. length = length(dim(ar))}. \itemize{
\item If \code{return_hclust = FALSE}: Each element is a vector giving the permutation of the
corresponding array dimension.
\item If \code{return_hclust = TRUE}: Each element is an \code{hclust} object for the
corresponding dimension, or NULL if that dimension was not ordered.
}
}
\description{
Order each dimension of array by hierarchical clustering.
}
\examples{
ar <- matrix(c(1, 1, 1, 2, 2, 2, 3, 4, 5), nrow = 3)
orderArray(ar)
}
\seealso{
\link[stats]{cor}, \link[stats]{dist}, \link[stats]{hclust}.
}
|
46dfa717567e4e9f7e3e1bb62e36ca8137ad9773
|
3fc12685acd8034eea0a08d946f49efb746fcf88
|
/man/get_significant_results.Rd
|
eccf3902bf0f5b3a9e6ebbcd2515e8b01e169f9f
|
[
"BSD-3-Clause"
] |
permissive
|
surbut/mashr
|
16eb64d685085409aeba5785a65d0384d6843ea6
|
b66d2af16503bc46d785ac9c9ba447ecc29b6fae
|
refs/heads/master
| 2020-04-08T03:15:53.456268
| 2018-11-24T20:04:50
| 2018-11-24T20:04:50
| 158,968,895
| 0
| 0
|
BSD-3-Clause
| 2018-11-24T19:54:17
| 2018-11-24T19:54:17
| null |
UTF-8
|
R
| false
| true
| 902
|
rd
|
get_significant_results.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/get_functions.R
\name{get_significant_results}
\alias{get_significant_results}
\title{Find effects that are significant in at least one condition}
\usage{
get_significant_results(m, thresh = 0.05, conditions = NULL,
sig_fn = get_lfsr)
}
\arguments{
\item{m}{the mash result (from joint or 1by1 analysis)}
\item{thresh}{indicates the threshold below which to call signals significant}
\item{conditions}{which conditions to include in check (default to all)}
\item{sig_fn}{the significance function used to extract significance from mash object; eg could be ashr::get_lfsr or ashr::get_lfdr. (Small values must indicate significant.)}
}
\value{
a vector containing the indices of the significant effects, by order of most significant to least
}
\description{
Find effects that are significant in at least one condition
}
|
e0d05d82ef2c24b16488aee46718f09232d86e27
|
266a322b66eddc97c035753a27fa2e95d9b6dc6d
|
/Part3/home_prac.R
|
914cdd4c310bd3155bc1fd34d813d753927e61d5
|
[] |
no_license
|
duamkr/R-program
|
b42894eb81024d40dcab6c870dc64ebbaf219638
|
e88fd69a58cf9efd58b9b097f81d786981284c5a
|
refs/heads/master
| 2020-05-29T13:39:21.242384
| 2019-06-18T08:47:43
| 2019-06-18T08:47:43
| 189,168,744
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,081
|
r
|
home_prac.R
|
setwd("E:/workspace/R/R-program/Part3/data")
getwd()
# λ³μμ λ°μ΄ν° λ΄κΈ°
aaa1 <- 'aaa' #'aaa'μ λ¬Έμμ΄ λ° 111μ μ«μννμ κ°λ λ³μ μ
λ ₯ κ°λ₯
aaa2 <- 111 # λ³μμ κ° μ§μ λͺ
λ Ήμ΄λ λ³μ <- κ° μ΄μ§λ§, κ° -> λ³μλ κ°λ₯
# Sequence_μ°μλ μ«μμ κ°μ λμ΄
seq(1:9)
seq(from='1',to='99',by=1) # 1-99κΉμ§ 1κ° μ¦κ° μΆλ ₯
seq(from=as.Date('2019-05-30') # by=1 μ§μ 1μΌμ© μ¦κ° μΆλ ₯
,to=as.Date('2019-06-06'),by=1)
seq(from=as.Date('2019-05-30') # by='month' μ§μ 1λ¬μ© μ¦κ° μΆλ ₯
,to=as.Date('2020-06-06'),by='month')
seq(from=as.Date('2019-05-30') # by='year' μ§μ 1λ
μ© μ¦κ° μΆλ ₯
,to=as.Date('2025-06-06'),by='years')
seq(from='1',to=50,by=3) # μΌμ λ²μ κ° 3μ© μ¦κ° μΆλ ₯
# Objects()_μ¬μ©μκ° μ§μ ν λ³μλ₯Ό νμΈ κ°λ₯
objects()
# rm()_ μ§μ ν λ³μ μμ
rm(aaa1) # aaa1μΌλ‘ μ§μ λ λ³μκ° μμ λ¨
.hidden <- 'abc' # λ³μλͺ
μμ . μ΄ λΆμΌλ©΄ μ¨κΉ λ³μ , μ¨κΈ΄λ³μλ rm()μΌλ‘ μμ λΆκ°λ₯
ls()
|
4172745bab9f300db1ed084f00e1a6710709bedf
|
bb310e92f81d1ef05d7b74fff808060fb7d7eeec
|
/R/zzz.R
|
e1c057cafc76aaa5e8e972936d32375ca9cfda5f
|
[] |
no_license
|
DarwinAwardWinner/rctutils
|
21646b4d2c5ec771250d78a23fcb82b6d70933a8
|
b7747eb50a42c9f48aecbf052c53a8cd42995031
|
refs/heads/master
| 2022-07-26T13:56:25.549006
| 2022-07-20T14:51:57
| 2022-07-20T14:51:57
| 130,285,249
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,803
|
r
|
zzz.R
|
#' Shortcut for the usual "requireNamespace" dance
#'
#' This shortens the boilerplate required to use functios from a
#' suggested package.
#'
#' @param ... Packages to require
#' @param caller The name of the function this was called from. Only
#' used to create an appropriate error message.
req_ns <- function(..., caller = as.character(sys.call(-1)[1])) {
for (pkg in unlist(list(...))) {
if (!requireNamespace(pkg, quietly = TRUE)) {
if (length(caller) != 1 || is.na(caller)) {
caller <- "this function"
} else {
caller <- str_c(caller, "()")
}
stop(sprintf("Package '%s' must be installed to use %s", pkg, caller), call. = FALSE)
}
}
}
## Tell "R CMD check" not to worry about the magrittr pronoun
utils::globalVariables(".")
## Tell check not to worry about rex internal functions
globalVariables(c("one_or_more", "space", "zero_or_more", "capture", "maybe", "digit", "%if_prev_is%", "%if_next_isnt%", "or"))
#' Common imports
#'
#' This is just here to tell roxygen2 about all base package imports,
#' which were recommended by R CMD check, as well as some common
#' imports that are used in many functions. Adding these to every
#' individual function that uses these common functions is too
#' tedious, so I've just added them all here.
#'
#' @importFrom grDevices cairo_pdf dev.cur dev.list dev.off dev.set png
#' @importFrom graphics abline barplot lines par title
#' @importFrom methods as is new
#' @importFrom stats approx approxfun as.dist as.formula cmdscale end lowess model.matrix na.omit start
#' @importFrom utils read.csv read.table write.table
#' @import magrittr
#' @import dplyr
#' @import stringr
#' @import ggplot2
#' @importFrom assertthat assert_that
"_PACKAGE"
|
a7cde9a08058fb78f5c912c2bfb587dc2912559e
|
92f5eca955e8137e3688ca447a013589fb51945f
|
/Limits Determination Code Final.R
|
064103e56da92b7c6f290e9c1c4f3bce2500ba7a
|
[] |
no_license
|
OMRFJamesLab/Cytokine-Quality-Control
|
88d675675abe6934433803b60ecf9b71bf722488
|
62bee5a45c30a5d64909991b19c2fa882a92a1ff
|
refs/heads/master
| 2021-01-20T15:19:32.388226
| 2017-02-22T13:26:13
| 2017-02-22T13:26:13
| 82,806,880
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 33,008
|
r
|
Limits Determination Code Final.R
|
#Load drm package which is used for the 5-parameter logistic curve optimization
library(nCal)
library(vioplot)
library(gridExtra)
library(grid)
######################################################################################
####The functions used to build the bigger algorithm##################################
#Calculate coefficient of variation for each concentration/dosage
cov <- function(data, conc, mfi){
#Get the target variable to calculate %CV
target.no <- grep(colnames(data), pattern = conc)
mfi.index <- grep(colnames(data), pattern = mfi)
#Check to see if the other variable is a numeric or factor
check <- is.numeric(data[,target.no])
if (check == TRUE){
#If it was numeric find unique values
dose <- unique(data[,target.no])
} else {
#If it was factor find the unique levels
dose <- levels(data[,target.no])
}
#calculate each %CV for a concentration/dosage
nlvl <- length(x = dose)
#Declare the return matrix that contains the means, stdev, and %CV
ret <- data.frame(array(dim=c(nlvl,4)))
name <- colnames(data)[mfi.index]
colnames(ret) <- c("Conc", "mean", "stdev", "CV")
#Calculate the %CV
i = 1
for (i in 1:nlvl){
#put the dosage/concentration to the first column of return matrix
ret[i,1] <- dose[i]
#Grab the replicates for each dosage/concentration
replicates <- data[which(data[, target.no] == dose[i]), mfi.index]
replicates.val <- as.numeric(unlist(replicates))
#Calculate the mean and stdev and %CV
mean <- mean(replicates.val)
std <- sd(replicates.val)
cv <- std/mean*100
ret[i,c(2:4)] <- c(mean, std, cv)
}
#Return the matrix as function
return(ret)
}
#Function to prune the standard had too much variance, user-defined or algorithm picked
#data = data that used in the coev function, and coev = result from the coev function
#Limit = CV% allowed for each standards, for CAP 20% precision or CoV is standard limit
prune.stds.cv <- function(data, coev, limit=20){
#Get the average of the %CV of the standard, limit is not chosen
if (is.null(limit) == TRUE) {
mean.cv <- mean(coev$CV) + 3 * sd(coev$CV) #Find the outlier values for CoV based on the CV of MFI measured
} else {
mean.cv <- limit
}
#Get rid of the standard had %CV above the limit
outliers <- coev[which(coev$CV > mean.cv),1]
#Get the name of dosage/concentration from coev and find it in data
dosage <- grep(pattern = colnames(coev)[1], colnames(data))
#Eliminate all standards that had CV above the limit
if (length(outliers) == 0) {
data <- data
} else {
for (j in 1:length(outliers)){
data <- data[-which(data[,dosage] == outliers[j]),]
}
}
data <- data[which(data[, dosage] != 0), ]
data <- data[order(-data[,dosage]),]
return(data)
}
#Detect single replicates meaning only one standard sample was found
# Rufei's code
#singles <- function(list){
# uniques = unique(list)
# count = unlist(lapply(X = list, FUN = function(x) sum(list == x)))
# sin = cbind(uniques, count)
# singles.out = sin[sin[, "count"] == 1, "uniques"]
# return (singles.out)
#}
# Hua's code
singles <- function(list){
duplicates<-list[duplicated(list)]
singles.out<-list[!list %in% duplicates]
return (singles.out)
}
#Prune standards that are lower than LOD which is defined as LOD function
#If one of the duplicate of standards fall out of range, then all duplicates were eliminated
prune.stds.lod <- function(data, expected = "Conc", measured, lod, plate.id = "plate.id"){
exp.id = grep(pattern = expected, x = colnames(data))
mea.id = grep(pattern = measured, x = colnames(data))
#eliminate the samples below LOD
if (length(which(data[, mea.id] < lod)) == 0) {
data = data
} else {
data = data[-which(data[, mea.id] < lod), ]
}
#eliminate single standard replicate after prune
plates = unique(data[, plate.id])
output = data.frame()
for (i in 1:length(plates)){
temp = data[data[, plate.id] == plates[i], ]
list = temp[temp[, plate.id] == plates[i], exp.id]
single = singles(list = list)
if (length(single) == 0) {
temp = temp
} else {
single.index = unlist(lapply(X = single, FUN = function(x) grep(pattern = x, x = temp[, exp.id])))
temp = temp[-c(single.index), ]
}
output = rbind(output, temp)
}
return(output)
}
#This Function gets rid of the uneven standard ranges. So the most common range is preserved whereas
#the high ranges were eliminated
std.range <- function(data, x, y, group){
#Get the x, y, and group column number
if (is.numeric(x) == TRUE) {
n.x <- x
} else { n.x <- grep(pattern = x, x = colnames(data))}
if (is.numeric(y) == TRUE) {
n.y <- y
} else { n.y <- grep(pattern = y, x = colnames(data))}
if (is.numeric(group) == TRUE) {
group <- group
} else { group <- grep(pattern = group, x = colnames(data))}
plate.id <- unique(data[, group])
hi <- array(dim = c(length(plate.id), 2))
for (i in 1:length(plate.id)){
hi[i, 1] <- plate.id[i]
hi[i, 2] <- max(data[which(data[, group] == plate.id[i]), n.x])
}
ret <- data.frame()
cutoff <- min(hi[,2]) * 1.5
for (i in 1:length(plate.id)){
std.temp <- data[which(data[, group] == plate.id[i] & data[, n.x] < cutoff),]
ret <- rbind(ret, std.temp)
}
return(ret)
}
#Calculating LOB, according to CAP LOB = mean(blanks) + 1.645 * sd(blanks)
LOB.single <- function(blanks, n = 1.645){
mean.blanks = mean(blanks) #Average of blanks, the blank sample across plates can be used here
sd.blanks = sd(blanks) #Standard deviation of blanks
LOB = mean.blanks + (n * sd.blanks) #LOB based on CAP definition, it's 1.645*SD
return(c(blanks.ave = mean.blanks, blanks.sd = sd.blanks, LOB = LOB))
}
#Calculate LOB across plates
# Rufei's Code
#LOB.acrossplates <- function(data, id, assay, blank.pattern = "Blank.*$"){
#Hua's Code
LOB.acrossplates <- function(data, id, assay, blank.pattern){
blanks.rowindex <- grep(pattern = blank.pattern, x = data[,id])
assay.colindex <- grep(pattern = assay, x = colnames(data))
blanks = na.omit(data[blanks.rowindex, assay])
LOB = LOB.single(blanks = blanks)
return(LOB)
}
#Extract standards for each assay for each plate or all, can be used to extract measure and expected
#from its perspective file
stds.extract <- function(data, id, assay, std = "Std", plate.id = NULL, plate.name = NULL) {
pattern.std = paste0(std, ".*$")
id.index = grep(pattern = id, x = colnames(data))
plateid.colindex= grep(pattern = "plate.id", x = colnames(data))
stds.index = grep(pattern = pattern.std, x = data[, id])
assay.colindex = grep(pattern = assay, x = colnames(data))
stds = data[stds.index, c(id.index, assay.colindex, plateid.colindex)]
if (is.null(plate.id) == FALSE){
plateid.index = grep(pattern = plate.id, x = stds[, "plate.id"])
stds = stds[plateid.index, ]
}
if (is.null(plate.name) == FALSE){
stds = stds[stds[, "plate.id"] == plate.name, ]
}
return(stds)
}
#Combine expected and known values in one file
StandardCurve.file <- function(data.master, id, assay, std = "Std", platenames){
combined.master = data.frame()
master = data.frame()
for (i in 1:length(platenames)){
#extract individual plate measured and expected values
measured = stds.extract(data = data.frame(data.master[[1]]), id = id, std = std, assay = assay, plate.name = platenames[i])
expected = stds.extract(data = data.frame(data.master[[2]]), id = id, std = std, assay = assay, plate.name = platenames[i])
combined.master = measured
Conc = c(1:nrow(combined.master))
combined.master = cbind(combined.master, Conc)
for (j in 1:nrow(combined.master)){
combined.master[j, "Conc"] = expected[c(expected[, id] == as.character(combined.master[j, id])), assay]
}
master = rbind(master, combined.master)
}
return(master)
}
#Determine LOD based on CAP approved method which is LOB + 1.645 * sd(low concentration samples)
LOD.cal <- function(std.files, expected = "Conc", measured, LOB, sd.blank = "yes"){
exp.id = grep(pattern = expected, x = colnames(std.files))
mea.id = grep(pattern = measured, x = colnames(std.files))
expected.min = min(std.files[, exp.id])
lowConc = std.files[c(std.files[, exp.id] == expected.min), mea.id]
if (sd.blank == "yes") {
LOD = LOB[[3]] + 1.645 * LOB[[2]]
} else {
LOD = LOB[[3]] + 1.645 * sd(lowConc)
}
return(c(LOD = LOD, LowConc.sd = sd(lowConc)))
}
#Combine expected known standards with measured MFI from those known values
stdCurve <- function(stdCurve.mod){
colnames(stdCurve.mod)[2] = "MFI"
colnames(stdCurve.mod)[4] = "Conc"
colnames(stdCurve.mod)[3] = "Plateid"
stdCurve.mod = data.frame(stdCurve.mod)
stdCurve.mod[, "MFI"] = log10(stdCurve.mod[, "MFI"])
stdCurve.mod[, "Conc"] = log10(stdCurve.mod[, "Conc"])
model<-drm(MFI~Conc, data=stdCurve.mod, curveid = stdCurve.mod[, "Plateid"], fct=LL.5(), type="continuous", robust="mean", logDose = 10)
return(model)
}
#Method 1 of LOQ, whihc is Signal to Noise ratio of 10, which means LOQ = LOB + 10 * sd(blanks)
LOQ.1 <- function(LOB, LOD){
LOQ = LOB[3] + 10 * LOD[2]
return(LOQ)
}
#Method 2 of LOQ, which is LOQ = LOD + 1.645 * sd(low conc)
LOQ.2 <- function(LOD){
LOQ = LOD[1] + 1.645 * LOD[2]
return(LOQ)
}
#A specific function to extract the IDs from the columan names
extract <- function (pattern, x){
ret <- sub(pattern, "\\1", x)
return(ret)
}
#Calculate the concentration of the assay based on the MFI
calculate.conc <- function(model, MFI, platename){
#Extract calculated parameter from the model
coefficients = model$coefficients
coeff.names = names(coefficients)
platename.index =c(grep(pattern = paste0(".*?",platename), coeff.names))
plate.coeff = coefficients[platename.index]
b = plate.coeff[1]
c = plate.coeff[2]
d = plate.coeff[3]
e = plate.coeff[4]
f = plate.coeff[5]
#Calculate the concentration based on the equation provided by the model
#f(x) = c + \frac{d-c}{(1+\exp(b(\log(x)-\log(e))))^f}
MFI.log = log10(MFI)
conc = exp((log(((d - c)/(MFI.log - c))^(1/f) - 1))/b)*e
return(conc)
}
#Calculate the MFI based on the 5-parameter logisitc curve
calculate.mfi <- function(b, c, d, e, f, Conc){
MFI = c + (d - c)/((1 + exp(b*log(Conc/e)))^f)
return(MFI)
}
#Calculate coefficient of variance
coev <- function(values){
coev = sd(values) / mean(values)
return(coev)
}
#Method 3 of LOQ, where CAP accept the <20% CV%
LOQ.3 <- function(stdsCurve.files, platenames, cv.limit = 0.2){
stdsCurve.files[, "calculated.conc"] = log10(stdsCurve.files[, "calculated.conc"])
#Calculate CV% for each unique expected concentration
exp.conc = unique(stdsCurve.files[, "Conc"])
CV = c(1:nrow(stdsCurve.files))
stdsCurve.files = cbind(stdsCurve.files, CV)
for (i in 1:length(exp.conc)){
cal.conc.temp = stdsCurve.files[stdsCurve.files[, "Conc"] == exp.conc[i], "calculated.conc"]
if (length(cal.conc.temp) > 2) {
cv = abs(sd(cal.conc.temp)/mean(cal.conc.temp)) #Calculate the CV%
stdsCurve.files[stdsCurve.files[, "Conc"] == exp.conc[i], "CV"] = round(cv, 4)
} else {
stdsCurve.files[stdsCurve.files[, "Conc"] == exp.conc[i], "CV"] = NA
}
}
#Determine the lowest expected concentration as LOQ
temp <- na.omit(stdsCurve.files)
temp = temp[temp[, "CV"] < cv.limit, ]
lloq = min(temp[, "Conc"])
uloq = max(temp[, "Conc"])
return(list(lloq, uloq, stdsCurve.files))
}
#Method 4 of LOQ, where LOQ is defined by an acceptable difference between groups, since the threshold is
#flexible, this can be adapted into any recursive analysis for downstream
LOQ.4 <- function(stdsCurve.files, model.l5, platenames, LOQ, a.2 = 1.645, b = 1.645, delta, n = 1){
Calculated.Conc = c(1:nrow(stdsCurve.files))
stdsCurve.files = cbind(stdsCurve.files, Calculated.Conc)
#Back calculate all concentration based on the 5-parameter logisitc curve
for (i in 1:length(platenames)){
stdCurve.temp = stdsCurve.files[stdsCurve.files$plate.id == platenames[i], 2]
stdCurve.conc = lapply(X = stdCurve.temp, FUN = function(x) calculate.conc(model = model.l5, platename = platenames[i], MFI = x))
stdCurve.conc = log10(unlist(stdCurve.conc))
names(stdCurve.conc) = NULL
stdsCurve.files[stdsCurve.files$plate.id == platenames[i], ncol(stdsCurve.files)] = stdCurve.conc
}
stdsCurve.files[, 5] = log10(stdsCurve.files[, 5])
stdsCurve.files[, 2] = log10(stdsCurve.files[, 2])
#Calculate CV% for each unique expected concentration
exp.conc = unique(stdsCurve.files[, 5])
CV = c(1:nrow(stdsCurve.files))
Accuracy = c(1:nrow(stdsCurve.files))
sd.conc = c(1:nrow(stdsCurve.files))
stdsCurve.files = cbind(stdsCurve.files, CV, Accuracy, sd.conc)
for (i in 1:length(exp.conc)){
cal.conc.temp = stdsCurve.files[stdsCurve.files[, 5] == exp.conc[i], "Calculated.Conc"]
cv = abs(coev(values = cal.conc.temp)) #Calculate the CV%
stdsCurve.files[stdsCurve.files[, 5] == exp.conc[i], "CV"] = cv
accu = abs(sd(cal.conc.temp)/exp.conc[i]) #Accuracy based on sd(calculated concentrations)/expected values
stdsCurve.files[stdsCurve.files[, 5] == exp.conc[i], "Accuracy"] = accu
sd.conc = sd(cal.conc.temp) #Accuracy based on sd(calculated concentrations)/expected values
stdsCurve.files[stdsCurve.files[, 5] == exp.conc[i], "sd.conc"] = sd.conc
}
#Determine the lowest expected concentration as LOQ
sigma = sqrt(n)*delta/(sqrt(2)*((a.2 + b)^2))
min.temp = na.omit(stdsCurve.files[stdsCurve.files[, "CV"] < sigma, ])
min.temp = min.temp[min.temp[, 2] > log10(LOQ), ]
LOQ.exp.conc = min(min.temp[, 5])
return(c(LOQ.exp.conc, stdsCurve.files))
}
#This function is used to read in all the data in to one single file with sample MFI and expected concentrations based on assay
#Directory = directory all the raw files are stored in
#filepattern.samples = a particular pattern that sample files are stored in, for examples: if all files of samples are stored as "Study 1 FI.csv", "Study 2 FI.csv" ... then pattern is "xxx FI.csv", where xxx stands for wild cards
#filepattern.knownValues = a particular pattern that known values or expected values files are stored in,
#for examples: if all files of samples are stored as "Study 1 Expected Conc.csv", "Study 2 Expected Conc.csv" ... then pattern is "xxx FI.csv", where xxx stands for wild cards
read.to.masterfile <- function(dir, filepattern.samples, filepattern.knownValues){
setwd(dir) #Set the working directory
filenames <- dir(dir) #Grab the file names of ALL files in the folder or directory
pattern.samples <- paste0(sub("(.*?)xxx(.*?)$", "\\1", filepattern.samples),"(.*?)",
sub("(.*?)xxx(.*?)$", "\\2", filepattern.samples),"$") #Change the pattern in to R code command, e.g. "(.*?) FI.csv$"
pattern.knownValues <- paste0(sub("(.*?)xxx(.*?)$", "\\1", filepattern.knownValues),"(.*?)",
sub("(.*?)xxx(.*?)$", "\\2", filepattern.knownValues),"$") #Change the pattern in to R code command, e.g. "(.*?) Expected Values.csv$"
samples <- grep(pattern = pattern.samples, filenames) #get sample files indexes can be converted to filenames later
knownValues <- grep(pattern = pattern.knownValues, filenames) #get known value files indexes and can be converted to filenames later
platenames <- sapply(X = filenames[samples], FUN = extract, pattern = pattern.samples) #Extract plate names as it appears in the directory, e.g. "Study 1 FI.csv", would be extracted as "Study 1" as plate 1 name
masterfile.samples <- data.frame() #declare master file to store all sample data in
masterfile.knownValues <- data.frame() #declare master file to store all known values in
#Loop to combine all sample files into a masterfile to be used later for calculation
for (i in 1:length(samples)){
tempfile.samples <- read.table(file = filenames[samples[i]], header = T, sep = ",") #Extract in to a temp file to be combined into master file
plate.id = rep(platenames[i], nrow(tempfile.samples))
tempfile.samples <- cbind(tempfile.samples, plate.id)
masterfile.samples <- data.frame(rbind(masterfile.samples, tempfile.samples)) #Loop to combine all files
}
rm(tempfile.samples) #Clear the memory
#Loop to combine all known values files into a masterfile to be used later for calculation
for (i in 1:length(knownValues)){
tempfile.knownValues <- read.table(file = filenames[knownValues[i]], header = T, sep = ",") #Extract in to a temp file to be combined into master file
plate.id = rep(platenames[i], nrow(tempfile.knownValues))
tempfile.knownValues <- cbind(tempfile.knownValues, plate.id)
masterfile.knownValues <- data.frame(rbind(masterfile.knownValues, tempfile.knownValues)) #Loop to combine all files
}
rm(tempfile.knownValues) #Clear the memory
return(list(masterfile.samples, masterfile.knownValues, platenames))
}
#Main function to do that pre-stat QC
#filepattern.samples = "xxx FI.csv"
#filepattern.knownValues = "xxx Expected Conc.csv"
#sampleid = "Barcode"
#dir = "/Users/rufeilu/Desktop/OMRF Analysis/BOLD cytokine data/Combined/Plate A"
#pattern.s = "Std"
#pattern.blank = "Blank.*$"
# Rufei's code
# pre.analysis.qc <- function(filepattern.samples, filepattern.knownValues, dir, sampleid, pattern.s, pattern.blank, no.lob.limit = "yes", lob = "yes"){
# Hua's code
pre.analysis.qc <- function(filepattern.samples, filepattern.knownValues, dir, sampleid, pattern.s, pattern.blank, no.lob.limit = "yes", lob = "yes", blank.pattern, control.pattern){
files <- read.to.masterfile(dir = dir, filepattern.samples = filepattern.samples, filepattern.knownValues = filepattern.knownValues)
#turn all variable into numeric
temp <- files[[1]][, c(2:(ncol(files[[1]])-1))]
files[[1]][, c(2:(ncol(files[[1]])-1))] <- apply(X = temp, MARGIN = 2, function(x) as.numeric(as.character(x)))
temp <- data.frame(files[[2]][, (2:(ncol(files[[1]])-1))])
files[[2]][, c(2:(ncol(files[[2]])-1))] <- apply(X = temp, MARGIN = 2, function(x) as.numeric(as.character(x)))
#####Use method 3 of LOQ, which is lowest concentration < 20% CV%
platenames = files[[3]]
assay.names = colnames(files[[1]]) #Getting all assay names
assay.names = assay.names[-c(grep(pattern = sampleid, x = assay.names), grep(pattern = "plate.id", x = assay.names))] #Keep only assay names, but eliminate sample id and plate id columns
n.assay = length(assay.names)
#Keep just samples
# Rufei's code
# samples = files[[1]]
# samples.legacy = files[[1]] #keep original files for all MFI values.
# stds.n = grep(pattern = paste0(pattern.s, ".*$"), samples[, sampleid])
# samples = samples[-c(stds.n), ]
# conc.s = samples #Pass to be calculated
# conc.all = samples.legacy #pass to legacy
# Hua's code
#Keep just samples
samples = files[[1]]
samples.legacy = files[[1]]
stds.n = grep(pattern = paste0(pattern.s, ".*$"), samples[, sampleid])
blank.n = grep(pattern = paste0(blank.pattern, ".*$"), samples[, sampleid])
control.n = grep(pattern = paste0(control.pattern, ".*$"), samples[, sampleid])
samples = samples[-c(stds.n, blank.n, control.n), ]
conc.s = samples #Pass to be calculated
conc.all = samples.legacy #pass to legacy
#Generate blank QC report
dir.create(file.path(dir, "QC Output"), showWarnings = FALSE) #Create a directory for output
setwd(file.path(dir, "QC Output"))
QC.Steps = c("Step 1", "No. Stds > 20% CV", "No. Stds < LOD", "Step 2", "No. Stds outside of 80% to 120% accuracy",
"Problem Plates", "Step 3", "No. Samples outside of LOQ", "No. Samples < LOD")
table.report = data.frame(matrix(ncol = n.assay + 1, nrow = 9))
colnames(table.report) = c("QC Steps", assay.names)
table.report[, 1] = QC.Steps
pdfname = "QC plots.pdf"
pdf(file = pdfname, onefile = TRUE, paper = "letter", height = 12)
for (i in 1: n.assay){
assayid = assay.names[i]
#Determine the LOB
# Rufei's code
# LOB <- LOB.acrossplates(data = data.frame(files[1]), id = sampleid, assay = assayid, blank.pattern = pattern.blank) #Extract the LOB for each assay
#Hua's code
LOB <- LOB.acrossplates(data = data.frame(files[1]), id = sampleid, assay = assayid, blank.pattern = blank.pattern) #Extract the LOB for each assay
LOB.val = LOB[3]
#Get master standards file
master.stds <- StandardCurve.file(data.master = files, std = pattern.s, id = sampleid, assay = assayid, platenames = files[[3]])
no.start.stds = length(unique(master.stds[, sampleid]))
#Determine the LOD
LOD <- LOD.cal(std.files = master.stds, LOB = LOB, measured = assayid, expected = "Conc", sd.blank = "no")
if (lob == "yes"){
LOD.val = LOB.val
} else if (lob == "no"){
LOD.val = LOD[1]
}
master.stds.prune = data.frame()
if (no.lob.limit == "yes"){
master.stds.prune = master.stds #Default option to leave the below dectection low concentration in for curve estimate purposes, only use for bad curves
} else if (no.lob.limit == "no"){
master.stds.prune <- prune.stds.lod(data = master.stds, expected = "Conc", measured = assayid, lod = LOD.val) #Cleaner way of eliminate stds that are below the detection, but does eliminate a lot in some cytokines
}
#Estimate how many samples are below limit of blank or detection
n.sample = nrow(samples) #Estimate total sample size
n_lod = round(length(which(samples[, assayid] < LOD.val)) / n.sample, 3) #Estimate fraction of samples are below limit of blank or detection
samples[which(samples[, assayid] < LOD.val), assayid] = NA #Change one below LOB or LOD to NA so won't be calculated
conc.s[which(conc.s[, assayid] < LOD.val), assayid] = NA #Change one below LOB or LOD to NA so won't be calculated
table.report[9, i + 1] = n_lod
#Elminate stds with > 20% CV
no.cv.drop = NULL
no.lod.drop = NULL
master.stds.prune.2 = data.frame()
for (j in 1:length(platenames)){
plate.stds = master.stds.prune[master.stds.prune[, "plate.id"] == platenames[j], ]
cv <- cov(data = plate.stds, conc = "Conc", mfi = assayid) #Output matrix contains mean and %CV for each concentration
plate.stds.prune <- prune.stds.cv(data = plate.stds, coev = cv, limit = 20) #Eliminates %CV > 20%
lod.drop = round(((no.start.stds * 2) - nrow(plate.stds)) / (no.start.stds * 2), 4)
no.lod.drop = c(no.lod.drop, lod.drop)
drop = round((nrow(plate.stds) - nrow(plate.stds.prune)) / (no.start.stds * 2), digits = 2)
no.cv.drop = c(no.cv.drop, drop)
master.stds.prune.2 = rbind(master.stds.prune.2, plate.stds.prune)
}
table.report[2, i + 1] = paste0(no.cv.drop, collapse = ", ")
table.report[3, i + 1] = paste0(no.lod.drop, collapse = ", ")
#Eliminate stds fall outside of 80% to 120% range of accuracy
suppressWarnings(model <- stdCurve(master.stds.prune.2))
recovery = master.stds.prune.2 #Transfer over
calculated.conc = c(1:nrow(recovery))
accuracy = c(1:nrow(recovery))
recovery = cbind(recovery, calculated.conc, accuracy)
for (j in 1:length(platenames)){
plate = recovery[which(recovery[, "plate.id"] == platenames[j]), ]
mfi.rec = recovery[which(recovery[, "plate.id"] == platenames[j]), assayid]
suppressWarnings(
conc.rec <- unlist(lapply(X = mfi.rec, FUN = function(x) calculate.conc(model = model, MFI = x, platename = platenames[j])))
)
recovery[c(recovery[, "plate.id"] == platenames[j]), "calculated.conc"] = conc.rec
accuracy = abs((conc.rec - plate[, "Conc"]) / plate[, "Conc"])
plate[, "accuracy"] = accuracy
#stds.unique = unique(plate[, "Conc"])
#for (k in 1:length(stds.unique)){
# rec.ave = mean(plate[plate[, "Conc"] == stds.unique[k], "accuracy"])
# plate[plate[, "Conc"] == stds.unique[k], "accuracy"] = rec.ave
#}
recovery[c(recovery[, "plate.id"] == platenames[j]), "accuracy"] = plate[, "accuracy"]
}
#take the stds with average accuracy outside of the 80% to 120% range
master.stds.prune.3 = na.omit(recovery)
master.stds.prune.3 = master.stds.prune.3[master.stds.prune.3[, "accuracy"] < 0.2, ]
#Make sure the plate is not dropping out too many stds
no.drop.final = NULL
for (j in 1:length(platenames)){
plate = master.stds.prune.3[c(master.stds.prune.3[, "plate.id"] == platenames[j]), ]
no.drop.temp = 1 - round(length(unique(plate[, "Conc"])) / (no.start.stds), 2)
no.drop.final = c(no.drop.final, no.drop.temp)
}
table.report[5, i + 1] = paste0(no.drop.final, collapse = ", ")
#All the plate with > 60% drop rate
p = which(no.drop.final > 0.6)
problem = platenames[p]
table.report[6, i + 1] = paste0(problem, collapse = ", ")
#After pruning make the final model
model.final <- stdCurve(stdCurve.mod = master.stds.prune.3)
loq <- LOQ.3(stdsCurve.files = master.stds.prune.3, platenames = platenames, cv.limit = 0.2)
lloq = loq[[1]]
uloq = loq[[2]]
#Calculate concentration based on each plates standard curves
for (j in 1:length(platenames)){
samples.assay = conc.s[c(conc.s[, "plate.id"] == platenames[j]), assayid]
samples.legacy.assy = conc.all[c(conc.all[, "plate.id"] == platenames[j]), assayid]
suppressWarnings(
sample.concs <- unlist(lapply(X = samples.assay, FUN = function(x) calculate.conc(model = model.final, MFI = x, platename = platenames[j])))
)
suppressWarnings(
sample.concs.all <- unlist(lapply(X = samples.legacy.assy, FUN = function(x) calculate.conc(model = model.final, MFI = x, platename = platenames[j])))
)
conc.s[which(conc.s[, "plate.id"] == platenames[j]), assayid] = sample.concs
conc.all[which(conc.all[, "plate.id"] == platenames[j]), assayid] = sample.concs.all
}
#Calculate how many sample fall outside of 80% to 120%
n.low = length(which(conc.s[, assayid] < lloq))
n.hi = length(which(conc.s[, assayid] > uloq))
n_loq = (n.low + n.hi) / n.sample
table.report[8, i + 1] = n_loq
conc.s[which(conc.s[, assayid] < lloq), assayid] = lloq
conc.s[which(conc.s[, assayid] > uloq), assayid] = uloq
#Set up plot panels
par(mfrow = c(2, 1))
#Dynamic range set by max and min of calculated concentration and expected concentration
y.max = log10(max(master.stds[, assayid]) * 1.4)
y.min = log10(min(master.stds[, assayid]) * 0.8)
x.max = log10(max(master.stds[, "Conc"]) * 1.4)
x.min = log10(min(master.stds[, "Conc"]) * 0.8)
col.pal <- rainbow(length(unique(platenames)))
plot(model.final, col=col.pal, xlab=paste("log10(", assayid, "Concentration)"),
ylab=paste("log10(", assayid, ")MFI"), type="all", xlim = c(x.min, x.max), ylim = c(y.min, y.max))
#graph points below the detection
graph.below.lod <- na.omit(data.frame(Conc = log10(conc.all[, assayid]), MFI = log10(samples.legacy[, assayid]), plate.id = conc.all[, "plate.id"]))
graph.below.lod <- graph.below.lod[which(graph.below.lod$MFI < log10(LOD.val)), ]
points(x = graph.below.lod[, 1], y = graph.below.lod[, 2], cex = 1, pch = 16, col="black")
#Plot points calucated based on 5-parameter logitis curve
graph = na.omit(data.frame(Conc = log10(conc.s[, assayid]), MFI = log10(samples[, assayid]), plate.id = conc.s[, "plate.id"]))
col.pt <- col.pal[c(as.numeric(graph[, "plate.id"]))] #Set same colors as the standard curves
points(x = graph[, 1], y = graph[, 2], cex = 1, pch = 16, col=col.pt)
#Calculate LLOQ for LOD for each plate
lloq.at.lod = NULL
for (k in platenames){
suppressWarnings(
lloq.cal <- calculate.conc(model = model.final, MFI = LOD.val, platename = k)
)
lloq.at.lod <- c(lloq.at.lod, lloq.cal)
}
lloq.graph <- min(lloq.at.lod)
abline(v = log10(lloq), col="green", lwd = 2, lty = 2)
text(log10(lloq), 2, "LLOQ", adj = c(0,0))
abline(v = log10(uloq), col="green", lwd = 2, lty = 2)
text(log10(uloq), 2, "ULOQ", adj = c(0,0))
abline(h = log10(LOD.val), col = "red", lwd = 1, lty = 2)
text(log10(lloq.graph), log10(LOD.val), "LOD", adj = c(0,0))
abline(h = log10(LOB[1]), col = "red", lwd = 1.2, lty = 1)
#text(log10(lloq.graph), log10(LOB[1]), "Blank Average", adj = c(0,0))
mtext(text = paste0(n_lod*100, "% below LOD"), side = 3)
#Generate violin plot for each plate
if (length(na.omit(log10(conc.s[, assayid]))) == 0){
range = c(0, 1)
} else {
range = range(na.omit(log10(conc.s[, assayid])))
}
plot(1, 1, xlim = c(0, length(platenames) + 1), ylim = range, xlab = "", ylab = paste0("log10(", assayid, ")"), xaxt = 'n', type = 'n')
for (k in 1:length(platenames)){
name = platenames[k]
x = na.omit(log10(conc.s[which(conc.s[, "plate.id"] == name), assayid]))
if (length(x) == 0) {
k = k + 1
} else {
vioplot(x, names = name, add = T, at = k, col = col.pal[k])
label = paste0(name, " (n=", length(x), ")")
axis(1, at = k, labels = label, las = 2, cex.axis = 0.6)
}
}
#Output progress
print(paste0(signif(i/n.assay*100, digits = 4),"% Complete!"))
}
graphics.off()
write.table(x = table.report, file = "QC Step by Step Report.csv", sep = ",", na = "", row.names = FALSE)
pdf(file = "QC Undetected Rate.pdf", onefile = T, paper = "letter", height = 10)
#display the bar plot with missing rates
par(mfrow = c(1,1))
x = as.numeric(table.report[9,-1])*100
col = rep(x = "green", length(x))
col[which(x > 70)] <- "red"
legend <- c(paste0("N of passed = ", sum(x<70)),
paste0("N of failed = ", sum(x>70)))
barplot(height = x, names.arg = colnames(table.report)[-1], cex.names = 0.7, las = 2, main = "Percentage below LOD",
ylab = "% Undetected", col = col)
legend("topright", legend = legend, fill = c("green", "red"))
abline(h = 60, col = "orange")
abline(h = 70, col = "red", lwd = 2)
#automatically generate QC report for each analyte
for (p in colnames(table.report)[-1]){
#Step 1
step.1 <- table.report[c(2:3), c("QC Steps", p)]
step.1.table <- data.frame(matrix(0, nrow = 2, ncol = (length(platenames) + 1)))
colnames(step.1.table) <- c("Std QC Step", platenames)
step.1.table[1, ] <- unlist(c(step.1[1, 1], strsplit(step.1[1, 2], split = ",")))
step.1.table[2, ] <- unlist(c(step.1[2, 1], strsplit(step.1[2, 2], split = ",")))
theme <- ttheme_default(base_size = 10)
step.1.grid <- tableGrob(step.1.table, rows = NULL, cols = gsub("\\ ", "\\\n", colnames(step.1.table)), theme = theme)
#Step 2
step.2 <- table.report[c(5:6), c("QC Steps", p)]
step.2.table <- data.frame(matrix(0, nrow = 1, ncol = (length(platenames) + 1)))
colnames(step.2.table) <- c("Accuracy QC Step", platenames)
step.2.table[1, ] <- unlist(c(step.2[1, 1], strsplit(step.2[1, 2], split = ",")))
step.2.grid <- tableGrob(step.2.table, rows = NULL, cols = gsub("\\ ", "\\\n", colnames(step.2.table)), theme = theme)
#Step 3
step.3 <- table.report[c(8:9), c("QC Steps", p)]
step.3[, 2] <- signif(as.numeric(step.3[, 2]), 3)
step.3.grid <- tableGrob(step.3, rows = NULL, theme = theme)
grid.arrange(step.1.grid, step.2.grid, step.3.grid, newpage = T, nrow = 3, top = p)
}
graphics.off()
write.table(x = conc.s, file = "Calculated Concentration.csv", sep = ",", na = "", row.names = FALSE)
}
######################################################################################
#filepattern.samples = "xxx FI.csv"
#filepattern.knownValues = "xxx Expected Conc.csv"
#dir <- "/Users/Rufei/Desktop/OMRF Analysis/OLC 200"
#sampleid = "Barcode"
#pattern.s = "Std"
#pre.analysis.qc(filepattern.samples = "xxx FI.csv", filepattern.knownValues = "xxx Expected Conc.csv", dir = "/Users/rufeilu/Desktop/OMRF Analysis/OLC 200", sampleid = "Barcode", pattern.s = "Std", pattern.blank = "Blank.*$", lob = "yes")
|
9b1acba2870e25f39c1df71cfc7fecaa0599718b
|
77adeb996aa86cf4c27c51fd2eb66a17adaa95e1
|
/2018 - 01/03. μκ³μ΄λΆμ/2018-06-05 μμ
(1).R
|
688565295570888f21622ec0c882929d7bb5f64e
|
[] |
no_license
|
ajskdlf64/Bachelor-of-Statistics
|
44e5b5953ac0c17406bfc45dd868efbfab18e70f
|
bc7f92fce9977c74c09d4efb0ead35e2cd38e843
|
refs/heads/master
| 2021-07-20T00:22:26.981721
| 2021-07-14T08:47:43
| 2021-07-14T08:47:43
| 220,665,955
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,324
|
r
|
2018-06-05 μμ
(1).R
|
# κ³μ μΆμΈ + ARMA μ€μ°¨ νκ· λͺ¨ν.
library(forecast)
# μλ£ λΆλ¬μ€κΈ°.
tourist <- scan("C:/Users/user/Desktop/νκ΅μμ
/μκ³μ΄λΆμ/μμ
μλ£/tourist.txt")
tourist.ts <- ts(tourist, start = c(1981), frequency = 12)
tour92 <- scan("C:/Users/user/Desktop/νκ΅μμ
/μκ³μ΄λΆμ/μμ
μλ£/tourist.txt")
tour92.ts <- ts(tourist, start = c(1982), frequency = 12)
plot(tourist.ts, ylab = "κ΄κ΄κ°")
# λΆμ°μμ νλ₯Ό μν λ‘κ·Έ λ³ν.
lntourist <- log(tourist.ts)
plot(lntourist, ylab = "κ΄κ΄κ°")
# μκ°(t) λ³μ μμ± λ° λ³μ(D) μμ±.
Time <- time(lntourist)
Month <- cycle(lntourist)
# κ³μ μΆμΈλͺ¨ν μ ν©.
fit <- lm(lntourist ~ Time + factor(Month) + 0) # +0 νλ μ΄μ : μ νΈ μ κ±°. 2μ°¨ λͺ¨νμ ν΄λ³΄κ³ λμ΄κ° νμλ μμ.
# μ ν© κ²°κ³Ό νμΈ.
summary(fit)
# μμ°¨λΆμ.
checkresiduals(fit)
# μ€μ°¨κ° λ
λ¦½μ΄ μλ.
# μ€μ°¨μ λν λͺ¨νμ΄ νμν¨. μ€μ°¨ λͺ¨ν : ARMA(p,q)
# μ€μ°¨ λͺ¨ν λ¨κ³
# 1. λͺ¨ν μλ³.
# 2, λͺ¨ν μΆμ .
# 3. λͺ¨ν μ§λ¨.
resid <- ts(fit$resid, start = 1981)
ggtsdisplay(resid,lag.max = 48)
# λͺ¨ν μλ³ : AR(3) λ‘ νλ¨.
fit1 <- arima(resid, order = c(3, 0, 0), include.mean = FALSE)
confint(fit1)
checkresiduals(fit1)
fit1_1 <- arima(resid, order = c(4, 0, 0), include.mean = FALSE)
confint(fit1_1)
checkresiduals(fit1_1) # μΆκ°λ λͺ¨μκ° λΉμ μμ .
fit1_2 <- arima(resid, order = c(3, 0, 1), include.mean = FALSE)
confint(fit1_2)
checkresiduals(fit1_1) # μΆκ°λ λͺ¨μκ° λΉμ μμ .
# AR(3) λ‘ μ μ κ²°μ .
# μΆμΈλͺ¨ν(fit1)μ AR(3) μ€μ°¨λͺ¨ν : λ λͺ¨νμ κ²°ν©.
fit_x <- model.matrix(fit)
fit2 <- Arima(tourist.ts, order = c(3, 0, 0), xreg = fit_x, include.mean = FALSE, lambda = 0)
confint(fit2) # λͺ¨μμ μ μμ± κ²μ .
summary(fit2)
coef(fit2)
# μλͺ»λ¨!!! λ
립μ±μ΄ μλ°!!!
# dfκ° νμ€μ΄λ€μ....p-κ°μ΄ μ μμ μ΄λΌκ³ λμ΄...
# μμ λκ° λ무 μμμ λ
립 κ°μ€μ κΈ°κ°ν κ²μΌλ‘ νλ¨.
checkresiduals(fit2)
# λͺ¨ν μμΈ‘.
new_t <- time(ts(start = c(1991, 1), end = c(1991, 12), freq = 12))
new_x <- cbind(new_t, diag(rep(1, 12)))
fore <- forecast(fit2, xreg = new_x)
accuracy(fore)
plot(fore)
lines(tour92,col='red')
# κ³μ ν ARIMA λͺ¨νκ³Ό λΉκ΅νλ©΄ μ’μ...
|
f5fda3daa59e90f1e2d38dc946f1f752d1d8c7b4
|
0054f25bd3fd82f8d8440de039cd589ca35e3168
|
/man/CoW.Rd
|
b5fe083cd2b791941478a28a1a93c60898e7f2d5
|
[] |
no_license
|
dncnbrn/EmsiAgnitio
|
6e3bcf0324fed7462be6e26a068e2efa424975e1
|
c4ef657605da55bcb3a8451e145b6ab00d788b5e
|
refs/heads/master
| 2023-03-31T01:06:15.421945
| 2021-03-24T18:27:51
| 2021-03-24T18:27:51
| 123,454,318
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 590
|
rd
|
CoW.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dimensions.R
\name{CoW}
\alias{CoW}
\title{A short-hand function to map UK ClassOfWorker dimensions around one of four options}
\usage{
CoW(option)
}
\arguments{
\item{option}{One of "E" (for Employee), "P" (for "Proprietor"), "A" (for "All" combined) or "S" (for
Employee and Proprietor separately.)}
}
\value{
The necessary mapping for ClassOfWorker for inclusion in a data pull query.
}
\description{
A short-hand function to map UK ClassOfWorker dimensions around one of four options
}
\examples{
CoW("E")
}
|
1d65c41c613806f70ca210df5060f0bfc14ccc46
|
8091ac441b2d468d9d9350ea299970aecf35e8e0
|
/R/AAProcess.R
|
af2ad51a8759afa0491384c273c77035cb833474
|
[] |
no_license
|
bchain/agilp
|
e56f993e3abafd05b0d047be6580431d03ae8352
|
645de2c648b1bf57e05a3b1b12f6d703f96b7f08
|
refs/heads/master
| 2016-09-10T22:04:06.529888
| 2015-04-17T04:40:46
| 2015-04-17T04:40:46
| 28,714,946
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,456
|
r
|
AAProcess.R
|
AAProcess<-function(input=file.path(system.file(package="agilp"),"input",""),output=file.path(system.file(package="agilp"),"output/",""),s=9){
#reads the input directory of file names into directory
directory<-unlist(dir(input))[]
M<-length(directory)
#read in first data set skipping first "s" rows
inputpath<-c(rep(1,M))
i<-1
for (i in 1:M)
{
inputpath[i]<-file.path(input,directory[i],fsep = .Platform$file.sep)
if(file.exists(inputpath[i])){
data<-read.table(inputpath[i],skip = s, header = FALSE, quote = "",comment.char = "", sep = "\t", fill = TRUE, stringsAsFactors=FALSE )
colnames(data) <- data[1,]
data<-data[-1,]
probenames <- data[,"ProbeName"]
probes<-levels(factor(probenames))
green<-tapply(as.numeric(data[,"gMedianSignal"]),probenames,mean)
rownames(green)<-probes
Rawdg<-paste(output,"gRaw_",directory[i],sep = "")
greencol<-paste("gRaw_",directory[i],sep = "")
write.table(green,Rawdg,sep="\t", col.names = greencol, row.names = probes)
###############################################################################
if (match(as.vector("rMedianSignal"),as.vector(colnames(data)),nomatch=0)>0) {
red<-tapply(as.numeric(data[,"rMedianSignal"]),probenames,mean)
rownames(red)<-probes
Rawdr<-paste(output,"rRaw_",directory[i],sep = "")
redcol<-paste("rRaw_",directory[i],sep = "")
write.table(red,Rawdr,sep="\t", col.names = redcol, row.names = probes)
}
}else message("Array ",inputpath[i], "is not present")
#end of for loop
}
}
|
15be10b2c071860232a5417788749086f817fa5c
|
dfd898b1ff366eac82cd5818ba5d6db4db5eb7b6
|
/Plot2.R
|
870952f2cae95e63adb2e03b764eaf4ee0e9df2f
|
[] |
no_license
|
cesar-arce/Exploratory-Data-Analysis-Week4
|
2a48e17560801ba827b1005652055a4b3388b833
|
9acde84361f4b0d60abd4261538e447900a0f561
|
refs/heads/master
| 2022-10-25T17:51:20.652641
| 2020-06-09T01:56:16
| 2020-06-09T01:56:16
| 270,876,540
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 668
|
r
|
Plot2.R
|
# Peer Graded Assignment: Exploratory Data Analysis Course Project 2 (week 4)
# forming Baltimore data which will be NEI_data subset
baltdata <- NEI[NEI$fips=="24510", ]
# Baltimore yearly emmisisons data
baltYrEmm <- aggregate(Emissions ~ year, baltdata, sum)
#### generates plot2.png
cols1 <- c("maroon", "yellow", "orange", "Aquamarine")
barplot(height=baltYrEmm$Emissions/1000,
names.arg=baltYrEmm$year,
xlab="Year",
ylab=expression('Aggregated Emission'),
main=expression('Baltimore Aggregated PM'[2.5]*' Emmissions by Year'), col = cols1)
# to generate file plot2.png
dev.copy(png, file="plot2.png", height=480)
dev.off()
|
880ddca0364cf02d41a6c7c25b20d9f63f924eb6
|
093c976951d69367db559b760ce14879b8874e1c
|
/code/p-spline-mixture-models/help-functions.R
|
7cc217c7ac281320f64050b39eccc350a9770b33
|
[] |
no_license
|
taylerablake/Dissertation
|
da87de83872e1eab54791598a78b4479e5594e7f
|
9dc0db00409777a9007afb42c18ed0ee9b94cdf8
|
refs/heads/master
| 2021-03-24T12:46:40.194419
| 2017-07-24T20:07:37
| 2017-07-24T20:07:37
| 65,043,074
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,822
|
r
|
help-functions.R
|
# Compute B-spline base matrix
bspline <- function(X., XL., XR., NDX., BDEG.) {
dx <- (XR. - XL.)/NDX.
knots <- seq(XL. - BDEG. * dx, XR. + BDEG. * dx, by = dx)
B <- spline.des(knots, X., BDEG. + 1, 0 * X.)$design
B
}
# row-tensor product (or Box product of two matrices)
rowtens <- function(X, B) {
one.1 <- matrix(1, 1, ncol(X))
one.2 <- matrix(1, 1, ncol(B))
kronecker(X, one.2) * kronecker(one.1, B)
}
# Mixed Model Basis
MM.basis <- function(x, xl, xr, ndx, bdeg, pord) {
B <- bspline(x, xl, xr, ndx, bdeg)
m <- ncol(B)
D <- diff(diag(m), differences = pord)
P.svd <- svd(t(D) %*% D)
U <- (P.svd$u)[, 1:(m - pord)]
d <- (P.svd$d)[1:(m - pord)]
Z <- B %*% U
X <- NULL
for (i in 0:(pord - 1)) {
X <- cbind(X, x^i)
}
list(X = X, Z = Z, d = d, B = B, m = m, D = D)
}
# Construct 2 x 2 block symmetric matrices:
construct.block2 <- function(A1, A2, A4) {
block <- rbind(cbind(A1, A2), cbind(t(A2), A4))
return(block)
}
# Interpolate on a 2d grid
Grid2d <- function(x1, x2, nseg1, nseg2, div, bdeg, pord, ngrid,
b) {
# Build Mixed Model Bases
MM1 <- MM.basis(x1, min(x1) - 0.01, max(x1) + 0.01, nseg1,
bdeg, pord) # bases for x1
X1 <- MM1$X
G1 <- MM1$Z
d1 <- MM1$d
B1 <- MM1$B
MM2 <- MM.basis(x2, min(x2) - 0.01, max(x2) + 0.01, nseg2,
bdeg, pord) # bases for x2
X2 <- MM2$X
G2 <- MM2$Z
d2 <- MM2$d
B2 <- MM2$B
MM1n <- MM.basis(x1, min(x1) - 0.01, max(x1) + 0.01, nseg1/div,
bdeg, pord) # Nested bases for x1
G1n <- MM1n$Z
d1n <- MM1n$d
B1n <- MM1n$B
MM2n <- MM.basis(x2, min(x2) - 0.01, max(x2) + 0.01, nseg2/div,
bdeg, pord) # Nested bases for x2
G2n <- MM2n$Z
d2n <- MM2n$d
B2n <- MM2n$B
c1 <- ncol(B1)
c2 <- ncol(B2)
c1n <- ncol(B1n)
c2n <- ncol(B2n)
one1. <- matrix(X1[, 1], ncol = 1)
one2. <- matrix(X2[, 1], ncol = 1)
x1. <- matrix(X1[, 2], ncol = 1)
x2. <- matrix(X2[, 2], ncol = 1)
#####################
X <- rowtens(X2, X1) # -> Fixed effects
#
d3 <- c(rep(1, c2n - pord) %x% d1n + d2n %x% rep(1, c1n -
pord))
Delta1 <- diag(1/sqrt(d1))
Delta2 <- diag(1/sqrt(d2))
Delta3 <- diag(1/sqrt(d3))
# random effects matrices
Z1 <- G1 %*% Delta1 # smooth random comp. fx1
Z2 <- G2 %*% Delta2 # smooth random comp. fx2
Z1x2 <- rowtens(x2., G1n) # linear:smooth comp. x2:fx1
Z2x1 <- rowtens(G2n, x1.) # linear:smooth comp. fx2:x1
Z12 <- rowtens(G2n, G1n) %*% Delta3 # smooth interaction fx1:fx2
#####################
# Random effects matrix
Z <- cbind(Z1, Z2, Z1x2, Z2x1, Z12)
M <- cbind(X, Z)
M
}
|
44d6dcce0ca2cf794e711c228e8b1ce31780d663
|
03bc16fe40ab567e3dde851f42c92cfd464a0dd5
|
/R/cleverR.R
|
bd7c3aa00db070368e4ce011a837911a0ad22337
|
[
"MIT"
] |
permissive
|
michael-andre-stevens/CleverR
|
f75e90654faaeebf8d81afcd6f70734b38fa9948
|
9336a37c4f9aca2e8d94ce03e2722f2c03e4da80
|
refs/heads/master
| 2020-07-03T23:57:27.738871
| 2020-01-07T12:47:20
| 2020-01-07T12:47:20
| 202,092,219
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 253
|
r
|
cleverR.R
|
#' cleverR: Functions For Clever Notebooks.
#'
#' The foo package provides three categories of important functions:
#' foo, bar and baz.
#'
#' @section cleverR functions:
#' The cleverR functions ...
#'
#' @docType package
#' @name cleverR
NULL
#> NULL
|
9794f5cddd1fcb8584e9e289ce6a3c60eadffb87
|
6d0f4cde529471472332a3eb65b2e74890bbe916
|
/MGLM/man/MGLMsparsereg-class.Rd
|
a317dea314663195e3772ee445ea6fa93098982d
|
[] |
no_license
|
Yiwen-Zhang/MGLM
|
f9717283c97302dc298960313fc6e6ce698bbbf7
|
1a86e4968c9708e99e143d9caf45f5cc0d0423a0
|
refs/heads/master
| 2021-01-10T21:59:21.657115
| 2016-02-28T18:17:48
| 2016-02-28T18:17:48
| 9,347,523
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,035
|
rd
|
MGLMsparsereg-class.Rd
|
\name{MGLMsparsereg-class}
\Rdversion{1.1}
\docType{class}
\alias{MGLMsparsereg-class}
\title{Class \code{"MGLMsparsereg"}}
\description{
A list containing the results from the \code{MGLMsparsereg}.
}
\section{Objects from the Class}{
Objects can be created by calls of the form \code{new("MGLMsparsereg", ...)}.
}
\section{Slots}{
\describe{
\item{\code{call}:}{Object of class \code{"function"}. }
\item{\code{data}:}{Object of class \code{"list"},
consists of both the predictor matrix and the response matrix}
\item{\code{coefficients}:}{Object of class \code{"matrix"},
the estimated regression coefficients.}
\item{\code{logL}:}{Object of class \code{"numeric"},
the loglikelihood. }
\item{\code{BIC}:}{Object of class \code{"numeric"},
Bayesian information criterion. }
\item{\code{AIC}:}{Object of class \code{"numeric"},
Akaike information criterion.}
\item{\code{Beta}:}{Object of class \code{"numeric"},
the over dispersion parameter of the negative multinomial regression.}
\item{\code{Dof}:}{Object of class \code{"numeric"},
the degrees of freedom.}
\item{\code{iter}:}{Object of class \code{"numeric"},
number of iterations used. }
\item{\code{maxlambda}:}{Object of class \code{"numeric"},
the maximum tuning parameter that ensures the estimated regression coefficients are not all zero.}
\item{\code{lambda}:}{Object of class \code{"numeric"},
the tuning parameter used. }
\item{\code{distribution}:}{Object of class \code{"character"},
the distribution fitted. }
\item{\code{penalty}:}{Object of class \code{"character"},
the chosen penalty when running penalized regression. }
}
}
\section{Methods}{
\describe{
\item{print}{\code{signature(x = "MGLMsparsereg")}:
print out sparse regression results from class \code{"MGLMsparsereg"}.}
}
}
\author{
Yiwen Zhang and Hua Zhou
}
%% ~Make other sections like Warning with \section{Warning }{....} ~
\examples{
showClass("MGLMsparsereg")
}
\keyword{classes}
|
492238ec7edef2173b441c3c99b5a81fa96324a6
|
2f94579f26bcbc190a21378221c55d205284e95f
|
/listings/ex-6.3.R
|
0cc98615766428b82b72e5e8f099560e081619c2
|
[] |
no_license
|
Fifis/ekonometrika-bakalavr
|
9fdf130d57446182fcf935e60d9276cc99d89c0e
|
c2d89a382d3eaf450a8f4f4dc73c77dd7c6eefd7
|
refs/heads/master
| 2021-01-20T20:42:12.937927
| 2016-07-23T17:14:35
| 2016-07-23T17:14:35
| 63,989,268
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 277
|
r
|
ex-6.3.R
|
set.seed(115)
n <- 100
x <- rexp(n)
log_ml <- function(lam, x) {
sum(-dexp(x, rate = lam, log = TRUE))
}
lam_start <- 1/mean(x)
res <- nlm(f=log_ml, p=lam_start, x = x)
res$estimate
res <- nlm(f=log_ml, p=lam_start, x = x, hessian=TRUE)
fisher <- res$hessian
solve(fisher)
|
b5a1028a2aa75d79d40a6cc678e65b1be56b7097
|
0a906cf8b1b7da2aea87de958e3662870df49727
|
/detectRUNS/inst/testfiles/genoConvertCpp/libFuzzer_genoConvertCpp/genoConvertCpp_valgrind_files/1609875429-test.R
|
0bbb1b8f36421d63476bb9d78410ed973b591d24
|
[] |
no_license
|
akhikolla/updated-only-Issues
|
a85c887f0e1aae8a8dc358717d55b21678d04660
|
7d74489dfc7ddfec3955ae7891f15e920cad2e0c
|
refs/heads/master
| 2023-04-13T08:22:15.699449
| 2021-04-21T16:25:35
| 2021-04-21T16:25:35
| 360,232,775
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 287
|
r
|
1609875429-test.R
|
testlist <- list(genotype = c(1684300900L, 1684300900L, 1684300900L, 1684300900L, 1684300900L, 1684301055L, -16777216L, 245L, 211L, NA, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L))
result <- do.call(detectRUNS:::genoConvertCpp,testlist)
str(result)
|
5d5739fc60be0bcd570caffef5da8243aad0e8be
|
c03b195fb958ca1cd8ce86782ff6c84af88cd25f
|
/R/segment.R
|
f9f7cd56e040791031fac0c8cc5db268755c7076
|
[
"MIT"
] |
permissive
|
rebekahyates-peak/CITRUS
|
8dedfa7692742f865126d3560d0660b8e8ec0dac
|
41faff1762223d9fa0cd9c1b0118ef8608a9a96a
|
refs/heads/main
| 2023-08-02T07:21:21.966433
| 2021-09-28T09:49:54
| 2021-09-28T09:49:54
| 406,312,927
| 0
| 0
|
NOASSERTION
| 2021-09-14T09:56:39
| 2021-09-14T09:56:38
| null |
UTF-8
|
R
| false
| false
| 5,467
|
r
|
segment.R
|
#' Segment Function
#'
#' Segments the data by running all steps in the segmentation pipeline, including output table
#' @param data data.frame, the data to segment
#' @param modeltype character, the type of model to use to segment choices are: 'tree', 'k-clusters'
#' @param FUN function, A user specified function to segment, if the standard methods are not wanting to be used
#' @param FUN_preprocess function, A user specified function to preprocess, if the standard methods are not wanting to be used
#' @param steps list, names of the steps the user want to run the data on. Options are 'preprocess' and 'model'
#' @param prettify logical, TRUE if want cleaned up outputs, FALSE for raw output
#' @param print_plot logical, TRUE if want to print the plot
#' @param hyperparameters list of hyperparameters to use in the model.
#' @param force logical, TRUE to ignore errors in validation step and force model execution.
#' @param verbose logical whether information about the segmentation pipeline should be given.
#' @importFrom utils modifyList
#' @export
segment <- function(data,
modeltype = 'tree',
FUN = NULL,
FUN_preprocess = NULL,
steps = c('preprocess', 'model'),
prettify = F,
print_plot = F,
hyperparameters = NULL, force = FALSE, verbose = TRUE) {
# Data processing layer
# returns data in appropriate format called 'data'
if ('preprocess' %in% steps) {
if(verbose == TRUE) {message('Preprocessing data')}
if (is.null(FUN_preprocess)) {
if(verbose == TRUE) {message('Using default preprocessing')}
if (modeltype == 'tree') {
data <- preprocess(data, target = 'transactionvalue', target_agg = 'mean', verbose = verbose)
#print(data)
} else if (modeltype == 'k-clusters') {
data <- preprocess(data, verbose = verbose)
}
} else {
if(verbose == TRUE) {message('Using custom preprocessing')}
data <- FUN_preprocess(data)
}
}
# Model selection layer
if ('model' %in% steps) {
if(verbose == TRUE) {message('Setting up model')}
if (is.null(FUN)) {
# Tree Model
if (modeltype == 'tree') {
if(verbose == TRUE) {message('Tree based model chosen')}
if(verbose == TRUE) {message('Validating input data')}
# Default hyperparameters
default_hyperparameters = list(dependent_variable = 'response',
min_segmentation_fraction = 0.05,
number_of_segments = 6,
print_plot = ifelse(prettify == FALSE, print_plot, FALSE),
print_safety_check=20)
if(is.null(hyperparameters)){
if(verbose == TRUE) {message('Using default hyper-parameters')}
hyperparameters = default_hyperparameters
}else{
hyperparameters = modifyList(default_hyperparameters, hyperparameters)
}
validate(data, supervised = TRUE, force = force, hyperparameters)
if(verbose == TRUE) {message('Training model')}
model = tree_segment(data, hyperparameters, verbose = verbose)
if(verbose == TRUE) {message('Number of segments: ', paste0(max(model$segment_table$segment, '\n')))}
# Prettify layer
if(prettify == T){
if(verbose == TRUE) {message('Prettifying output data')}
model <- tree_segment_prettify(model, print_plot = print_plot)
}
# Abstraction layer
if(verbose == TRUE) {message('Abstracting model')}
model <- tree_abstract(model, data)
}
# Model B
if (modeltype == 'k-clusters') {
if(verbose == TRUE) {message('k-clusters model chosen')}
if(verbose == TRUE) {message('Validating input data')}
# Default hyperparameters
default_hyperparameters = list(centers = 'auto',
iter_max = 50,
nstart = 5,
max_centers = 5,
segmentation_variables = NULL,
standardize = TRUE)
if(is.null(hyperparameters)){
if(verbose == TRUE) {message('Using default hyper-parameters')}
hyperparameters = default_hyperparameters
}else{
hyperparameters = modifyList(default_hyperparameters, hyperparameters)
}
validate(data, supervised = FALSE, force = force, hyperparameters)
if(verbose == TRUE) {message('Training model')}
model = k_clusters(data, hyperparameters, verbose = verbose)
# Prettify layer
if(prettify == T){
if(verbose == TRUE) {message('Prettifying output data')}
print(citrus_pair_plot(model))
}
}
} else {
# User defined model
if(verbose == TRUE) {message('Using custom model')}
model <- FUN(data)
# Abstraction layer
}
}
# Model management layer
model_management(model,hyperparameters)
# Output
if(verbose == TRUE) {message('Generating output table')}
output <- output_table(data, model)
if(verbose == TRUE) {message('Finished!')}
return(list('OutputTable' = output,"segments" = model$predicted_values ,"CitrusModel" = model))
}
|
d5c38aeb0e83eaa12da57e6616edb520bbff0162
|
9e01e643567801ec1188f17b18609af2ceff5999
|
/04-exploratory_data_analysis/project2/plot1.R
|
fa56dde1201b42a3509c4ad38ecbe4861cd8a612
|
[] |
no_license
|
reidpowell/datascience
|
077d522a84838572e0b3d0575cf24bc4d7f2532f
|
1fd3ddec7a21c2ca325218e3b59e9a9ba1fd4c1b
|
refs/heads/master
| 2021-01-10T05:03:54.756547
| 2016-02-01T10:29:46
| 2016-02-01T10:29:46
| 48,336,485
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 845
|
r
|
plot1.R
|
# plot1.R
# assumes that spec *.rds are unzipped and in <pwd>/data/
# user parameters
output_file <- "./plot1.png"
# load libraries
library(sqldf)
# read data files
dat <- readRDS("./data/summarySCC_PM25.rds")
cod <- readRDS("./data/Source_Classification_Code.rds")
# select data for plot
sql <- "SELECT year, SUM(Emissions) AS Total_Emissions FROM dat GROUP BY year"
plot_dat <- sqldf(sql)
# Open the device
png(filename=output_file, width = 480, height = 480)
# generate plot
plot(plot_dat$year, plot_dat$Total_Emissions,
type = "l",
col = "red",
lwd = 3,
xlab = "Year",
ylab = "Total Emissions from PM2.5 (tons)",
main = "Total Emissions from PM2.5, 1999--2008"
)
# add linear regression line
fit <- lm(Total_Emissions ~ year, data = plot_dat)
abline(fit, lty = "dashed")
# Close the device
dev.off()
|
4703ac6d44396cce908302ff70efe34cfab591f0
|
14b76686fbb656353323de8dea135a2c96fbb037
|
/testing.R
|
690a39bb04a97a296a23bd93ea5e59d076c60694
|
[] |
no_license
|
sayon000/oac-shiny
|
8dd3a8a8c8a26d54a90806e54cbf3c130c39b163
|
1d1ce6f5ecdbc30e2036f519dc368a7334321c64
|
refs/heads/master
| 2020-09-09T00:14:37.267383
| 2019-04-05T18:12:55
| 2019-04-05T18:12:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,950
|
r
|
testing.R
|
#Misc. testing
library(shiny)
library(shinyjs)
library(zoo)
library(xts)
library(reshape)
library(lubridate)
library(ggplot2)
library(plotly)
library(DT)
#library(shinyTime)
data_sorter <- function(filein){
#TODO: Account for obvious outlier values (see RAT.csv)
if(is.null(filein)){
return (NULL)
}
else{
#return data frame with empty striings as NA
datain <- read.csv(filein, skip = 2, header = TRUE, na.strings = "")
cnames = c("time","temp")
colnames(datain) <- cnames
#subset datain with no NA values in time/temp columns
complete <- datain[complete.cases(datain[,1:2]),]
#convert string datetimes to POSIX
datetimes <- complete$time
datetimes <- ymd_hms(datetimes)
#Time series value
values <- complete$temp
xtsdata <- xts(values,order.by = datetimes)
#Account for Periodicty < 15 minutes
p <- periodicity(xtsdata)
if(p['frequency'] < 15 && p['units'] == 'mins'){
xtsdata <- to.minutes15(xtsdata)[,1]
}
return(xtsdata)
}
}
fan_dataIn <- function(filein){
if(is.null(filein)){
return (NULL)
}
else{
datain <- read.csv(filein, skip = 2, header = TRUE, na.strings = "")
cnames <- c("num","time","value")
colnames(datain) <- cnames
#subset datain with no NA values in time/temp columns
complete <- datain[complete.cases(datain[,2:3]),]
#convert string datetimes to POSIX
datetimes <- complete$time
datetimes <- mdy_hms(datetimes)
#Time series value
values <- complete$value
xtsdata <- xts(values,order.by = datetimes)
times <- index(xtsdata)
times <- times - 1
times <- times[-1]
nas <- rep(NA,length(times))
insert <- xts(nas,times)
xtsdata <- rbind(xtsdata,insert)
xtsdata <- na.locf(xtsdata)
return(xtsdata)
}
}
######################################################
dateRange <- function(all_data){
first_date <- NA
last_date <- NA
for(data in all_data){
data <- na.trim(data, is.na = 'all')
start <- head(index(data),1)
start <- as.POSIXct(start)
end <- tail(index(data),1)
end <- as.POSIXct(end)
if(is.na(first_date)){
first_date <- start
}else{
if(start < first_date){
first_date <- start
}
}
if(is.na(last_date)){
last_date <- end
}else{
if(end > last_date){
last_date <- end
}
}
}
return(c(first_date,last_date))
}
##########################################
#fan within bounds of mat/rat
case_1_fan <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_1_fan.csv"
case_1_rat <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_1_rat.csv"
case_1_mat <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_1_mat.csv"
case_1_fan <- fan_dataIn(case_1_fan)
case_1_rat <- data_sorter(case_1_rat)
case_1_mat <- data_sorter(case_1_mat)
case1 <- list(case_1_rat, case_1_mat)
dr_case1 <- dateRange(case1)
#beginning of fan outside range of mat/rat
case_2_fan <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_2_fan.csv"
case_2_rat <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_2_rat.csv"
case_2_mat <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_2_mat.csv"
case_2_fan <- fan_dataIn(case_2_fan)
case_2_rat <- data_sorter(case_2_rat)
case_2_mat <- data_sorter(case_2_mat)
case2 <- list(case_2_rat, case_2_mat)
dr_case2 <- dateRange(case2)
#end of fan outside mat/rat
case_3_fan <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_3_fan.csv"
case_3_rat <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_3_rat.csv"
case_3_mat <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_3_mat.csv"
case_3_fan <- fan_dataIn(case_3_fan)
case_3_rat <- data_sorter(case_3_rat)
case_3_mat <- data_sorter(case_3_mat)
case3 <- list(case_3_rat, case_3_mat)
dr_case3 <- dateRange(case3)
#both beginning/end outside range of mat/rat
case_4_fan <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_4_fan.csv"
case_4_rat <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_4_rat.csv"
case_4_mat <- "C:\\Users\\dvign\\Desktop\\bpl\\oac_data\\oac_data\\fan_testing\\case_4_mat.csv"
case_4_fan <- fan_dataIn(case_4_fan)
case_4_rat <- data_sorter(case_4_rat)
case_4_mat <- data_sorter(case_4_mat)
case4 <- list(case_4_rat, case_4_mat)
dr_case4 <- dateRange(case4)
fix_fan_endpoints <- function(fan_data, date_range){
fan_data <- fan_data
index_fan <- index(fan_data)
core_fan <- coredata(fan_data)
start <- date_range[1]
end <- date_range[2]
fan_start <- head(index(fan_data),1)
fan_end <- tail(index(fan_data),1)
#if no endpoints cutoff
if(fan_start > start && fan_end < end){
return(fan_data)
}
#if beginning cutoff
if(fan_start < start){
prev <- index_fan[1]
prev_ind = 1
for(dt in index_fan[-1]){
if(dt > start){
break
}
prev <- dt
prev_ind <- prev_ind + 1
}
prev_val <- core_fan[prev_ind]
to_combine <- xts(prev_val, order.by = start)
fan_data <- rbind(fan_data, to_combine)
}
#if end cutoff
if(fan_end > end){
ind <- length(fan_data)
prev <- index_fan[ind]
ind <- ind -1
prev_ind <- ind
for(i in ind:1){
dt <- index_fan[i]
if(dt < end){
break
}
prev <- dt
prev_ind <- i
}
prev_val <- core_fan[prev_ind]
to_combine <- xts(prev_val, order.by = end)
fan_data <- rbind(fan_data, to_combine)
}
return(fan_data)
}
test <- fix_fan_endpoints(case_4_fan,dr_case4)
data <- list(NA)
data_index <- 1
foo <- function(file_dp){
data[data_index] <- file_dp
data_index <- data_index + 1
}
|
c94129e5bb2d6f1a89832e07eb52cd4fb5af3b65
|
b4dfe3e6c1118b234c911c8f426455a05c1cf66b
|
/cachematrix.R
|
4c4ef7b013aa7bdd52550b7c8991b132f936532a
|
[] |
no_license
|
TomMarvolo/ProgrammingAssignment2
|
fb739760811729abf8486f2a51f5d8c4cabf41d1
|
ce4e2b9e5fedc64714cec1a5a5d85d9479a23358
|
refs/heads/master
| 2021-01-18T03:49:14.603676
| 2014-05-22T20:23:17
| 2014-05-22T20:23:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,167
|
r
|
cachematrix.R
|
## This script defines a Matrix which save its own inverse.
## makeCacheMatrix -> creates a matrix with a Setter/Getter for the values
## and Setter/Getter for the inverse values.
makeCacheMatrix <- function(x = matrix()) { # if x is missing create an empty matrix
inv <- NULL
set <- function(value){
x <<- value
inv <<- NULL
}
get <- function() x
getInverse <- function() inv
setInverse <- function(inverse){
inv <<- inverse
}
list( Set = set, Get= get, SetInverse=setInverse, GetInverse = getInverse)
}
## cacheSolve -> calculates inverse matrix of x,
## arguments:
## x -> Matrix, create with makeCacheMatrix function.
## ... -> additional parameters for solve Function.
cacheSolve <- function(x, ...) {
i <- x$GetInverse()
if(!is.null(i)){ ## If isn't the first time you calculate the inverse return the value of i
message("Obtaining data from Cache...")
return(i)
}
## If its the first time
matriz <- x$Get() ## obtain the values of th ematrix
i <- try(solve(matriz, ...)) ## calculate the inverse
x$SetInverse(inverse = i) ## and update the values saved in the matrix x
return(i)
}
|
4ab5060c2cdfabe6da4d09ba557510f8a7c2e5c6
|
f1e7940e5455d36d36d06b7e92d4fac2aaebd605
|
/man/lag_covariates.Rd
|
56ba3b059e9630e998bf640b5762ca4063ff4dbe
|
[
"MIT"
] |
permissive
|
patdumandan/portalcasting
|
f9dbf0f9ff4718475a8a04137f2bf39382b151e3
|
6faf4c89df2ee686636bd96a535202530fd93acf
|
refs/heads/main
| 2023-05-29T03:11:42.222799
| 2021-03-10T23:21:01
| 2021-03-10T23:21:01
| 328,410,286
| 0
| 0
|
NOASSERTION
| 2021-01-10T15:05:45
| 2021-01-10T15:05:45
| null |
UTF-8
|
R
| false
| true
| 1,376
|
rd
|
lag_covariates.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/prepare_covariates.R
\name{lag_covariates}
\alias{lag_covariates}
\title{Lag covariate data}
\usage{
lag_covariates(covariates, lag, tail = FALSE, arg_checks = TRUE)
}
\arguments{
\item{covariates}{\code{data.frame} of covariate data to be lagged.}
\item{lag}{\code{integer} lag between rodent census and covariate data, in
new moons.}
\item{tail}{\code{logical} indicator if the data lagged to the tail end
should be retained.}
\item{arg_checks}{\code{logical} value of if the arguments should be
checked using standard protocols via \code{\link{check_args}}. The
default (\code{arg_checks = TRUE}) ensures that all inputs are
formatted correctly and provides directed error messages if not. \cr
However, in sandboxing, it is often desirable to be able to deviate from
strict argument expectations. Setting \code{arg_checks = FALSE} triggers
many/most/all enclosed functions to not check any arguments using
\code{\link{check_args}}, and as such, \emph{caveat emptor}.}
}
\value{
\code{data.frame} with a \code{newmoonnumber} column reflecting
the lag.
}
\description{
Lag the covariate data together based on the new moons
}
\examples{
\donttest{
setup_dir()
covariate_casts <- read_covariate_casts()
covar_casts_lag <- lag_covariates(covariate_casts, lag = 2, tail = TRUE)
}
}
|
4e2af70c83fbb6c903df25a631bac15c674ea9f0
|
0766c9ba62e459c753c138c423e57fba14629551
|
/run_analysis.R
|
f14c33fea10014b6f36ea3523bdbb28935aa3281
|
[] |
no_license
|
saptarshihere/datasciencecoursera
|
17d9a62a179eca75e82e035a0ae90e866e80a330
|
de77c83246ff5a928817506b771a61870a2f0a98
|
refs/heads/master
| 2021-01-11T17:54:35.951877
| 2017-03-19T16:47:32
| 2017-03-19T16:47:32
| 79,869,816
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,249
|
r
|
run_analysis.R
|
library(dplyr)
##Setting working directory
setwd("E:/DataScience/Workspace")
##Download and unzip file in local machine
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
download.file(fileUrl,destfile="./UCI_HAR_Dataset.zip")
unzip(zipfile="./UCI_HAR_Dataset.zip")
# Reading trainings tables from the extracted data set
x_train <- read.table("./UCI HAR Dataset/train/X_train.txt")
y_train <- read.table("./UCI HAR Dataset/train/y_train.txt")
subject_train <- read.table("./UCI HAR Dataset/train/subject_train.txt")
# Reading testing tables from the extracted data set
x_test <- read.table("./UCI HAR Dataset/test/X_test.txt")
y_test <- read.table("./UCI HAR Dataset/test/y_test.txt")
subject_test <- read.table("./UCI HAR Dataset/test/subject_test.txt")
# Reading feature data
features <- read.table('./UCI HAR Dataset/features.txt')
# Reading activity labels data
activityLabels = read.table('./UCI HAR Dataset/activity_labels.txt')
##Assign column names
colnames(x_train) <- features[,2]
colnames(y_train) <-"activityId"
colnames(subject_train) <- "subjectId"
colnames(x_test) <- features[,2]
colnames(y_test) <- "activityId"
colnames(subject_test) <- "subjectId"
colnames(activityLabels) <- c('activityId','activityType')
##Merging data set
mrg_train <- cbind(y_train, subject_train, x_train)
mrg_test <- cbind(y_test, subject_test, x_test)
setAllInOne <- rbind(mrg_train, mrg_test)
##Extracting arithmetic mean and standard deviation for the measurements
colNames <- colnames(setAllInOne)
mean_and_std <- (grepl("activityId" , colNames) |
grepl("subjectId" , colNames) |
grepl("mean.." , colNames) |
grepl("std.." , colNames)
)
setForMeanAndStd <- setAllInOne[ , mean_and_std == TRUE]
setWithActivityNames <- merge(setForMeanAndStd, activityLabels,
by='activityId',
all.x=TRUE)
##Creating second independent tidy data set
secTidySet <- aggregate(. ~subjectId + activityId, setWithActivityNames, mean)
secTidySet <- secTidySet[order(secTidySet$subjectId, secTidySet$activityId),]
##Write flat file
write.table(secTidySet, "sec_ind_tidy_set.txt", row.name=FALSE)
|
b259db41c4d8cb93458b85b1c9e2110cb7d26b98
|
8d61e8c0f417348f843fbd3a0f13311d03fa50f8
|
/man/compare_version.Rd
|
c14e70b9ce8e3343db914b6e14838df58a91eca7
|
[
"MIT"
] |
permissive
|
mokymai/bio
|
5ca95723fda6a7f6fcaa0ff6b8a4bb55e76d9330
|
032b86e67fcdf848128e76dcdd3081376d868ce2
|
refs/heads/master
| 2023-08-31T09:10:26.340392
| 2023-08-26T21:28:22
| 2023-08-26T21:28:22
| 234,381,371
| 3
| 1
|
NOASSERTION
| 2023-08-26T18:56:07
| 2020-01-16T18:08:35
|
R
|
UTF-8
|
R
| false
| true
| 792
|
rd
|
compare_version.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/packages--check.R
\name{compare_version}
\alias{compare_version}
\title{Compare Version Numbers}
\usage{
compare_version(v_installed, v_required)
}
\arguments{
\item{v_installed}{vector with installed version numbers}
\item{v_required}{vector with required version numbers}
}
\value{
The same as in \code{\link[utils:compareVersion]{utils::compareVersion()}}, just a vector.
}
\description{
Compare Version Numbers
}
\examples{
compare_version("2.4", "2")
compare_version("2.3", "2.3")
compare_version("2.3", "2.3.1")
}
\seealso{
Other R-packages-related functions:
\code{\link{get_pkgs_installation_status}()},
\code{\link{get_pkgs_installed}()}
}
\concept{R-packages-related functions}
\concept{utilities}
|
399637a3c390843d1fd4b7d5d6a84940826d1ef1
|
30226a8ce00f58e009fea1df7ab4be3e3015d5cc
|
/global.R
|
a3b315960847b7eb66079a654f7e8f8355858b2b
|
[] |
no_license
|
scottglennscott/RshinyDB
|
d476311d053f49e6c70210b5bfb5c8c8920977e7
|
9dfd6a360a07fb58d8f8ebf1535b59fe2c0608a6
|
refs/heads/master
| 2020-03-26T00:09:55.449004
| 2018-08-10T18:49:02
| 2018-08-10T18:49:02
| 144,308,803
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,220
|
r
|
global.R
|
# Load major & minor categories for the survey mock data
source("settings/categories.R")
library(data.table)
library(ggplot2)
library(rgdal)
library(leaflet)
# Create color palette
# Read geojson with world country data
shp <- rgdal::readOGR(dsn = "layers")
shp@data$level <- as.numeric(shp@data$level)
shp = subset(shp, shp@data$level <= 2)
shp@data$admin <- as.character(shp@data$loc_name)
shp2 <- shp
# read in collaborator data
collab_raw <- fread('layers/All Collabs_salesforce.csv')
#collabs = read.csv('C:/users/Scottg16/repos/RshinyDB/layers/Collaborators in Salesforce_Policy Engagement.csv')
collabs_raw = as.data.table(collab_raw)
# Values for selectize input
shp@data = as.data.table(shp@data)
countries <- shp@data$loc_name
countries = na.omit(as.data.table(countries))
ISO3 <- shp@data$ihme_lc_id
mock.data.all <- data.table(countries = countries, ISO3.codes = ISO3)
#mock.data.all <- shp@data[,.(ihme_lc_id, loc_name)]
epsg4088 <- leafletCRS(
crsClass = "L.CRS.Simple",
code = "EPSG:4088",
proj4def = "+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +a=6371007 +b=6371007 +units=m +no_defs",
resolutions = 2^(16:7)
)
# Load CFI theme for ggplot2
source("settings/ggplot_theme_cfi.R")
|
43537c569ec201306acd3b48bf8e77b73cb0ddab
|
b33735d157848984bc57288b41ce2bded79e2710
|
/man/print.CInLPN.Rd
|
59533c408b99138e465e97fac8eb44afa4ab1ea2
|
[] |
no_license
|
bachirtadde/CInLPN
|
9a00a0cabf5af34ba8403b17d81763db6067b990
|
bb51492aa116635c4bf70afd29de7bdd58de15a5
|
refs/heads/master
| 2023-06-30T15:21:04.684650
| 2023-06-20T14:31:49
| 2023-06-20T14:31:49
| 163,929,733
| 2
| 1
| null | 2021-03-28T14:58:25
| 2019-01-03T06:00:38
|
R
|
UTF-8
|
R
| false
| true
| 327
|
rd
|
print.CInLPN.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/print.CInLPN.R
\name{print.CInLPN}
\alias{print.CInLPN}
\title{Print CInLPN object}
\usage{
\method{print}{CInLPN}(x, ...)
}
\arguments{
\item{x}{an CInLPN object}
\item{\dots}{optional parameters}
}
\value{
0
}
\description{
Print CInLPN object
}
|
5d7b9283335983fd741c0d6309789463586b511c
|
375aa98bbe1bcc9ec96e1ff9a0b563c2526ef317
|
/first_paper/GMM EXPORT.R
|
daaff398ecf5563e677a19998fc7b880729a7713
|
[] |
no_license
|
QiKatherine/phd_dissertation
|
06f09bfb5ce465cb3536b9302aa349ec0bec3d39
|
0411c7ace720f9616dadbda101b063e622de0d0c
|
refs/heads/master
| 2023-07-30T10:42:48.983012
| 2021-09-09T15:20:04
| 2021-09-09T15:20:04
| 404,759,069
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,973
|
r
|
GMM EXPORT.R
|
# add_sig_level <- function(x) {
# sig_level <- function(dat) {
#
# if (is.na(dat)) return("")
# y <- as.numeric(dat)
# if (y <= 0.001) return("***")
# else if (y <= 0.01) return("**")
# else if (y <= 0.05) return("*")
# else return("")
# }
# map_chr(x, sig_level)
# }
#
# library(tidyverse)
# library(broom)
library(gmm)
library(plm)
setwd("D:/Google drive local/Financial constraints/Data/")
model_manu_small <- readRDS("modell_manu_small.rds" )
model_manu_CF <- readRDS("model_manu_CF.rds")
model_manu_size <- readRDS("model_manu_size.rds")
model_manu_age <- readRDS("model_manu_age.rds")
summary(model_manu_CF)
model_bank_small <- readRDS("model_bank_small.rds")
model_bank_CF <- readRDS("model_bank_CF.rds")
model_bank_size <- readRDS("model_bank_size.rds")
model_bank_age <- readRDS("model_bank_age.rds")
model_cons_small <- readRDS("model_cons_small.rds")
model_cons_CF <- readRDS("model_cons_CF.rds")
model_cons_size <- readRDS("model_cons_size.rds")
model_cons_age <- readRDS("model_cons_age.rds")
# manu_srmy_small <- summary(model_manu_small)$coefficients[,1:2]
tidy_gmm <- function(md) {
md_srmy <- summary(md)$coefficients[,1:2] %>%
as.data.frame()
vars <- rownames(md_srmy)
md_srmy %>%
mutate(term = vars) %>%
mutate_if(is.numeric, ~ as.character(round(.x, digits = 3))) %>%
select(term, everything())
}
manu_md_res <- tidy_gmm(model_manu_size) %>%
full_join(tidy_gmm(model_manu_CF), by = "term") %>%
full_join(tidy_gmm(model_manu_age), by = "term")
write.csv(manu_md_res, "gmm_manu.csv")
bank_md_res <- tidy_gmm(model_bank_size) %>%
full_join(tidy_gmm(model_bank_CF), by = "term") %>%
full_join(tidy_gmm(model_bank_age), by = "term")
write.csv(bank_md_res, "gmm_bank.csv")
cons_md_res <- tidy_gmm(model_cons_size) %>%
full_join(tidy_gmm(model_cons_CF), by = "term") %>%
full_join(tidy_gmm(model_cons_age), by = "term")
write.csv(cons_md_res, "gmm_cons.csv")
|
317932a47f95c8c21e2f0545ac4103662d9adcbf
|
fa6c05d1ef97f092b4c51c167f70eb426bc6c1f7
|
/05-cluster.r
|
ad8492ae79a8746b323677dc57a73398bd4d50cf
|
[] |
no_license
|
huaiyutian/Dengue_COVID-19
|
5120e1b0681307714104eedf599c1238771f02d2
|
c0c56b18f8fa2280da29770bd7909796518778ab
|
refs/heads/main
| 2023-08-25T16:03:56.458418
| 2021-10-17T14:27:13
| 2021-10-17T14:27:13
| 418,144,930
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 860
|
r
|
05-cluster.r
|
library(pvclust)
npi <- read.csv("00.data/02.PHSM_HMB.csv",row.names=1)
pdf("02.fig/Fig_S14/Fig_S13_cluster.pdf")
# The hierarchical clustering analysis of Bootstrap (the number of Bootstrap is 10000) was carried out. Ward method
# The dissimilarity matrix based on correlation were adopted as follows:
result <- pvclust(npi, method.dist="euclidean", method.hclust="ward.D2", nboot=10000, parallel=TRUE)
plot(result)
pvrect(result, alpha=0.95)
dev.off()
# For the cluster with Au P value > 0.95, the hypothesis of "non-existence of clustering" was rejected at the significance level of 0.05.
# Roughly speaking, we can think of these highlighted clusters as not just "appearing to exist" due to sampling errors
# And if we increase the number of observations, we can see them steadily.
seplot(result, identify=TRUE)
msplot(result, edges=x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.