content large_stringlengths 0 6.46M | path large_stringlengths 3 331 | license_type large_stringclasses 2 values | repo_name large_stringlengths 5 125 | language large_stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.46M | extension large_stringclasses 75 values | text stringlengths 0 6.46M |
|---|---|---|---|---|---|---|---|---|---|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/robomaker_operations.R
\name{robomaker_list_world_generation_jobs}
\alias{robomaker_list_world_generation_jobs}
\title{Lists world generator jobs}
\usage{
robomaker_list_world_generation_jobs(nextToken, maxResults, filters)
}
\arguments{
\item{nextToken}{If the previous paginated request did not return all of the remaining
results, the response object's \code{nextToken} parameter value is set to a
token. To retrieve the next set of results, call
\code{ListWorldGenerationJobsRequest} again and assign that token to the
request object's \code{nextToken} parameter. If there are no remaining
results, the previous response object's NextToken parameter is set to
null.}
\item{maxResults}{When this parameter is used, \code{ListWorldGeneratorJobs} only returns
\code{maxResults} results in a single page along with a \code{nextToken} response
element. The remaining results of the initial request can be seen by
sending another \code{ListWorldGeneratorJobs} request with the returned
\code{nextToken} value. This value can be between 1 and 100. If this
parameter is not used, then \code{ListWorldGeneratorJobs} returns up to 100
results and a \code{nextToken} value if applicable.}
\item{filters}{Optional filters to limit results. You can use \code{status} and
\code{templateId}.}
}
\description{
Lists world generator jobs.
}
\section{Request syntax}{
\preformatted{svc$list_world_generation_jobs(
nextToken = "string",
maxResults = 123,
filters = list(
list(
name = "string",
values = list(
"string"
)
)
)
)
}
}
\keyword{internal}
| /cran/paws.robotics/man/robomaker_list_world_generation_jobs.Rd | permissive | sanchezvivi/paws | R | false | true | 1,657 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/robomaker_operations.R
\name{robomaker_list_world_generation_jobs}
\alias{robomaker_list_world_generation_jobs}
\title{Lists world generator jobs}
\usage{
robomaker_list_world_generation_jobs(nextToken, maxResults, filters)
}
\arguments{
\item{nextToken}{If the previous paginated request did not return all of the remaining
results, the response object's \code{nextToken} parameter value is set to a
token. To retrieve the next set of results, call
\code{ListWorldGenerationJobsRequest} again and assign that token to the
request object's \code{nextToken} parameter. If there are no remaining
results, the previous response object's NextToken parameter is set to
null.}
\item{maxResults}{When this parameter is used, \code{ListWorldGeneratorJobs} only returns
\code{maxResults} results in a single page along with a \code{nextToken} response
element. The remaining results of the initial request can be seen by
sending another \code{ListWorldGeneratorJobs} request with the returned
\code{nextToken} value. This value can be between 1 and 100. If this
parameter is not used, then \code{ListWorldGeneratorJobs} returns up to 100
results and a \code{nextToken} value if applicable.}
\item{filters}{Optional filters to limit results. You can use \code{status} and
\code{templateId}.}
}
\description{
Lists world generator jobs.
}
\section{Request syntax}{
\preformatted{svc$list_world_generation_jobs(
nextToken = "string",
maxResults = 123,
filters = list(
list(
name = "string",
values = list(
"string"
)
)
)
)
}
}
\keyword{internal}
|
#' @name primate.dat
#' @title Primate line transect survey data.
#' @docType data
#' @description Locations relative to the observer of 127 detections of primates from a
#' visual survey conducted by three sets of trained observers walking previously cut line
#' transects in primary tropical rainforest.
#' @usage primate.dat
#' @format A list with elements x (perpendicular distance) and y (forward distance).
#' @source We are grateful to Matthew Nowak from the Sumatran Orangutan Conservation
#' Programme (SOCP) for allowing us to use the primate survey data from the Jantho
#' Reintroduction Station. The initial survey was developed by Matthew Nowak and Serge
#' Wich (Liverpool John Moores University) and then undertaken by the SOCP with funding
#' from Chester Zoo.
#' @examples
#' data(primate.dat)
NULL
#' @name dolphin.dat
#' @title Dolphin line transect survey data.
#' @docType data
#' @description Locations relative to the observer of 74 detections of dolphins from a
#' shipboard visual survey.
#' @usage dolphin.dat
#' @format A list with elements x (perpendicular distance) and y (forward distance).
#' @source We are gerateful to North Atlantic Marine Mammal Commission (NAMMCO) and the
#' Faroese Museum of Natural History for allowing us to use the dolphin survey data from
#' 1995 North Atlantic Sightings Survey (NASS95). These data are analysed using
#' mark-recapture distance sampling methods by Ca\~{n}adas et al. (2004).
#' @references
#' Ca\~{n}adas, A., Desportes, G. and Borchers, D.L. 2004. The estimation of the detection
#' function and g(0) for short-beaked common dolphins (Delphinis delphis), using
#' double-platform data collected during the NASS-95 Faroese survey. Journal of Cetacean
#' Research and Management 6: 191-198.
#' @examples
#' data(primate.dat)
NULL
| /R/data.r | no_license | david-borchers/LT2D | R | false | false | 1,825 | r |
#' @name primate.dat
#' @title Primate line transect survey data.
#' @docType data
#' @description Locations relative to the observer of 127 detections of primates from a
#' visual survey conducted by three sets of trained observers walking previously cut line
#' transects in primary tropical rainforest.
#' @usage primate.dat
#' @format A list with elements x (perpendicular distance) and y (forward distance).
#' @source We are grateful to Matthew Nowak from the Sumatran Orangutan Conservation
#' Programme (SOCP) for allowing us to use the primate survey data from the Jantho
#' Reintroduction Station. The initial survey was developed by Matthew Nowak and Serge
#' Wich (Liverpool John Moores University) and then undertaken by the SOCP with funding
#' from Chester Zoo.
#' @examples
#' data(primate.dat)
NULL
#' @name dolphin.dat
#' @title Dolphin line transect survey data.
#' @docType data
#' @description Locations relative to the observer of 74 detections of dolphins from a
#' shipboard visual survey.
#' @usage dolphin.dat
#' @format A list with elements x (perpendicular distance) and y (forward distance).
#' @source We are gerateful to North Atlantic Marine Mammal Commission (NAMMCO) and the
#' Faroese Museum of Natural History for allowing us to use the dolphin survey data from
#' 1995 North Atlantic Sightings Survey (NASS95). These data are analysed using
#' mark-recapture distance sampling methods by Ca\~{n}adas et al. (2004).
#' @references
#' Ca\~{n}adas, A., Desportes, G. and Borchers, D.L. 2004. The estimation of the detection
#' function and g(0) for short-beaked common dolphins (Delphinis delphis), using
#' double-platform data collected during the NASS-95 Faroese survey. Journal of Cetacean
#' Research and Management 6: 191-198.
#' @examples
#' data(primate.dat)
NULL
|
#
# Copyright 2007-2017 The OpenMx Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# OpenMx Out of order thresholds test
require(OpenMx)
set.seed(1234)
# Set up simulation parameters
nVariables <- 3
varNames <- paste0("var",1:nVariables)
nFactors <- 1
nThresholds <- 3
nSubjects <- 500
# Simulate multivariate normal data and chop into ordinal
loadings <- matrix(.7,nrow=nVariables,ncol=nFactors)
residuals <- 1 - (loadings * loadings)
sigma <- loadings %*% t(loadings) + vec2diag(residuals)
mu <- matrix(0,nrow=nVariables,ncol=1)
continuousData <- mvtnorm::rmvnorm(n=nSubjects, mu, sigma)
quants <-quantile(continuousData[,1], probs = c((1:nThresholds)/(nThresholds+1)))
quants[2] <- .65
ordinalData <- matrix(0, nrow = nSubjects, ncol = nVariables)
for(i in 1:nVariables) {
ordinalData[,i] <- cut(as.vector(continuousData[,i]), c(-Inf, quants, Inf))
}
ordinalData <- mxFactor(as.data.frame(ordinalData),levels=c(1:(nThresholds+1)))
names(ordinalData) <- varNames
# table(list(ordinalData[,1],ordinalData[,2]))
m1 <- mxModel("m1",
mxMatrix(name = "vectorofOnes", "Unit", nVariables, 1),
mxMatrix(name = "L" , "Full", nVariables, nFactors, values=0.2, free=TRUE, lbound=-.99, ubound=.99),
mxMatrix(name = "M" , "Zero", 1, nVariables),
mxAlgebra(vectorofOnes - (diag2vec(L %*% t(L))) , name = "E"),
mxAlgebra(L %*% t(L) + vec2diag(E), name="impliedCovs"),
mxMatrix(name="thresholdDeviations", "Full", nrow=nThresholds, ncol=nVariables,
values = c(.2,.201,.3),
free = TRUE,
lbound = rep(c(-Inf,rep(.01,(nThresholds-1))) , nVariables),
dimnames = list(c(), varNames)
),
# mxMatrix("Lower",nThresholds,nThresholds,values=1,free=F,name="unitLower"),
mxAlgebra(thresholdDeviations, name = "thresholdMatrix"),
mxExpectationNormal("impliedCovs", means = "M", dimnames = varNames, thresholds = "thresholdMatrix"),
mxFitFunctionML(),
mxData(ordinalData, type = 'raw')
)
# set up checkpointing to observe the threshold locations
m1 <- mxOption(m1,'Checkpoint Units', 'evaluations')
m1 <- mxOption(m1,'Checkpoint Count', 1)
mxRun(m1, checkpoint=TRUE, unsafe= TRUE)
summary(m1)
| /inst/models/passing/test_thresh_kept_in_order.R | no_license | ktargows/OpenMx | R | false | false | 2,711 | r | #
# Copyright 2007-2017 The OpenMx Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# OpenMx Out of order thresholds test
require(OpenMx)
set.seed(1234)
# Set up simulation parameters
nVariables <- 3
varNames <- paste0("var",1:nVariables)
nFactors <- 1
nThresholds <- 3
nSubjects <- 500
# Simulate multivariate normal data and chop into ordinal
loadings <- matrix(.7,nrow=nVariables,ncol=nFactors)
residuals <- 1 - (loadings * loadings)
sigma <- loadings %*% t(loadings) + vec2diag(residuals)
mu <- matrix(0,nrow=nVariables,ncol=1)
continuousData <- mvtnorm::rmvnorm(n=nSubjects, mu, sigma)
quants <-quantile(continuousData[,1], probs = c((1:nThresholds)/(nThresholds+1)))
quants[2] <- .65
ordinalData <- matrix(0, nrow = nSubjects, ncol = nVariables)
for(i in 1:nVariables) {
ordinalData[,i] <- cut(as.vector(continuousData[,i]), c(-Inf, quants, Inf))
}
ordinalData <- mxFactor(as.data.frame(ordinalData),levels=c(1:(nThresholds+1)))
names(ordinalData) <- varNames
# table(list(ordinalData[,1],ordinalData[,2]))
m1 <- mxModel("m1",
mxMatrix(name = "vectorofOnes", "Unit", nVariables, 1),
mxMatrix(name = "L" , "Full", nVariables, nFactors, values=0.2, free=TRUE, lbound=-.99, ubound=.99),
mxMatrix(name = "M" , "Zero", 1, nVariables),
mxAlgebra(vectorofOnes - (diag2vec(L %*% t(L))) , name = "E"),
mxAlgebra(L %*% t(L) + vec2diag(E), name="impliedCovs"),
mxMatrix(name="thresholdDeviations", "Full", nrow=nThresholds, ncol=nVariables,
values = c(.2,.201,.3),
free = TRUE,
lbound = rep(c(-Inf,rep(.01,(nThresholds-1))) , nVariables),
dimnames = list(c(), varNames)
),
# mxMatrix("Lower",nThresholds,nThresholds,values=1,free=F,name="unitLower"),
mxAlgebra(thresholdDeviations, name = "thresholdMatrix"),
mxExpectationNormal("impliedCovs", means = "M", dimnames = varNames, thresholds = "thresholdMatrix"),
mxFitFunctionML(),
mxData(ordinalData, type = 'raw')
)
# set up checkpointing to observe the threshold locations
m1 <- mxOption(m1,'Checkpoint Units', 'evaluations')
m1 <- mxOption(m1,'Checkpoint Count', 1)
mxRun(m1, checkpoint=TRUE, unsafe= TRUE)
summary(m1)
|
library(plyr)
library(emdbook)
source('../R/Libraries/GLM.functions.R')
data = read.table('../Output/omg.huge.output.tsv', sep='\t', header=TRUE)
wi = read.table('../supporting files/WI_boundary_lat_lon.tsv', sep='\t', header=TRUE)
driver.data = read.table('../Output/driver.JAS.means.tsv', sep='\t', header=TRUE)
lake.meta = data.frame(WBIC=unique(data$lakeid), max.depth=NA, area=NA, kd=NA, lat=NA, lon=NA)
for(i in 1:nrow(lake.meta)){
lake.meta$max.depth[i] = getZmax(as.character(lake.meta$WBIC[i]))
lake.meta$area[i] = getArea(as.character(lake.meta$WBIC[i]))
if(is.na(lake.meta$max.depth[i])){
lake.meta$max.depth[i] = max(getBathy(as.character(lake.meta$WBIC[i]))$depth)
}
lake.meta$kd[i] = getClarity(as.character(lake.meta$WBIC[i]))
ll = getLatLon(as.character(lake.meta$WBIC[i]))
lake.meta$lat[i] = ll[1]
lake.meta$lon[i] = ll[2]
}
air.temp = read.table('../Output/airtemp.metrics.csv', sep=',', header=TRUE)
hyp.temps = read.table('../Output/KdScenarios/stable.metrics.out.tsv', sep='\t', header=TRUE)
all.data = merge(air.temp, data, by.x=c("WBIC", "Year"), by.y=c("lakeid", "year"))
all.data = merge(all.data, hyp.temps, by.x=c("WBIC", "Year"), by.y=c("lakeid", "year"))
jas.air.slopes = ddply(all.data, c('WBIC'), function(df) lm(df$JAS.Mean ~ df$Year)$coeff[2])
jas.surf.slopes = ddply(all.data, c('WBIC'), function(df) lm(df$mean_surf_JAS ~ df$Year)$coeff[2])
names(jas.surf.slopes) = c('WBIC','surf.slope')
names(jas.air.slopes) = c('WBIC','air.slope')
sw.slopes = ddply(driver.data, c('WBIC'), function(df) lm(df$ShortWave ~ df$year)$coeff[2])
names(sw.slopes) = c('WBIC','sw.slope')
lw.slopes = ddply(driver.data, c('WBIC'), function(df) lm(df$LongWave ~ df$year)$coeff[2])
names(lw.slopes) = c('WBIC','lw.slope')
ws.slopes = ddply(driver.data, c('WBIC'), function(df) lm(df$WindSpeed ~ df$year)$coeff[2])
names(ws.slopes) = c('WBIC','ws.slopes')
at.slopes = ddply(driver.data, c('WBIC'), function(df) lm(df$AirTemp ~ df$year)$coeff[2])
names(at.slopes) = c('WBIC','at.slope')
driver.slopes = merge(merge(sw.slopes,lw.slopes), merge(ws.slopes, at.slopes))
all.slopes= join(jas.surf.slopes, jas.air.slopes)
all.slopes = join(all.slopes, lake.meta)
all.slopes = join(all.slopes, driver.slopes)
colors = rainbow(nrow(all.slopes),alpha=0.4)[order(all.slopes$surf.slope, decreasing=TRUE)]
plot(all.slopes$lon, all.slopes$lat, col=colors, pch=16)
#wi = wi[!is.na(wi$Lon),]
lines(wi$Lon, wi$Lat)
tiff('wtr.trend.tiff', width=1800, height=1800, res=300, compression='lzw')
my.mat = interp(all.slopes$lon, all.slopes$lat, all.slopes$surf.slope)
filled.contour(my.mat, color.palette=
colorRampPalette(c("violet","blue","cyan", "green3", "yellow", "orange", "red"),
bias = 1, space = "rgb"), ylab="Lat", xlab="Lon", main='Wtr Trend',
plot.axes = lines(wi$Lon, wi$Lat))
dev.off()
tiff('air.trend.tiff', width=1800, height=1800, res=300, compression='lzw')
my.mat = interp(all.slopes$lon, all.slopes$lat, all.slopes$air.slope)
#tiff('kd.area.slope.heat.tiff', width=1800, height=1200, res=300, compression='lzw')
filled.contour(my.mat, color.palette=
colorRampPalette(c("violet","blue","cyan", "green3", "yellow", "orange", "red"),
bias = 1, space = "rgb"), ylab="Lat", xlab="Lon", main='Air Trend',
plot.axes = lines(wi$Lon, wi$Lat))
dev.off()
tiff('sw.trend.tiff', width=1800, height=1800, res=300, compression='lzw')
my.mat = interp(all.slopes$lon, all.slopes$lat, all.slopes$sw.slope)
#tiff('kd.area.slope.heat.tiff', width=1800, height=1200, res=300, compression='lzw')
filled.contour(my.mat, color.palette=
colorRampPalette(c("violet","blue","cyan", "green3", "yellow", "orange", "red"),
bias = 1, space = "rgb"), ylab="Lat", xlab="Lon", main='SW Trend',
plot.axes = lines(wi$Lon, wi$Lat))
dev.off()
tiff('lw.trend.tiff', width=1800, height=1800, res=300, compression='lzw')
my.mat = interp(all.slopes$lon, all.slopes$lat, all.slopes$lw.slope)
#tiff('kd.area.slope.heat.tiff', width=1800, height=1200, res=300, compression='lzw')
filled.contour(my.mat, color.palette=
colorRampPalette(c("violet","blue","cyan", "green3", "yellow", "orange", "red"),
bias = 1, space = "rgb"), ylab="Lat", xlab="Lon", main='LW Trend',
plot.axes = lines(wi$Lon, wi$Lat))
dev.off()
my.mat = interp(all.slopes$lon, all.slopes$lat, all.slopes$ws.slope)
#tiff('kd.area.slope.heat.tiff', width=1800, height=1200, res=300, compression='lzw')
filled.contour(my.mat, color.palette=
colorRampPalette(c("violet","blue","cyan", "green3", "yellow", "orange", "red"),
bias = 1, space = "rgb"), ylab="Lat", xlab="Lon", main='Wind Trend',
plot.axes = lines(wi$Lon, wi$Lat))
#dev.off()
| /demo/pub_code/R.Figures/figure.maps.R | permissive | USGS-R/mda.lakes | R | false | false | 5,044 | r |
library(plyr)
library(emdbook)
source('../R/Libraries/GLM.functions.R')
data = read.table('../Output/omg.huge.output.tsv', sep='\t', header=TRUE)
wi = read.table('../supporting files/WI_boundary_lat_lon.tsv', sep='\t', header=TRUE)
driver.data = read.table('../Output/driver.JAS.means.tsv', sep='\t', header=TRUE)
lake.meta = data.frame(WBIC=unique(data$lakeid), max.depth=NA, area=NA, kd=NA, lat=NA, lon=NA)
for(i in 1:nrow(lake.meta)){
lake.meta$max.depth[i] = getZmax(as.character(lake.meta$WBIC[i]))
lake.meta$area[i] = getArea(as.character(lake.meta$WBIC[i]))
if(is.na(lake.meta$max.depth[i])){
lake.meta$max.depth[i] = max(getBathy(as.character(lake.meta$WBIC[i]))$depth)
}
lake.meta$kd[i] = getClarity(as.character(lake.meta$WBIC[i]))
ll = getLatLon(as.character(lake.meta$WBIC[i]))
lake.meta$lat[i] = ll[1]
lake.meta$lon[i] = ll[2]
}
air.temp = read.table('../Output/airtemp.metrics.csv', sep=',', header=TRUE)
hyp.temps = read.table('../Output/KdScenarios/stable.metrics.out.tsv', sep='\t', header=TRUE)
all.data = merge(air.temp, data, by.x=c("WBIC", "Year"), by.y=c("lakeid", "year"))
all.data = merge(all.data, hyp.temps, by.x=c("WBIC", "Year"), by.y=c("lakeid", "year"))
jas.air.slopes = ddply(all.data, c('WBIC'), function(df) lm(df$JAS.Mean ~ df$Year)$coeff[2])
jas.surf.slopes = ddply(all.data, c('WBIC'), function(df) lm(df$mean_surf_JAS ~ df$Year)$coeff[2])
names(jas.surf.slopes) = c('WBIC','surf.slope')
names(jas.air.slopes) = c('WBIC','air.slope')
sw.slopes = ddply(driver.data, c('WBIC'), function(df) lm(df$ShortWave ~ df$year)$coeff[2])
names(sw.slopes) = c('WBIC','sw.slope')
lw.slopes = ddply(driver.data, c('WBIC'), function(df) lm(df$LongWave ~ df$year)$coeff[2])
names(lw.slopes) = c('WBIC','lw.slope')
ws.slopes = ddply(driver.data, c('WBIC'), function(df) lm(df$WindSpeed ~ df$year)$coeff[2])
names(ws.slopes) = c('WBIC','ws.slopes')
at.slopes = ddply(driver.data, c('WBIC'), function(df) lm(df$AirTemp ~ df$year)$coeff[2])
names(at.slopes) = c('WBIC','at.slope')
driver.slopes = merge(merge(sw.slopes,lw.slopes), merge(ws.slopes, at.slopes))
all.slopes= join(jas.surf.slopes, jas.air.slopes)
all.slopes = join(all.slopes, lake.meta)
all.slopes = join(all.slopes, driver.slopes)
colors = rainbow(nrow(all.slopes),alpha=0.4)[order(all.slopes$surf.slope, decreasing=TRUE)]
plot(all.slopes$lon, all.slopes$lat, col=colors, pch=16)
#wi = wi[!is.na(wi$Lon),]
lines(wi$Lon, wi$Lat)
tiff('wtr.trend.tiff', width=1800, height=1800, res=300, compression='lzw')
my.mat = interp(all.slopes$lon, all.slopes$lat, all.slopes$surf.slope)
filled.contour(my.mat, color.palette=
colorRampPalette(c("violet","blue","cyan", "green3", "yellow", "orange", "red"),
bias = 1, space = "rgb"), ylab="Lat", xlab="Lon", main='Wtr Trend',
plot.axes = lines(wi$Lon, wi$Lat))
dev.off()
tiff('air.trend.tiff', width=1800, height=1800, res=300, compression='lzw')
my.mat = interp(all.slopes$lon, all.slopes$lat, all.slopes$air.slope)
#tiff('kd.area.slope.heat.tiff', width=1800, height=1200, res=300, compression='lzw')
filled.contour(my.mat, color.palette=
colorRampPalette(c("violet","blue","cyan", "green3", "yellow", "orange", "red"),
bias = 1, space = "rgb"), ylab="Lat", xlab="Lon", main='Air Trend',
plot.axes = lines(wi$Lon, wi$Lat))
dev.off()
tiff('sw.trend.tiff', width=1800, height=1800, res=300, compression='lzw')
my.mat = interp(all.slopes$lon, all.slopes$lat, all.slopes$sw.slope)
#tiff('kd.area.slope.heat.tiff', width=1800, height=1200, res=300, compression='lzw')
filled.contour(my.mat, color.palette=
colorRampPalette(c("violet","blue","cyan", "green3", "yellow", "orange", "red"),
bias = 1, space = "rgb"), ylab="Lat", xlab="Lon", main='SW Trend',
plot.axes = lines(wi$Lon, wi$Lat))
dev.off()
tiff('lw.trend.tiff', width=1800, height=1800, res=300, compression='lzw')
my.mat = interp(all.slopes$lon, all.slopes$lat, all.slopes$lw.slope)
#tiff('kd.area.slope.heat.tiff', width=1800, height=1200, res=300, compression='lzw')
filled.contour(my.mat, color.palette=
colorRampPalette(c("violet","blue","cyan", "green3", "yellow", "orange", "red"),
bias = 1, space = "rgb"), ylab="Lat", xlab="Lon", main='LW Trend',
plot.axes = lines(wi$Lon, wi$Lat))
dev.off()
my.mat = interp(all.slopes$lon, all.slopes$lat, all.slopes$ws.slope)
#tiff('kd.area.slope.heat.tiff', width=1800, height=1200, res=300, compression='lzw')
filled.contour(my.mat, color.palette=
colorRampPalette(c("violet","blue","cyan", "green3", "yellow", "orange", "red"),
bias = 1, space = "rgb"), ylab="Lat", xlab="Lon", main='Wind Trend',
plot.axes = lines(wi$Lon, wi$Lat))
#dev.off()
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/arrival.process.R
\name{arrival.process}
\alias{arrival.process}
\title{Generates patient arrival data}
\usage{
arrival.process(nr.datasets = 1, seed = NULL, rates.by.disease,
mutants.by.disease = NULL, mutants.by.module = NULL, by.module = FALSE)
}
\arguments{
\item{nr.datasets}{Number of arrival-datasets to be generated.}
\item{seed}{Set seed equela to \code{seed}.}
\item{rates.by.disease}{A vector or matrix of arrival rates for K disease (columns) and M subpopulations (rows),
for a trial M Biomarker subpopulations.}
\item{mutants.by.disease}{A vector or matrix of total patient accrual by disease (columns) and subpopulation (rows).}
\item{mutants.by.module}{A scalar or vector of total patient accrual by subpopulation.}
\item{by.module}{If true simulate patient total patient accrual by model (fixed) and
then simulated for the \code{mutants.by.module[m]} patients on subpopulation the disease type.}
}
\value{
Returns a list of nr.datasets matrices, where each row indicates a patient.
The 1th, 2th and 3th column contains the arrival-time, disease and subpopulation for each patient.
}
\description{
Takes the a vector of arrival rates and the number of patients to be accruled by disease and returns patients arrival data by time (in weeks).
}
\examples{
## one module with 3 cancer
rates.by.disease = c(1,2,3)
mutants.by.disease = c(10, 20, 10)
arrival.process(nr.datasets=10, seed=1121, rates.by.disease, mutants.by.disease)
## two modules with 3 cancer
rates.by.disease = cbind(c(1,0,3), c(0,3,3))
mutants.by.disease = cbind(c(10, 0, 10), c(0, 10, 10))
arrival.process(nr.datasets=10, seed=1121, rates.by.disease, mutants.by.disease)
}
\author{
Steffen Ventz \email{ventzer@yahoo.de}
}
| /man/arrival.process.Rd | no_license | stefvanbuuren/BayesAdaptive | R | false | true | 1,797 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/arrival.process.R
\name{arrival.process}
\alias{arrival.process}
\title{Generates patient arrival data}
\usage{
arrival.process(nr.datasets = 1, seed = NULL, rates.by.disease,
mutants.by.disease = NULL, mutants.by.module = NULL, by.module = FALSE)
}
\arguments{
\item{nr.datasets}{Number of arrival-datasets to be generated.}
\item{seed}{Set seed equela to \code{seed}.}
\item{rates.by.disease}{A vector or matrix of arrival rates for K disease (columns) and M subpopulations (rows),
for a trial M Biomarker subpopulations.}
\item{mutants.by.disease}{A vector or matrix of total patient accrual by disease (columns) and subpopulation (rows).}
\item{mutants.by.module}{A scalar or vector of total patient accrual by subpopulation.}
\item{by.module}{If true simulate patient total patient accrual by model (fixed) and
then simulated for the \code{mutants.by.module[m]} patients on subpopulation the disease type.}
}
\value{
Returns a list of nr.datasets matrices, where each row indicates a patient.
The 1th, 2th and 3th column contains the arrival-time, disease and subpopulation for each patient.
}
\description{
Takes the a vector of arrival rates and the number of patients to be accruled by disease and returns patients arrival data by time (in weeks).
}
\examples{
## one module with 3 cancer
rates.by.disease = c(1,2,3)
mutants.by.disease = c(10, 20, 10)
arrival.process(nr.datasets=10, seed=1121, rates.by.disease, mutants.by.disease)
## two modules with 3 cancer
rates.by.disease = cbind(c(1,0,3), c(0,3,3))
mutants.by.disease = cbind(c(10, 0, 10), c(0, 10, 10))
arrival.process(nr.datasets=10, seed=1121, rates.by.disease, mutants.by.disease)
}
\author{
Steffen Ventz \email{ventzer@yahoo.de}
}
|
library(ggplot2)
library(corrplot)
mtcars <- read.csv("Seccion 09 - El paquete ggplot2/mtcars.csv")
mtcars$X <- NULL
mtcars.cor <- cor(mtcars,
method = "pearson")
round(mtcars.cor,
digits = 2)
corrplot(mtcars.cor)
corrplot(mtcars.cor,
method = "shade",
shade.col = NA,
tl.col = "black",
tl.srt = 45)
colores <- colorRampPalette(c("#BB4444",
"#EE9988",
"#FFFFFF",
"#77AADD",
"#4477AA"))
corrplot(mtcars.cor,
method = "shade",
shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE")
corrplot(mtcars.cor,
method = "shade",
shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE",
type = "lower")
corrplot(mtcars.cor,
method = "shade",
shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE",
type = "upper")
corrplot(mtcars.cor,
method = "shade",
#shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE",
type = "lower",
diag = F,
addshade = "all")
corrplot(mtcars.cor,
method = "circle",
#shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE",
type = "lower",
diag = F,
addshade = "all")
corrplot(mtcars.cor,
method = "pie",
#shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE",
type = "lower",
diag = F,
addshade = "all")
## con ggplot tambien podemos representar una matrix de corr
library(reshape2)
mtcars.melted <- melt(mtcars.cor)
ggplot(data = mtcars.melted,
aes(x=Var1,
y=Var2,
fill = value)) +
geom_tile()
####119. Agregando tonalidades a las matrices de color
get_lower_triangle <- function(cormat) {
cormat[upper.tri(cormat)] <- NA
return(cormat)
}
get_upper_triangle <- function(cormat) {
cormat[lower.tri(cormat)] <- NA
return(cormat)
}
reorder_cormat <- function(cormat){
dd <- as.dist((1 - cormat)/2)
hc <- hclust(dd)
cormat <- cormat[hc$order,hc$order]
}
cormat <- reorder_cormat(mtcars.cor)
cormat.up <- get_upper_triangle(cormat)
cormat.up.melted <- melt(cormat.up,
na.rm = T)
ggplot(cormat.up.melted,
aes(x = Var1,
y = Var2,
fill = value)) +
geom_tile(color = "white")+
scale_fill_gradient2(low = "blue",
high = "red",
mid = "white",
midpoint = 0,
limit = c(-1, 1),
space = "Lab",
name = "Pearson\nCorrelation") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1)) +
coord_fixed()
| /Seccion 09 - El paquete ggplot2/118 - Graficos con Matrices de correlación.R | no_license | achiola/r | R | false | false | 3,557 | r | library(ggplot2)
library(corrplot)
mtcars <- read.csv("Seccion 09 - El paquete ggplot2/mtcars.csv")
mtcars$X <- NULL
mtcars.cor <- cor(mtcars,
method = "pearson")
round(mtcars.cor,
digits = 2)
corrplot(mtcars.cor)
corrplot(mtcars.cor,
method = "shade",
shade.col = NA,
tl.col = "black",
tl.srt = 45)
colores <- colorRampPalette(c("#BB4444",
"#EE9988",
"#FFFFFF",
"#77AADD",
"#4477AA"))
corrplot(mtcars.cor,
method = "shade",
shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE")
corrplot(mtcars.cor,
method = "shade",
shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE",
type = "lower")
corrplot(mtcars.cor,
method = "shade",
shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE",
type = "upper")
corrplot(mtcars.cor,
method = "shade",
#shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE",
type = "lower",
diag = F,
addshade = "all")
corrplot(mtcars.cor,
method = "circle",
#shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE",
type = "lower",
diag = F,
addshade = "all")
corrplot(mtcars.cor,
method = "pie",
#shade.col = NA,
tl.col = "black",
tl.srt = 45,
col = colores(200),
addCoef.col = "black",
addcolorlabel = "no",
order = "AOE",
type = "lower",
diag = F,
addshade = "all")
## con ggplot tambien podemos representar una matrix de corr
library(reshape2)
mtcars.melted <- melt(mtcars.cor)
ggplot(data = mtcars.melted,
aes(x=Var1,
y=Var2,
fill = value)) +
geom_tile()
####119. Agregando tonalidades a las matrices de color
get_lower_triangle <- function(cormat) {
cormat[upper.tri(cormat)] <- NA
return(cormat)
}
get_upper_triangle <- function(cormat) {
cormat[lower.tri(cormat)] <- NA
return(cormat)
}
reorder_cormat <- function(cormat){
dd <- as.dist((1 - cormat)/2)
hc <- hclust(dd)
cormat <- cormat[hc$order,hc$order]
}
cormat <- reorder_cormat(mtcars.cor)
cormat.up <- get_upper_triangle(cormat)
cormat.up.melted <- melt(cormat.up,
na.rm = T)
ggplot(cormat.up.melted,
aes(x = Var1,
y = Var2,
fill = value)) +
geom_tile(color = "white")+
scale_fill_gradient2(low = "blue",
high = "red",
mid = "white",
midpoint = 0,
limit = c(-1, 1),
space = "Lab",
name = "Pearson\nCorrelation") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1)) +
coord_fixed()
|
\name{read_indexing_PCR}
\alias{read_idx}
\title{Parsing Indexing PCRs}
\usage{
read_indexing_PCR(ss)
}
\description{
When preparing MiSeq libraries using Nextera indices, I use a Google spreadsheet for adding the samples and the Indetifiers they use.
Use this function to recover all that info
}
\examples{
indexing_ss <- "1iJc7MRdQQH18UPt5tBS13D5ry_s69OZ1cLcD7dntZ3Q"
read_indexing_PCR(indexing_ss)
}
| /man/Read_gsheet.Rd | permissive | ramongallego/eDNA_functions | R | false | false | 405 | rd | \name{read_indexing_PCR}
\alias{read_idx}
\title{Parsing Indexing PCRs}
\usage{
read_indexing_PCR(ss)
}
\description{
When preparing MiSeq libraries using Nextera indices, I use a Google spreadsheet for adding the samples and the Indetifiers they use.
Use this function to recover all that info
}
\examples{
indexing_ss <- "1iJc7MRdQQH18UPt5tBS13D5ry_s69OZ1cLcD7dntZ3Q"
read_indexing_PCR(indexing_ss)
}
|
library(plyr)
library(dplyr)
library(ggplot2)
library(stats4)
library(gridExtra)
setwd("/Users/g-woloschak/Documents/")
BEIR_VII_animal_data <- read.csv('BEIR_VII_animal_data.csv')
data_to_plot <- BEIR_VII_animal_data[BEIR_VII_animal_data$protraction == "Acute" &
!is.na(BEIR_VII_animal_data$risk) &
BEIR_VII_animal_data$dose <=2,]
#create for loop to get likelihood values for range of theta values
likelihood_values <- list()
o_range <- seq(-2, 6, .02)
for(i in 1:length(o_range)){
o<- o_range[i]
model_one_theta <- lm(risk ~ factor(facet) * I(dose+o*dose^2),
data = data_to_plot,
weights = (1/error^2))
likelihood_values[i] <- logLik(model_one_theta)
}
#take list of likelihood values and put in a dataframe
df_10b2 <- data.frame(matrix(unlist(likelihood_values), nrow=length(o_range), byrow=T))
#add theta values to dataframe
df_10b2$theta_values <- o_range
#label columns
colnames(df_10b2) <- c("likelihoods", "thetas")
#find 95% CI
bestloglik <- max(df_10b2$likelihoods, na.rm = TRUE)
minloglik <- bestloglik - qchisq(.95, 1)/2
min(df_10b2[df_10b2$likelihoods >= minloglik,][,2])
max(df_10b2[df_10b2$likelihoods >= minloglik,][,2])
#convert from log likelihood to likelihood
df_10b2$likelihoods <- exp(df_10b2$likelihoods)
#get row number of max likelihood value
row_number <- which(df_10b2$likelihoods == max(df_10b2$likelihoods, na.rm=TRUE))
#use row number to get best theta value
best_theta <- df_10b2[row_number, 2]
#plot profile likelihood
p_10B2 <- ggplot(df_10b2, aes(x=thetas, y = likelihoods)) + geom_point()
##downlaod data for plot 10B-3######################################################
BEIR_VII_10B_3 <- read.csv('BEIR_VII_10B-3_data.csv')
BEIR_VII_10B_3$sem <- BEIR_VII_10B_3$sd / sqrt(BEIR_VII_10B_3$n)
model_data <- BEIR_VII_10B_3[BEIR_VII_10B_3[,6] == "F" &
BEIR_VII_10B_3$dose <= 1.5 &
BEIR_VII_10B_3[,5] == "RFM",]
likelihood_values <- list()
o_range <- seq(-2, 6, .02)
for(i in 1:length(o_range)){
o<- o_range[i]
model3 <- lm(I(1/age) ~ I(dose+o*dose^2*(!model_data$chronic)),
#weights = 1/sem^2,
data = model_data)
likelihood_values[i] <- logLik(model3)
}
#take list of likelihood values and put in a dataframe
df_10B3 <- data.frame(matrix(unlist(likelihood_values), nrow=length(o_range), byrow=T))
#add theta values to dataframe
df_10B3$theta_values <- o_range
#label columns
colnames(df_10B3) <- c("likelihoods", "thetas")
df_10B3$likelihoods <- exp(df_10B3$likelihoods)
#graph theta vs likelihood
p_10B3 <- ggplot(df_10B3, aes(x=thetas, y = likelihoods)) +
geom_point() +
xlab("Possible Values of theta, in Gy-1") +
ylab("Likelihood Value")
p_10B3
#get row number of max likelihood value
row_number <- which(df$likelihoods == max(df_10B3$likelihoods, na.rm=TRUE))
#use row number to get best theta value
best_theta <- df_10B3[row_number, 2]
best_theta
######################## 10-B4 combo ##############################
df_10B4 <- data.frame(theta=df_10b2$thetas,
like_10b2 = df_10b2$likelihoods,
like_10b3 = df_10B3$likelihoods)
#https://en.wikipedia.org/wiki/Normalizing_constant
#http://stats.stackexchange.com/questions/31238/what-is-the-reason-that-a-likelihood-function-is-not-a-pdf#comment60635_31248
#http://cmd.inp.nsk.su/old/cmd2/manuals/cernlib/minuit/node46.html
df_10B4$like_10b2 <- df_10B4$like_10b2/sum(df_10B4$like_10b2)
df_10B4$like_10b3 <- df_10B4$like_10b3/sum(df_10B4$like_10b3)
df_10B4$like_10b4 <- (df_10B4$like_10b2+df_10B4$like_10b3)/2
df_10B4[,2:4] <- df_10B4[,2:4]/max(df_10B4$like_10b2)
p_10B4 <- ggplot(data = df_10B4, aes(x=theta)) +
geom_line(aes(y=like_10b2), colour="red") + # first layer
geom_line(aes(y=like_10b3), colour="green") + # second layer
geom_line(aes(y=like_10b4), colour="blue") + # third layer
xlab("Possible Values of Theta (1/Gy)") +
ylab("Likelihood Value")
p_10B4
row_number <- which(df_10B4$like_10b4 == max(df_10B4$like_10b4, na.rm=TRUE))
best_theta <- df_10B4[row_number, 1]
best_theta
#find 95% CI
loglike_CI <- data.frame(theta = df_10B4$theta, loglike = log(df_10B4$like_10b4))
bestloglik <- max(loglike_CI$loglike, na.rm = TRUE)
minloglik <- bestloglik - qchisq(.95, 1)/2
min(loglike_CI[loglike_CI$loglike >= minloglik,][,1])
max(loglike_CI[loglike_CI$loglike >= minloglik,][,1])
| /BEIR_VII_10-B4.R | no_license | aliazander/Learn_R_and_radiation_models | R | false | false | 4,585 | r | library(plyr)
library(dplyr)
library(ggplot2)
library(stats4)
library(gridExtra)
setwd("/Users/g-woloschak/Documents/")
BEIR_VII_animal_data <- read.csv('BEIR_VII_animal_data.csv')
data_to_plot <- BEIR_VII_animal_data[BEIR_VII_animal_data$protraction == "Acute" &
!is.na(BEIR_VII_animal_data$risk) &
BEIR_VII_animal_data$dose <=2,]
#create for loop to get likelihood values for range of theta values
likelihood_values <- list()
o_range <- seq(-2, 6, .02)
for(i in 1:length(o_range)){
o<- o_range[i]
model_one_theta <- lm(risk ~ factor(facet) * I(dose+o*dose^2),
data = data_to_plot,
weights = (1/error^2))
likelihood_values[i] <- logLik(model_one_theta)
}
#take list of likelihood values and put in a dataframe
df_10b2 <- data.frame(matrix(unlist(likelihood_values), nrow=length(o_range), byrow=T))
#add theta values to dataframe
df_10b2$theta_values <- o_range
#label columns
colnames(df_10b2) <- c("likelihoods", "thetas")
#find 95% CI
bestloglik <- max(df_10b2$likelihoods, na.rm = TRUE)
minloglik <- bestloglik - qchisq(.95, 1)/2
min(df_10b2[df_10b2$likelihoods >= minloglik,][,2])
max(df_10b2[df_10b2$likelihoods >= minloglik,][,2])
#convert from log likelihood to likelihood
df_10b2$likelihoods <- exp(df_10b2$likelihoods)
#get row number of max likelihood value
row_number <- which(df_10b2$likelihoods == max(df_10b2$likelihoods, na.rm=TRUE))
#use row number to get best theta value
best_theta <- df_10b2[row_number, 2]
#plot profile likelihood
p_10B2 <- ggplot(df_10b2, aes(x=thetas, y = likelihoods)) + geom_point()
##downlaod data for plot 10B-3######################################################
BEIR_VII_10B_3 <- read.csv('BEIR_VII_10B-3_data.csv')
BEIR_VII_10B_3$sem <- BEIR_VII_10B_3$sd / sqrt(BEIR_VII_10B_3$n)
model_data <- BEIR_VII_10B_3[BEIR_VII_10B_3[,6] == "F" &
BEIR_VII_10B_3$dose <= 1.5 &
BEIR_VII_10B_3[,5] == "RFM",]
likelihood_values <- list()
o_range <- seq(-2, 6, .02)
for(i in 1:length(o_range)){
o<- o_range[i]
model3 <- lm(I(1/age) ~ I(dose+o*dose^2*(!model_data$chronic)),
#weights = 1/sem^2,
data = model_data)
likelihood_values[i] <- logLik(model3)
}
#take list of likelihood values and put in a dataframe
df_10B3 <- data.frame(matrix(unlist(likelihood_values), nrow=length(o_range), byrow=T))
#add theta values to dataframe
df_10B3$theta_values <- o_range
#label columns
colnames(df_10B3) <- c("likelihoods", "thetas")
df_10B3$likelihoods <- exp(df_10B3$likelihoods)
#graph theta vs likelihood
p_10B3 <- ggplot(df_10B3, aes(x=thetas, y = likelihoods)) +
geom_point() +
xlab("Possible Values of theta, in Gy-1") +
ylab("Likelihood Value")
p_10B3
#get row number of max likelihood value
row_number <- which(df$likelihoods == max(df_10B3$likelihoods, na.rm=TRUE))
#use row number to get best theta value
best_theta <- df_10B3[row_number, 2]
best_theta
######################## 10-B4 combo ##############################
df_10B4 <- data.frame(theta=df_10b2$thetas,
like_10b2 = df_10b2$likelihoods,
like_10b3 = df_10B3$likelihoods)
#https://en.wikipedia.org/wiki/Normalizing_constant
#http://stats.stackexchange.com/questions/31238/what-is-the-reason-that-a-likelihood-function-is-not-a-pdf#comment60635_31248
#http://cmd.inp.nsk.su/old/cmd2/manuals/cernlib/minuit/node46.html
df_10B4$like_10b2 <- df_10B4$like_10b2/sum(df_10B4$like_10b2)
df_10B4$like_10b3 <- df_10B4$like_10b3/sum(df_10B4$like_10b3)
df_10B4$like_10b4 <- (df_10B4$like_10b2+df_10B4$like_10b3)/2
df_10B4[,2:4] <- df_10B4[,2:4]/max(df_10B4$like_10b2)
p_10B4 <- ggplot(data = df_10B4, aes(x=theta)) +
geom_line(aes(y=like_10b2), colour="red") + # first layer
geom_line(aes(y=like_10b3), colour="green") + # second layer
geom_line(aes(y=like_10b4), colour="blue") + # third layer
xlab("Possible Values of Theta (1/Gy)") +
ylab("Likelihood Value")
p_10B4
row_number <- which(df_10B4$like_10b4 == max(df_10B4$like_10b4, na.rm=TRUE))
best_theta <- df_10B4[row_number, 1]
best_theta
#find 95% CI
loglike_CI <- data.frame(theta = df_10B4$theta, loglike = log(df_10B4$like_10b4))
bestloglik <- max(loglike_CI$loglike, na.rm = TRUE)
minloglik <- bestloglik - qchisq(.95, 1)/2
min(loglike_CI[loglike_CI$loglike >= minloglik,][,1])
max(loglike_CI[loglike_CI$loglike >= minloglik,][,1])
|
help("sapply")
help("apply")
help("lapply")
help("c")
## Compute row and column sums for a matrix:
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8]
class(x)
View(x)
# apply(X, MARGIN, FUN, ...)
# MARGIN a vector giving the subscripts which the function will be applied over.
# E.g., for a matrix 1 indicates rows, 2 indicates columns, c(1, 2) indicates rows and columns.
# Where X has named dimnames, it can be a character vector selecting dimension names.
# FUN the function to be applied
apply(x, 2, sum)
apply(x, 2, mean)
apply(x, 1, mean)
apply(x, 1, sum)
#Sum each row and column of the matrix. 1 indicates rows 2 indicates columns.
col.sums <- apply(x, 2, sum)
row.sums <- apply(x, 1, sum)
column_M <- cbind(x, Rtot = row.sums)
View(column_M)
rbind(cbind(x, Rtot = row.sums), Ctot = c(col.sums, sum(col.sums)))
| /R/applysample.R | no_license | kate-kee/R-Analytics-and-visualizations | R | false | false | 851 | r | help("sapply")
help("apply")
help("lapply")
help("c")
## Compute row and column sums for a matrix:
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8]
class(x)
View(x)
# apply(X, MARGIN, FUN, ...)
# MARGIN a vector giving the subscripts which the function will be applied over.
# E.g., for a matrix 1 indicates rows, 2 indicates columns, c(1, 2) indicates rows and columns.
# Where X has named dimnames, it can be a character vector selecting dimension names.
# FUN the function to be applied
apply(x, 2, sum)
apply(x, 2, mean)
apply(x, 1, mean)
apply(x, 1, sum)
#Sum each row and column of the matrix. 1 indicates rows 2 indicates columns.
col.sums <- apply(x, 2, sum)
row.sums <- apply(x, 1, sum)
column_M <- cbind(x, Rtot = row.sums)
View(column_M)
rbind(cbind(x, Rtot = row.sums), Ctot = c(col.sums, sum(col.sums)))
|
# 앞에서 data이름으로 전처리를 마친후에 확인
# 1. 결측치 확인
table(is.na(data$birth))
# 2. birth컬럼을 이용한 age파생변수 생성
data$age <- 2021 - data$birth + 1
data
# 3. 나이에따른 월급평균표
d2 <- data %>%
filter(!is.na(income)) %>%
group_by(round(age,-1)) %>% #10대, 20대....
summarise(mean_income = mean(income))
colnames(d2)[1] <- "mean_age"
ggplot(d2, aes(x = mean_age, y = mean_income, fill = mean_age)) +
geom_col()
# ans----------------------------
data %>%
filter(!is.na(income)) %>%
group_by(age) %>%
summarise(mean_income = mean(income)) %>%
ggplot(aes(x = age, y = mean_income, fill = age)) +
geom_col()
# 연령대에 따른급여 ####
# 1. age를 이용해서 연령대 파생변수 생성
data <- data %>%
mutate(ageg = ifelse(age < 30, "young",
ifelse(age < 60, "middle", "old")))
# 2. 분석처리
d2 <- data %>%
filter(!is.na(income) & !is.na(ageg)) %>%
group_by(ageg) %>%
summarise(mean_income = mean(income))
# 3. 시각화
# reorder는 데이터의 정렬순서, scale_x_discrete 축 정렬순서
ggplot(d2, aes(x = ageg, y = mean_income, fill = ageg)) +
geom_col() +
labs(title = "연령대별 급여평균", x = "연령대", y = "급여평균") +
scale_x_discrete(limits = c("young", "middle", "old")) #x축 순서
# 실습
# 연령대 및 성별에 따른 차이 막대그래프(그룹핑을 2개)
d3 <- data %>%
filter(!is.na(income)) %>%
group_by(ageg, gender) %>%
summarise(mean_income = mean(income))
d3
ggplot(d3, aes(x = ageg, y = mean_income, fill = gender)) +
geom_col(position = "dodge") +
scale_x_discrete(limits = c("young", "middle", "old")) + #x축 순서
labs(title = "연령대 및 성별에 따른 급여평균", x = "연령대", y = "급여평균")
| /basic_r/code/04분석하기/script02(나이에따른급여).R | no_license | jhr1494/R | R | false | false | 1,837 | r | # 앞에서 data이름으로 전처리를 마친후에 확인
# 1. 결측치 확인
table(is.na(data$birth))
# 2. birth컬럼을 이용한 age파생변수 생성
data$age <- 2021 - data$birth + 1
data
# 3. 나이에따른 월급평균표
d2 <- data %>%
filter(!is.na(income)) %>%
group_by(round(age,-1)) %>% #10대, 20대....
summarise(mean_income = mean(income))
colnames(d2)[1] <- "mean_age"
ggplot(d2, aes(x = mean_age, y = mean_income, fill = mean_age)) +
geom_col()
# ans----------------------------
data %>%
filter(!is.na(income)) %>%
group_by(age) %>%
summarise(mean_income = mean(income)) %>%
ggplot(aes(x = age, y = mean_income, fill = age)) +
geom_col()
# 연령대에 따른급여 ####
# 1. age를 이용해서 연령대 파생변수 생성
data <- data %>%
mutate(ageg = ifelse(age < 30, "young",
ifelse(age < 60, "middle", "old")))
# 2. 분석처리
d2 <- data %>%
filter(!is.na(income) & !is.na(ageg)) %>%
group_by(ageg) %>%
summarise(mean_income = mean(income))
# 3. 시각화
# reorder는 데이터의 정렬순서, scale_x_discrete 축 정렬순서
ggplot(d2, aes(x = ageg, y = mean_income, fill = ageg)) +
geom_col() +
labs(title = "연령대별 급여평균", x = "연령대", y = "급여평균") +
scale_x_discrete(limits = c("young", "middle", "old")) #x축 순서
# 실습
# 연령대 및 성별에 따른 차이 막대그래프(그룹핑을 2개)
d3 <- data %>%
filter(!is.na(income)) %>%
group_by(ageg, gender) %>%
summarise(mean_income = mean(income))
d3
ggplot(d3, aes(x = ageg, y = mean_income, fill = gender)) +
geom_col(position = "dodge") +
scale_x_discrete(limits = c("young", "middle", "old")) + #x축 순서
labs(title = "연령대 및 성별에 따른 급여평균", x = "연령대", y = "급여평균")
|
#' Read a file using readr::read_csv suppressing its output
#'
#' This function reads csv files using the read_csv function from readr.
#' Its messages and progress bar is suppressed.
#' Entering a non-existent file
#' while raise an error.
#' @param filename (character) The file to load
#' @return A tbl_df
#' @export
fars_read <- function(filename) {
if(!file.exists(filename))
stop("file '", filename, "' does not exist")
data <- suppressMessages({
readr::read_csv(filename, progress = FALSE)
})
dplyr::tbl_df(data)
}
#' Generate filenames for specific years corresponding to the naming scheme of the FARS
#'
#' This function generates one or more filenames corresponding to the naming scheme of the
#' US National Highway Traffic Safety Administration's Fatality Analysis
#' Reporting System.
#' @param year (numeric) The years for which the respective filenames should be generated
#' @return A character vector of filenames ending in .csv.bz2
#' @examples
#' make_filename(c(2013, 2014))
#' @export
make_filename <- function(year) {
year <- as.integer(year)
sprintf("accident_%d.csv.bz2", year)
}
#' Extract month numbers from FARS files of specific years
#'
#' This function will try to read in standard named FARS files from the
#' working directory using fars_read() and extract the month number of every observation.
#' Years for which no correspondingly named file can be found will raise an error.
#' @param years (numeric) A vector of years for which the month numbers should be returned
#' @return A tbl_df with columns MONTH and year
#' @importFrom dplyr %>%
#' @export
fars_read_years <- function(years) {
lapply(years, function(year) {
file <- make_filename(year)
tryCatch({
dat <- fars_read(file)
dplyr::mutate_(dat, year = ~ year) %>%
dplyr::select_(~ MONTH, ~ year)
}, error = function(e) {
warning("invalid year: ", year)
return(NULL)
})
})
}
#' Get the number of observations per month from a FARS file
#'
#' A FARS file with standard naming is expected to be found in the working
#' directory.
#' @param years (numeric) A vector of years
#' @return A tbl_df with column MONTH and columns corresponding to years with
#' the number of observations per month per year.
#' @importFrom dplyr %>%
#' @export
fars_summarize_years <- function(years) {
dat_list <- fars_read_years(years)
dplyr::bind_rows(dat_list) %>%
dplyr::group_by_(~ year, ~ MONTH) %>%
dplyr::summarize_(n = ~ n()) %>%
tidyr::spread_(key_col = "year", value_col = "n")
}
#' Draw a map of accidents of a specific state during a specific year
#'
#' Not suitable for plotting multiple years or multiple states. FARS files with
#' standard naming are expected to be found in the working directory. States
#' that can not be found in a file or state.num year combinations without
#' accidents will raise errors.
#' @param state.num (numeric) The state number
#' @param year (numeric) The year
#' @return NULL
#' @export
fars_map_state <- function(state.num, year) {
filename <- make_filename(year)
data <- fars_read(filename)
state.num <- as.integer(state.num)
if(!(state.num %in% unique(data$STATE)))
stop("invalid STATE number: ", state.num)
data.sub <- dplyr::filter_(data, ~ STATE == state.num)
if(nrow(data.sub) == 0L) {
message("no accidents to plot")
return(invisible(NULL))
}
is.na(data.sub$LONGITUD) <- data.sub$LONGITUD > 900
is.na(data.sub$LATITUDE) <- data.sub$LATITUDE > 90
with(data.sub, {
maps::map("state", ylim = range(LATITUDE, na.rm = TRUE),
xlim = range(LONGITUD, na.rm = TRUE))
graphics::points(LONGITUD, LATITUDE, pch = 46)
})
}
| /R/fars_functions.R | no_license | pipinho13/fars | R | false | false | 3,980 | r | #' Read a file using readr::read_csv suppressing its output
#'
#' This function reads csv files using the read_csv function from readr.
#' Its messages and progress bar is suppressed.
#' Entering a non-existent file
#' while raise an error.
#' @param filename (character) The file to load
#' @return A tbl_df
#' @export
fars_read <- function(filename) {
if(!file.exists(filename))
stop("file '", filename, "' does not exist")
data <- suppressMessages({
readr::read_csv(filename, progress = FALSE)
})
dplyr::tbl_df(data)
}
#' Generate filenames for specific years corresponding to the naming scheme of the FARS
#'
#' This function generates one or more filenames corresponding to the naming scheme of the
#' US National Highway Traffic Safety Administration's Fatality Analysis
#' Reporting System.
#' @param year (numeric) The years for which the respective filenames should be generated
#' @return A character vector of filenames ending in .csv.bz2
#' @examples
#' make_filename(c(2013, 2014))
#' @export
make_filename <- function(year) {
year <- as.integer(year)
sprintf("accident_%d.csv.bz2", year)
}
#' Extract month numbers from FARS files of specific years
#'
#' This function will try to read in standard named FARS files from the
#' working directory using fars_read() and extract the month number of every observation.
#' Years for which no correspondingly named file can be found will raise an error.
#' @param years (numeric) A vector of years for which the month numbers should be returned
#' @return A tbl_df with columns MONTH and year
#' @importFrom dplyr %>%
#' @export
fars_read_years <- function(years) {
lapply(years, function(year) {
file <- make_filename(year)
tryCatch({
dat <- fars_read(file)
dplyr::mutate_(dat, year = ~ year) %>%
dplyr::select_(~ MONTH, ~ year)
}, error = function(e) {
warning("invalid year: ", year)
return(NULL)
})
})
}
#' Get the number of observations per month from a FARS file
#'
#' A FARS file with standard naming is expected to be found in the working
#' directory.
#' @param years (numeric) A vector of years
#' @return A tbl_df with column MONTH and columns corresponding to years with
#' the number of observations per month per year.
#' @importFrom dplyr %>%
#' @export
fars_summarize_years <- function(years) {
dat_list <- fars_read_years(years)
dplyr::bind_rows(dat_list) %>%
dplyr::group_by_(~ year, ~ MONTH) %>%
dplyr::summarize_(n = ~ n()) %>%
tidyr::spread_(key_col = "year", value_col = "n")
}
#' Draw a map of accidents of a specific state during a specific year
#'
#' Not suitable for plotting multiple years or multiple states. FARS files with
#' standard naming are expected to be found in the working directory. States
#' that can not be found in a file or state.num year combinations without
#' accidents will raise errors.
#' @param state.num (numeric) The state number
#' @param year (numeric) The year
#' @return NULL
#' @export
fars_map_state <- function(state.num, year) {
filename <- make_filename(year)
data <- fars_read(filename)
state.num <- as.integer(state.num)
if(!(state.num %in% unique(data$STATE)))
stop("invalid STATE number: ", state.num)
data.sub <- dplyr::filter_(data, ~ STATE == state.num)
if(nrow(data.sub) == 0L) {
message("no accidents to plot")
return(invisible(NULL))
}
is.na(data.sub$LONGITUD) <- data.sub$LONGITUD > 900
is.na(data.sub$LATITUDE) <- data.sub$LATITUDE > 90
with(data.sub, {
maps::map("state", ylim = range(LATITUDE, na.rm = TRUE),
xlim = range(LONGITUD, na.rm = TRUE))
graphics::points(LONGITUD, LATITUDE, pch = 46)
})
}
|
library(tidyverse)
library(reshape2)
setwd("//chws3092/PPM Admin File/Pricing Product General/Users/Carey C/Coursera/Getting and cleaning data")
# find out which activities we want to keep
activityLabels <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR dataset/activity_labels.txt")
labels <- as.character(activityLabels$V2)
feats <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/features.txt")
features <- as.character(feats$V2)
which_features <- grep(".*mean|.*std.*", features)
# apply filter to get their names
features <- features[which_features]
feature_names <- feats$V2 %>% as.character()
# load in datasets
# train
train <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/train/X_train.txt")[which_features]
train_activities <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/train/Y_train.txt")
train_subjects <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/train/subject_train.txt")
# test
test <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/test/X_test.txt")[which_features]
test_activities <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/test/Y_test.txt")
test_subjects <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/test/subject_test.txt")
# combine
train <- cbind(train, train_activities, train_subjects)
test <- cbind(test, test_activities, test_subjects)
all_data <- rbind(train, test)
colnames(all_data) <- c(feature_names[which_features], "Activity", "Subject")
all_data$Activity <- factor(all_data$Activity, levels = activityLabels[, 1], labels = labels)
all_data$Subject <- as.factor(all_data$Subject)
# tidy up data
all_data_tidy <- all_data %>% melt(id = c("Subject", "Activity"))
all_data_mean <- all_data_tidy %>%
group_by(Subject, Activity, variable) %>%
summarise(Mean = mean(value))
# write the data
write.table(all_data_mean, "tidy_data_mean.txt", row.names = FALSE)
| /run_analysis.R | no_license | Tanvir007/getting-and-cleaning-data-coursera | R | false | false | 1,959 | r | library(tidyverse)
library(reshape2)
setwd("//chws3092/PPM Admin File/Pricing Product General/Users/Carey C/Coursera/Getting and cleaning data")
# find out which activities we want to keep
activityLabels <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR dataset/activity_labels.txt")
labels <- as.character(activityLabels$V2)
feats <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/features.txt")
features <- as.character(feats$V2)
which_features <- grep(".*mean|.*std.*", features)
# apply filter to get their names
features <- features[which_features]
feature_names <- feats$V2 %>% as.character()
# load in datasets
# train
train <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/train/X_train.txt")[which_features]
train_activities <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/train/Y_train.txt")
train_subjects <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/train/subject_train.txt")
# test
test <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/test/X_test.txt")[which_features]
test_activities <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/test/Y_test.txt")
test_subjects <- read.table("getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/test/subject_test.txt")
# combine
train <- cbind(train, train_activities, train_subjects)
test <- cbind(test, test_activities, test_subjects)
all_data <- rbind(train, test)
colnames(all_data) <- c(feature_names[which_features], "Activity", "Subject")
all_data$Activity <- factor(all_data$Activity, levels = activityLabels[, 1], labels = labels)
all_data$Subject <- as.factor(all_data$Subject)
# tidy up data
all_data_tidy <- all_data %>% melt(id = c("Subject", "Activity"))
all_data_mean <- all_data_tidy %>%
group_by(Subject, Activity, variable) %>%
summarise(Mean = mean(value))
# write the data
write.table(all_data_mean, "tidy_data_mean.txt", row.names = FALSE)
|
\name{oligo.estrogen}
\alias{oligo.estrogen}
\docType{data}
\title{The data from the estrogen package as an ExpressionFeatureSet object}
\description{
This data is taken from the \pkg{estrogen} package. It was created to be used in the vignette for the \pkg{puma} pacakge. It can be produced using the following code:
\preformatted{
library(estrogen)
datadir <- file.path(find.package("estrogen"),"extdata")
estrogenFilenames <- c("low10-1.cel","low10-2.cel","high10-1.cel","high10-2.cel"
, "low48-1.cel","low48-2.cel","high48-1.cel","high48-2.cel")
setwd(datadir)
oligo.estrogen <-read.celfiles(
filenames=estrogenFilenames
)
pData(oligo.estrogen) <- data.frame(
"estrogen"=c("absent","absent","present","present"
,"absent","absent","present","present")
, "time.h"=c("10","10","10","10","48","48","48","48")
, row.names=rownames(pData(oligo.estrogen))
)
}
}
\usage{data(oligo.estrogen)}
\format{
An \code{\link[oligoClasses:FeatureSet]{ExpressionFeatureSet}} object containing 8 HG\_U95Av2 arrays, in a 2 x 2 factorial design, with 2 replicates for each combination of factors. The factors are estrogen (absent of present) and time.h (10 or 48).
}
\keyword{datasets}
| /man/oligo.estrogen.Rd | no_license | PUGEA1/pumadata | R | false | false | 1,231 | rd | \name{oligo.estrogen}
\alias{oligo.estrogen}
\docType{data}
\title{The data from the estrogen package as an ExpressionFeatureSet object}
\description{
This data is taken from the \pkg{estrogen} package. It was created to be used in the vignette for the \pkg{puma} pacakge. It can be produced using the following code:
\preformatted{
library(estrogen)
datadir <- file.path(find.package("estrogen"),"extdata")
estrogenFilenames <- c("low10-1.cel","low10-2.cel","high10-1.cel","high10-2.cel"
, "low48-1.cel","low48-2.cel","high48-1.cel","high48-2.cel")
setwd(datadir)
oligo.estrogen <-read.celfiles(
filenames=estrogenFilenames
)
pData(oligo.estrogen) <- data.frame(
"estrogen"=c("absent","absent","present","present"
,"absent","absent","present","present")
, "time.h"=c("10","10","10","10","48","48","48","48")
, row.names=rownames(pData(oligo.estrogen))
)
}
}
\usage{data(oligo.estrogen)}
\format{
An \code{\link[oligoClasses:FeatureSet]{ExpressionFeatureSet}} object containing 8 HG\_U95Av2 arrays, in a 2 x 2 factorial design, with 2 replicates for each combination of factors. The factors are estrogen (absent of present) and time.h (10 or 48).
}
\keyword{datasets}
|
# ------------------------------------------------------------------------
# Create date difference variables for modelling dataset
# ------------------------------------------------------------------------
library(lubridate)
library(tidyverse)
library(zoo)
# Globals -----------------------------------------------------------------
data_dir <- "F:/Projects/Strongbridge/data/modelling/"
output_dir <- "F:/Projects/Strongbridge/data/modelling/"
# Date in -----------------------------------------------------------------
dates_unform <- read_rds(paste0(data_dir, "01_train_combined_dates_unformatted_new_index.rds"))
# Format dates ------------------------------------------------------------
# deal with the 'S_' variables that are in a different format:
S_vars <- dplyr::select(dates_unform, dplyr::starts_with("S_"))
S_vars_format <- as.data.frame(sapply(S_vars, function(x) { ifelse(is.na(x), NA, paste0(x, "01")) }))
S_vars_dates <- as.data.frame(lapply(S_vars_format, ymd))
# add index date column;
S_vars_dates$index_date <- ymd(dates_unform$index_date)
# convert to yearmonths:
S_vars_yearmon <- as.data.frame(sapply(S_vars_dates, as.yearmon))
# create date differences for these variables:
S_date_diffs <- as.data.frame(sapply(select(S_vars_yearmon, -index_date),
function(x) {(S_vars_yearmon$index_date - x)*12}))
# convert 'D' G' and 'P' variables to correct format
dates_form <- date_format(input_data = dates_unform,
date_pattern = "_EXP_DT",
PATIENT_ID_col = "PATIENT_ID")
# add index date column for creation of date diffs
dates_form$index_date <- ymd(dates_unform$index_date)
# create date difference columns
date_differences <- create_date_diffs(input = dates_form[,2:ncol(dates_form)],
index_col = "index_date")
# add necessary columns
date_diffs_combined <- data.frame(dates_unform[,1:5],
date_differences,
S_date_diffs)
# prop missing
length(date_diffs_combined[is.na(date_diffs_combined[,6:ncol(date_diffs_combined)])])/((ncol(date_diffs_combined)-6) * nrow(date_diffs_combined))
write_rds(date_diffs_combined, paste0(output_dir, "01_train_combined_date_differences_new_index.rds"))
r
# FUNCTIONS ---------------------------------------------------------------
# convert date format:
date_format <- function(input_data, date_pattern, PATIENT_ID_col) {
date_data <- dplyr::select(input_data, dplyr::contains(date_pattern))
formatted <- lapply(date_data, mdy)
df_date <- as.data.frame(formatted)
df <- data.frame(PATIENT_ID = input_data[PATIENT_ID_col],
df_date
)
return(df)
}
# please input only a dataframe full of dates into this function:
create_date_diffs <- function(input, index_col = "index_date") {
date_cols <- input[, -which(colnames(input) == index_col)]
date_diffs <- as.data.frame(sapply(date_cols, function(x) {
input[[index_col]] - x
}))
return(date_diffs)
}
| /pre_modelling/03_create_training_date_diffs.R | no_license | jzhao0802/strongbridge | R | false | false | 3,079 | r |
# ------------------------------------------------------------------------
# Create date difference variables for modelling dataset
# ------------------------------------------------------------------------
library(lubridate)
library(tidyverse)
library(zoo)
# Globals -----------------------------------------------------------------
data_dir <- "F:/Projects/Strongbridge/data/modelling/"
output_dir <- "F:/Projects/Strongbridge/data/modelling/"
# Date in -----------------------------------------------------------------
dates_unform <- read_rds(paste0(data_dir, "01_train_combined_dates_unformatted_new_index.rds"))
# Format dates ------------------------------------------------------------
# deal with the 'S_' variables that are in a different format:
S_vars <- dplyr::select(dates_unform, dplyr::starts_with("S_"))
S_vars_format <- as.data.frame(sapply(S_vars, function(x) { ifelse(is.na(x), NA, paste0(x, "01")) }))
S_vars_dates <- as.data.frame(lapply(S_vars_format, ymd))
# add index date column;
S_vars_dates$index_date <- ymd(dates_unform$index_date)
# convert to yearmonths:
S_vars_yearmon <- as.data.frame(sapply(S_vars_dates, as.yearmon))
# create date differences for these variables:
S_date_diffs <- as.data.frame(sapply(select(S_vars_yearmon, -index_date),
function(x) {(S_vars_yearmon$index_date - x)*12}))
# convert 'D' G' and 'P' variables to correct format
dates_form <- date_format(input_data = dates_unform,
date_pattern = "_EXP_DT",
PATIENT_ID_col = "PATIENT_ID")
# add index date column for creation of date diffs
dates_form$index_date <- ymd(dates_unform$index_date)
# create date difference columns
date_differences <- create_date_diffs(input = dates_form[,2:ncol(dates_form)],
index_col = "index_date")
# add necessary columns
date_diffs_combined <- data.frame(dates_unform[,1:5],
date_differences,
S_date_diffs)
# prop missing
length(date_diffs_combined[is.na(date_diffs_combined[,6:ncol(date_diffs_combined)])])/((ncol(date_diffs_combined)-6) * nrow(date_diffs_combined))
write_rds(date_diffs_combined, paste0(output_dir, "01_train_combined_date_differences_new_index.rds"))
r
# FUNCTIONS ---------------------------------------------------------------
# convert date format:
date_format <- function(input_data, date_pattern, PATIENT_ID_col) {
date_data <- dplyr::select(input_data, dplyr::contains(date_pattern))
formatted <- lapply(date_data, mdy)
df_date <- as.data.frame(formatted)
df <- data.frame(PATIENT_ID = input_data[PATIENT_ID_col],
df_date
)
return(df)
}
# please input only a dataframe full of dates into this function:
create_date_diffs <- function(input, index_col = "index_date") {
date_cols <- input[, -which(colnames(input) == index_col)]
date_diffs <- as.data.frame(sapply(date_cols, function(x) {
input[[index_col]] - x
}))
return(date_diffs)
}
|
/WhatIsCooking.R | no_license | CNJDS-Whats-Cooking/Team-2 | R | false | false | 126,220 | r | ||
c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 1120
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 1034
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 1034
c
c Input Parameter (command line, file):
c input filename QBFLIB/Herbstritt/blackbox-01X-QBF/biu.mv.xl_ao.bb-b003-p020-IPF03-c03.blif-biu.inv.prop.bb-bmc.conf05.01X-QBF.BB1-Zi.BB2-01X.BB3-Zi.with-IOC.unfold-001.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 1508
c no.of clauses 1120
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 1034
c
c QBFLIB/Herbstritt/blackbox-01X-QBF/biu.mv.xl_ao.bb-b003-p020-IPF03-c03.blif-biu.inv.prop.bb-bmc.conf05.01X-QBF.BB1-Zi.BB2-01X.BB3-Zi.with-IOC.unfold-001.qdimacs 1508 1120 E1 [1065 1067 1069 1071 1073 1075 1077 1079 1081 1083 1085 1087 1089 1091 1093 1095 1097 1101 1108 1109 1110 1111 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1143 1145 1147 1149 1151 1153 1155 1157 1171] 0 10 415 1034 RED
| /code/dcnf-ankit-optimized/Results/QBFLIB-2018/E1/Experiments/Herbstritt/blackbox-01X-QBF/biu.mv.xl_ao.bb-b003-p020-IPF03-c03.blif-biu.inv.prop.bb-bmc.conf05.01X-QBF.BB1-Zi.BB2-01X.BB3-Zi.with-IOC.unfold-001/biu.mv.xl_ao.bb-b003-p020-IPF03-c03.blif-biu.inv.prop.bb-bmc.conf05.01X-QBF.BB1-Zi.BB2-01X.BB3-Zi.with-IOC.unfold-001.R | no_license | arey0pushpa/dcnf-autarky | R | false | false | 1,230 | r | c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 1120
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 1034
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 1034
c
c Input Parameter (command line, file):
c input filename QBFLIB/Herbstritt/blackbox-01X-QBF/biu.mv.xl_ao.bb-b003-p020-IPF03-c03.blif-biu.inv.prop.bb-bmc.conf05.01X-QBF.BB1-Zi.BB2-01X.BB3-Zi.with-IOC.unfold-001.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 1508
c no.of clauses 1120
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 1034
c
c QBFLIB/Herbstritt/blackbox-01X-QBF/biu.mv.xl_ao.bb-b003-p020-IPF03-c03.blif-biu.inv.prop.bb-bmc.conf05.01X-QBF.BB1-Zi.BB2-01X.BB3-Zi.with-IOC.unfold-001.qdimacs 1508 1120 E1 [1065 1067 1069 1071 1073 1075 1077 1079 1081 1083 1085 1087 1089 1091 1093 1095 1097 1101 1108 1109 1110 1111 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1143 1145 1147 1149 1151 1153 1155 1157 1171] 0 10 415 1034 RED
|
library(randomForest)
# Loading data
word = read.csv("word_matrix.csv") # last column is "y"
power = read.csv("power_matrix.csv")
filenames = word[,1]
word = word[,-c(1,2)]
power = power[,-1]
word$y = as.factor(word$y)
power$y = as.factor(power$y)
combine = cbind(word[,-ncol(word)], power)
# Classification on the filtered Word Feature Matrix
# parameters to be tuned: mtry, ntree
set.seed(1)
k=10
fold=sample(1:k, nrow(word), replace=TRUE)
ntree = seq(100,2500,100)
# cross validation on word
mtry = c(seq(50,ncol(word), 100), ncol(word))
parameters = expand.grid(ntree, mtry)
colnames(parameters) = c("ntree","mtry")
cv.acc.word = matrix(NA,k,nrow(parameters))
for (i in 1:k){
train = word[fold!=i,]
test = word[fold==i,]
test.y = word$y[fold==i]
for (j in 1:nrow(parameters)){
rf.word = randomForest(y~., data=train, ntree=parameters[j,1],
mtry=parameters[j,2])
rf.pred= predict(rf.word, newdata=test,type="class")
confusion.matrix = table(rf.pred, test.y)
cv.acc.word[i,j] = (confusion.matrix[1,1]+confusion.matrix[2,2]+
confusion.matrix[3,3]+confusion.matrix[4,4])/sum(confusion.matrix)
}
}
# cross validation on power
mtry2 = c(seq(50,ncol(power), 100), ncol(power))
parameters2 = expand.grid(ntree, mtry2)
colnames(parameters2) = c("ntree","mtry")
cv.acc.power = matrix(NA,k,nrow(parameters2))
for (i in 1:k){
train = power[fold!=i,]
test = power[fold==i,]
test.y = power$y[fold==i]
for (j in 1:nrow(parameters2)){
rf.power = randomForest(y~., data=train, ntree=parameters2[j,1],
mtry=parameters2[j,2])
rf.pred= predict(rf.power, newdata=test,type="class")
confusion.matrix = table(rf.pred, test.y)
cv.acc.power[i,j] = (confusion.matrix[1,1]+confusion.matrix[2,2]+
confusion.matrix[3,3]+confusion.matrix[4,4])/sum(confusion.matrix)
}
}
# cross validation on combination
mtry3 = c(seq(50,ncol(combine), 100), ncol(combine))
parameters3 = expand.grid(ntree, mtry3)
colnames(parameters3) = c("ntree","mtry")
cv.acc.combine = matrix(NA,k,nrow(parameters3))
for (i in 1:k){
train = combine[fold!=i,]
test = combine[fold==i,]
test.y = combine$y[fold==i]
for (j in 1:nrow(parameters3)){
rf.combine = randomForest(y~., data=train, ntree=parameters3[j,1],
mtry=parameters3[j,2])
rf.pred= predict(rf.combine, newdata=test,type="class")
confusion.matrix = table(rf.pred, test.y)
cv.acc.combine[i,j] = (confusion.matrix[1,1]+confusion.matrix[2,2]+
confusion.matrix[3,3]+confusion.matrix[4,4])/sum(confusion.matrix)
}
}
| /random_forest.R | no_license | Jay4869/STAT-154 | R | false | false | 2,660 | r | library(randomForest)
# Loading data
word = read.csv("word_matrix.csv") # last column is "y"
power = read.csv("power_matrix.csv")
filenames = word[,1]
word = word[,-c(1,2)]
power = power[,-1]
word$y = as.factor(word$y)
power$y = as.factor(power$y)
combine = cbind(word[,-ncol(word)], power)
# Classification on the filtered Word Feature Matrix
# parameters to be tuned: mtry, ntree
set.seed(1)
k=10
fold=sample(1:k, nrow(word), replace=TRUE)
ntree = seq(100,2500,100)
# cross validation on word
mtry = c(seq(50,ncol(word), 100), ncol(word))
parameters = expand.grid(ntree, mtry)
colnames(parameters) = c("ntree","mtry")
cv.acc.word = matrix(NA,k,nrow(parameters))
for (i in 1:k){
train = word[fold!=i,]
test = word[fold==i,]
test.y = word$y[fold==i]
for (j in 1:nrow(parameters)){
rf.word = randomForest(y~., data=train, ntree=parameters[j,1],
mtry=parameters[j,2])
rf.pred= predict(rf.word, newdata=test,type="class")
confusion.matrix = table(rf.pred, test.y)
cv.acc.word[i,j] = (confusion.matrix[1,1]+confusion.matrix[2,2]+
confusion.matrix[3,3]+confusion.matrix[4,4])/sum(confusion.matrix)
}
}
# cross validation on power
mtry2 = c(seq(50,ncol(power), 100), ncol(power))
parameters2 = expand.grid(ntree, mtry2)
colnames(parameters2) = c("ntree","mtry")
cv.acc.power = matrix(NA,k,nrow(parameters2))
for (i in 1:k){
train = power[fold!=i,]
test = power[fold==i,]
test.y = power$y[fold==i]
for (j in 1:nrow(parameters2)){
rf.power = randomForest(y~., data=train, ntree=parameters2[j,1],
mtry=parameters2[j,2])
rf.pred= predict(rf.power, newdata=test,type="class")
confusion.matrix = table(rf.pred, test.y)
cv.acc.power[i,j] = (confusion.matrix[1,1]+confusion.matrix[2,2]+
confusion.matrix[3,3]+confusion.matrix[4,4])/sum(confusion.matrix)
}
}
# cross validation on combination
mtry3 = c(seq(50,ncol(combine), 100), ncol(combine))
parameters3 = expand.grid(ntree, mtry3)
colnames(parameters3) = c("ntree","mtry")
cv.acc.combine = matrix(NA,k,nrow(parameters3))
for (i in 1:k){
train = combine[fold!=i,]
test = combine[fold==i,]
test.y = combine$y[fold==i]
for (j in 1:nrow(parameters3)){
rf.combine = randomForest(y~., data=train, ntree=parameters3[j,1],
mtry=parameters3[j,2])
rf.pred= predict(rf.combine, newdata=test,type="class")
confusion.matrix = table(rf.pred, test.y)
cv.acc.combine[i,j] = (confusion.matrix[1,1]+confusion.matrix[2,2]+
confusion.matrix[3,3]+confusion.matrix[4,4])/sum(confusion.matrix)
}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/generate.R
\name{generate}
\alias{generate}
\title{R2RESUME: Converts Rmarkdown to Beautiful Resume Sites}
\usage{
generate(
template = "manzana",
self_contained = FALSE,
dir_lib = "site_libs",
css = "style.css",
...
)
}
\arguments{
\item{template}{Optional but probably the most important config. Declare a template name
for the final look of your resume site. The options include:
manzana, limon, circuela, anana, naranja}
\item{self_contained}{Optional. Takes input of \code{TRUE} or \code{FALSE}(default). Here, TRUE
indicates that all output will be compiled into one single file. FALSE means a library
folder will be generated. This is most important for rendering multiple pages simultaneously
so that all pages only refer to the library as supposed to containing the full libraries
within them.}
\item{dir_lib}{Optional directory name where scripts are to be stored. By default
this is set to site_libs.}
\item{css}{Optional stlysheet name for further beautification of the resume site.
Set by default to style.css. You may edit that file and its automatically reflected in
the final outlook of your resume site.}
\item{...}{Optional. Additional prarmeters for declaration in html_document}
}
\description{
See the \href{https://www.r2resume.com}{Official R2RESUME
website} for additional details on using the \code{generate}
function.
}
\details{
There is nothing extremely fancy about \code{generate},
it practically provides a shortcut to calling the already known
\code{rmarkdown::render_site} function with predefined arguments so that
the user does not have to spend time doing it.
}
\section{Usage and constituents}{
You may \code{generate} resume as a single page or a group of pages as a website.
The same declaration as is used in html_document rendering applies here, where for \emph{a single page}
\preformatted{ - include the call in the top portion of your page in the
yml section. An example of this is shown below.}
For \emph{multiple pages}, as you may see in the examples provided with the \code{r2resume::loadExamples} function,
you need to have an \emph{_site.yml} file and an \emph{index.Rmd}. The latter file should basically be one of your
resume pages, other pages may be named differently, but this naming convention does not affect the content
you choose to have in the files. \emph{_site.yml} is where the options are declared. See below for an example.
After creating your pages, use the \code{rmarkdown::render('index.Rmd')} to build single page resume and
\code{rmarkdown::render_site('.')} to simulaneously build your multiple page resume site.
}
\examples{
\dontrun{
generate(self_contained = TRUE)
}
}
| /man/generate.Rd | no_license | oobianom/r2resume | R | false | true | 2,754 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/generate.R
\name{generate}
\alias{generate}
\title{R2RESUME: Converts Rmarkdown to Beautiful Resume Sites}
\usage{
generate(
template = "manzana",
self_contained = FALSE,
dir_lib = "site_libs",
css = "style.css",
...
)
}
\arguments{
\item{template}{Optional but probably the most important config. Declare a template name
for the final look of your resume site. The options include:
manzana, limon, circuela, anana, naranja}
\item{self_contained}{Optional. Takes input of \code{TRUE} or \code{FALSE}(default). Here, TRUE
indicates that all output will be compiled into one single file. FALSE means a library
folder will be generated. This is most important for rendering multiple pages simultaneously
so that all pages only refer to the library as supposed to containing the full libraries
within them.}
\item{dir_lib}{Optional directory name where scripts are to be stored. By default
this is set to site_libs.}
\item{css}{Optional stlysheet name for further beautification of the resume site.
Set by default to style.css. You may edit that file and its automatically reflected in
the final outlook of your resume site.}
\item{...}{Optional. Additional prarmeters for declaration in html_document}
}
\description{
See the \href{https://www.r2resume.com}{Official R2RESUME
website} for additional details on using the \code{generate}
function.
}
\details{
There is nothing extremely fancy about \code{generate},
it practically provides a shortcut to calling the already known
\code{rmarkdown::render_site} function with predefined arguments so that
the user does not have to spend time doing it.
}
\section{Usage and constituents}{
You may \code{generate} resume as a single page or a group of pages as a website.
The same declaration as is used in html_document rendering applies here, where for \emph{a single page}
\preformatted{ - include the call in the top portion of your page in the
yml section. An example of this is shown below.}
For \emph{multiple pages}, as you may see in the examples provided with the \code{r2resume::loadExamples} function,
you need to have an \emph{_site.yml} file and an \emph{index.Rmd}. The latter file should basically be one of your
resume pages, other pages may be named differently, but this naming convention does not affect the content
you choose to have in the files. \emph{_site.yml} is where the options are declared. See below for an example.
After creating your pages, use the \code{rmarkdown::render('index.Rmd')} to build single page resume and
\code{rmarkdown::render_site('.')} to simulaneously build your multiple page resume site.
}
\examples{
\dontrun{
generate(self_contained = TRUE)
}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/grain.R
\name{plot.grain}
\alias{plot.grain}
\title{Title}
\usage{
\method{plot}{grain}(x, show = c("centre", "corner"))
}
\arguments{
\item{show}{}
}
\value{
}
\description{
Title
}
| /man/plot.grain.Rd | no_license | hypertidy/granulated | R | false | true | 262 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/grain.R
\name{plot.grain}
\alias{plot.grain}
\title{Title}
\usage{
\method{plot}{grain}(x, show = c("centre", "corner"))
}
\arguments{
\item{show}{}
}
\value{
}
\description{
Title
}
|
library(NHANES)
library(tidyverse)
# This dataset is from on the National Health and Nutrition Examination Survey
# (NHANES), a program designed to assess the health status of adults and children
# in the United States. It is conducted yearly by a suborganization of the CDC,
# and involves both interviews and physical examinations of participants. The raw
# data can be accessed through their R package, details about the study can be
# found at https://www.cdc.gov/nchs/nhanes/index.htm.
# Loading the data and selecting the variables to be used. The dataset includes
# more than 70 variables, so there are many more potentially useful variables
# than we could possibly include. The ones below are some of the more well known
# measures that are relatively easy to interpret.
x <- NHANES %>%
select(SurveyYr, Gender, Age,
Race1, Education, HHIncome,
Weight, Height, BMI, Pulse,
Diabetes, HealthGen, Depressed,
nPregnancies, SleepHrsNight) %>%
# Recoding 'SurveyYr' by converting it to a new variable name 'survey'.
# This variable only includes the first year, the second year is dropped. For
# example, "2011_12" will just be represented as "2011". This may not be
# totally correct, but it eases further analyses while creating only minor
# distortions (it's unlikely that people's health status changes a lot within
# half a year).
separate(SurveyYr, into = c("survey", NA),
sep = "_") %>%
# Converting the new 'survey' variable to an integer.
mutate(survey = as.integer(survey)) %>%
# Recoding some levels of 'Education' and converting it to
# an ordered factor.
mutate(Education = as.ordered(case_when(
Education == "8th Grade" ~ "Middle School",
Education == "9 - 11th Grade" ~ "Middle School",
Education == "High School" ~ "High School",
Education == "Some College" ~ "Some College",
Education == "College Grade" ~ "College"))) %>%
# Recoding some values of 'HHIncome' and converting it to an
# ordered factor. Having ranges instead of single values looks
# ugly, but this is still the best solution.
# There are two other options to deal with this variable, but
# both of them come with a problem. The first option to the
# below approach would be to recode the ranges as numbers, with
# the first group being "1" and the second group being "2", etc.
# However, this could imply a linear relationship between numbers
# and and ranges of each group, which would be wrong (e.g. the
# first group covers a range of 5k, the last group a range of 25k).
# The second option would be to use 'HHIncomeMid' variable in the
# dataset, which uses the median/mean of each group's range instead
# of the range itself. However, unless peoples' incomes in each
# group follow a normal or equal distribution that is centered
# around the mean/median of the respective range, this would lead
# to distortions. For example, it makes little sense to assume that
# the average income of all people in the group "75000-99999" is
# equal to this ranges' median of 87500. Instead, we would expect
# much fewer observations at the upper range, leading to a value that
# may not even be close to 87500.
mutate(HHIncome = as.ordered(case_when(
HHIncome == "more 99999" ~ "over 99999",
HHIncome == "75000-99999" ~ "75000-99999",
HHIncome == "65000-74999" ~ "65000-74999",
HHIncome == "55000-64999" ~ "55000-64999",
HHIncome == "45000-54999" ~ "45000-54999",
HHIncome == "35000-44999" ~ "35000-44999",
HHIncome == "25000-34999" ~ "25000-34999",
HHIncome == "20000-24999" ~ "20000-24999",
HHIncome == "15000-19999" ~ "15000-19999",
HHIncome == "10000-14999" ~ "10000-14999",
HHIncome == " 5000-9999" ~ "5000-9999",
HHIncome == " 0-4999" ~ "0-4999"))) %>%
# Converting 'HealthGen' to a numbered variable. Although it
# may again be problematic to assume a linear relationship
# between each of the five responses, this approach seems
# appropriate here. Keep in mind that these exact responses
# were offered by the researchers after asking people for their
# general health conditions. This is pretty close to a question
# of the form "On a scale of 1 to 5, and 5 being best, how well
# do you feel?".
mutate(HealthGen = as.integer(case_when(
HealthGen == "Poor" ~ 1,
HealthGen == "Fair" ~ 2,
HealthGen == "Good" ~ 3,
HealthGen == "Vgood" ~ 4,
HealthGen == "Excellent" ~ 5))) %>%
# Converting 'Depressed' to an ordered factor.
mutate(Depressed = as.ordered(Depressed)) %>%
# Converting 'Diabetes' to an integer variable.
mutate(Diabetes = as.integer(case_when(
Diabetes == "Yes" ~ 1,
Diabetes == "No" ~ 0))) %>%
# No factors unless it's necessary.
mutate(Gender = as.character(Gender),
Race1 = as.character(Race1)) %>%
# Capitalizing values of 'Gender'.
mutate(Gender = str_to_title(Gender)) %>%
# Renaming variables.
rename(gender = "Gender",
age = "Age",
race = "Race1",
education = "Education",
hh_income = "HHIncome",
weight = "Weight",
height = "Height",
bmi = "BMI",
pulse = "Pulse",
diabetes = "Diabetes",
general_health = "HealthGen",
depressed = "Depressed",
pregnancies = "nPregnancies",
sleep = "SleepHrsNight")
# Check and save.
stopifnot(nrow(x) == 10000)
stopifnot(ncol(x) > 10)
stopifnot(ncol(x) < 16)
stopifnot(is.integer(x$age))
stopifnot(is.character(x$race))
stopifnot(sum(is.na(x$depressed)) < 5000)
nhanes <- x
usethis::use_data(nhanes, overwrite = TRUE)
| /data-raw/make_nhanes.R | permissive | shealynj/PPBDS.data | R | false | false | 5,707 | r |
library(NHANES)
library(tidyverse)
# This dataset is from on the National Health and Nutrition Examination Survey
# (NHANES), a program designed to assess the health status of adults and children
# in the United States. It is conducted yearly by a suborganization of the CDC,
# and involves both interviews and physical examinations of participants. The raw
# data can be accessed through their R package, details about the study can be
# found at https://www.cdc.gov/nchs/nhanes/index.htm.
# Loading the data and selecting the variables to be used. The dataset includes
# more than 70 variables, so there are many more potentially useful variables
# than we could possibly include. The ones below are some of the more well known
# measures that are relatively easy to interpret.
x <- NHANES %>%
select(SurveyYr, Gender, Age,
Race1, Education, HHIncome,
Weight, Height, BMI, Pulse,
Diabetes, HealthGen, Depressed,
nPregnancies, SleepHrsNight) %>%
# Recoding 'SurveyYr' by converting it to a new variable name 'survey'.
# This variable only includes the first year, the second year is dropped. For
# example, "2011_12" will just be represented as "2011". This may not be
# totally correct, but it eases further analyses while creating only minor
# distortions (it's unlikely that people's health status changes a lot within
# half a year).
separate(SurveyYr, into = c("survey", NA),
sep = "_") %>%
# Converting the new 'survey' variable to an integer.
mutate(survey = as.integer(survey)) %>%
# Recoding some levels of 'Education' and converting it to
# an ordered factor.
mutate(Education = as.ordered(case_when(
Education == "8th Grade" ~ "Middle School",
Education == "9 - 11th Grade" ~ "Middle School",
Education == "High School" ~ "High School",
Education == "Some College" ~ "Some College",
Education == "College Grade" ~ "College"))) %>%
# Recoding some values of 'HHIncome' and converting it to an
# ordered factor. Having ranges instead of single values looks
# ugly, but this is still the best solution.
# There are two other options to deal with this variable, but
# both of them come with a problem. The first option to the
# below approach would be to recode the ranges as numbers, with
# the first group being "1" and the second group being "2", etc.
# However, this could imply a linear relationship between numbers
# and and ranges of each group, which would be wrong (e.g. the
# first group covers a range of 5k, the last group a range of 25k).
# The second option would be to use 'HHIncomeMid' variable in the
# dataset, which uses the median/mean of each group's range instead
# of the range itself. However, unless peoples' incomes in each
# group follow a normal or equal distribution that is centered
# around the mean/median of the respective range, this would lead
# to distortions. For example, it makes little sense to assume that
# the average income of all people in the group "75000-99999" is
# equal to this ranges' median of 87500. Instead, we would expect
# much fewer observations at the upper range, leading to a value that
# may not even be close to 87500.
mutate(HHIncome = as.ordered(case_when(
HHIncome == "more 99999" ~ "over 99999",
HHIncome == "75000-99999" ~ "75000-99999",
HHIncome == "65000-74999" ~ "65000-74999",
HHIncome == "55000-64999" ~ "55000-64999",
HHIncome == "45000-54999" ~ "45000-54999",
HHIncome == "35000-44999" ~ "35000-44999",
HHIncome == "25000-34999" ~ "25000-34999",
HHIncome == "20000-24999" ~ "20000-24999",
HHIncome == "15000-19999" ~ "15000-19999",
HHIncome == "10000-14999" ~ "10000-14999",
HHIncome == " 5000-9999" ~ "5000-9999",
HHIncome == " 0-4999" ~ "0-4999"))) %>%
# Converting 'HealthGen' to a numbered variable. Although it
# may again be problematic to assume a linear relationship
# between each of the five responses, this approach seems
# appropriate here. Keep in mind that these exact responses
# were offered by the researchers after asking people for their
# general health conditions. This is pretty close to a question
# of the form "On a scale of 1 to 5, and 5 being best, how well
# do you feel?".
mutate(HealthGen = as.integer(case_when(
HealthGen == "Poor" ~ 1,
HealthGen == "Fair" ~ 2,
HealthGen == "Good" ~ 3,
HealthGen == "Vgood" ~ 4,
HealthGen == "Excellent" ~ 5))) %>%
# Converting 'Depressed' to an ordered factor.
mutate(Depressed = as.ordered(Depressed)) %>%
# Converting 'Diabetes' to an integer variable.
mutate(Diabetes = as.integer(case_when(
Diabetes == "Yes" ~ 1,
Diabetes == "No" ~ 0))) %>%
# No factors unless it's necessary.
mutate(Gender = as.character(Gender),
Race1 = as.character(Race1)) %>%
# Capitalizing values of 'Gender'.
mutate(Gender = str_to_title(Gender)) %>%
# Renaming variables.
rename(gender = "Gender",
age = "Age",
race = "Race1",
education = "Education",
hh_income = "HHIncome",
weight = "Weight",
height = "Height",
bmi = "BMI",
pulse = "Pulse",
diabetes = "Diabetes",
general_health = "HealthGen",
depressed = "Depressed",
pregnancies = "nPregnancies",
sleep = "SleepHrsNight")
# Check and save.
stopifnot(nrow(x) == 10000)
stopifnot(ncol(x) > 10)
stopifnot(ncol(x) < 16)
stopifnot(is.integer(x$age))
stopifnot(is.character(x$race))
stopifnot(sum(is.na(x$depressed)) < 5000)
nhanes <- x
usethis::use_data(nhanes, overwrite = TRUE)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/primendoR.R
\docType{data}
\name{primendoR}
\alias{primendoR}
\title{example dataset}
\usage{
data(primendoR)
}
\description{
right brain hemisphere of 19 primate species
}
\author{
Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
}
\keyword{Arothron}
| /man/primendoR.Rd | no_license | cran/Arothron | R | false | true | 380 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/primendoR.R
\docType{data}
\name{primendoR}
\alias{primendoR}
\title{example dataset}
\usage{
data(primendoR)
}
\description{
right brain hemisphere of 19 primate species
}
\author{
Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
}
\keyword{Arothron}
|
## ----rosenbroeck---------------------------------------------------------
mountains <- function(v) {
(1 - v[1])^2 + 100 * (v[2] - v[1]*v[1])^2 +
0.3*(0.2 - 2*v[2])^2 + 100 * (v[1] - v[2]*v[2])^2 -
0.5*(v[1]^2 +5*v[2]^2)
}
## ---- eval=FALSE---------------------------------------------------------
## library("animation")
## grad.desc()
## ---- eval=FALSE---------------------------------------------------------
## ani.options(nmax = 70)
## par(mar = c(4, 4, 2, 0.1))
## f2 = function(x, y) sin(1/2 * x^2 - 1/4 * y^2 + 3) * cos(2 * x + 1 -
## exp(y))
## grad.desc(f2, c(-2, -2, 2, 2), c(-1, 0.5), gamma = 0.3, tol = 1e-04)
## ----B05113_05_02--------------------------------------------------------
n <- 300
## to define a grid
x <- seq(-1, 2, length.out = n)
y <- seq(-1, 2, length.out = n)
## evaluate on each grid point
z <- mountains(expand.grid(x, y))
## contour plot
par(mar = c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)),
xlab = "x", ylab = "y", nlevels = 20)
## starting value
sta <- c(0.5,-1)
points(sta[1], sta[2], cex = 2, pch = 20)
## solutions for each of 20 steps
sol <- matrix(, ncol=2, nrow = 21)
sol[1, ] <- sta
for(i in 2:20){
sol[i, ] <- nlm(mountains, sta, iterlim = i)$est
}
## optimal solution
sol[21, ] <- nlm(mountains, sta)$est
points(sol[21, 1], sol[21, 2], cex = 3, col = "red", pch = 20)
## path visually
lines(sol, pch=3, type="o")
## now let's start better (dashed line)
sta <- c(0,-1)
for(i in 2:20){
sol[i, ] <- nlm(mountains, sta, iterlim = i)$est
}
sol[1, ] <- sta
sol[21, ] <- nlm(mountains, sta)$est
points(sta[1], sta[2], cex = 2, pch = 20)
points(sol[21, 1], sol[21, 2], cex = 3, col = "red", pch = 20)
lines(sol, pch=3, type="o")
## ----B05113_05_03, cache=FALSE-------------------------------------------
## wrapper for all methods of optim
optims <- function(x, meth = "Nelder-Mead", start = c(0.5, -1)){
sol <- matrix(, ncol = 2, nrow = 21)
sol[1, ] <- start
for(i in 2:20){
sol[i, ] <- optim(start, mountains, method = meth,
control = list(maxit=i))$par
}
sol[21,] <- optim(start, mountains)$par
points(start[1], start[2], pch=20, cex = 2)
points(sol[21, ], sol[21, ], pch = 20, col = "red", cex = 3)
lines(sol[, 1], sol[, 2], type = "o", pch = 3)
}
## plot lines for all methods
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
optims() # Nelder-Mead
optims("BFGS")
optims("CG")
optims("L-BFGS-B")
optims("SANN")
optims("Brent")
optims(start = c(1.5,0.5))
## ----B05113_05_04, cache=TRUE--------------------------------------------
## define grid
n <- 1500
set.seed(1234567)
x1 <- runif(n, min = -2, max = 5)
y1 <- runif(n, min = -2, max = 5)
z1 <- matrix(, ncol = n, nrow = n)
## evaluate on each grid point
for(i in 1:n){
for(j in 1:n){
z1[i,j] <- mountains(c(x1[i], y1[j]))
}
}
## determine optima
w <- which(z1 == min(z1), arr.ind=TRUE)
## plot results
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
points(x1[w[1]], y1[w[2]], pch = 20, col = "red", cex = 3)
points(x1, y1, pch=3)
## ----B05113_05_05, cache=TRUE--------------------------------------------
library("RCEIM")
set.seed(123)
sol <- best <- list()
## save solution for each step
for(i in 2:20){
a <- ceimOpt(mountains, nParam = 2, maxIter = i)
sol[[i]] <- a$EliteMembers
best[[i]] <- a$BestMember
}
## plot the results for each step
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
greys <- grey(rev(2:20 / 20 - 0.099))
for(i in 2:20){
points(sol[[i]][,1], sol[[i]][,2], col = greys[i])
points(best[[i]][1], best[[i]][2], col = "red", pch = 3)
}
points(best[[i]][1], best[[i]][2], col = "red", pch = 20, cex = 3)
## ----randomwalk----------------------------------------------------------
## Simple random walk Metropolis Hastings:
rmh <- function(n = 20, start = c(0,-0.5), stepmult = 10){
x <- matrix(, ncol = 2, nrow = n)
x[1, ] <- start
sol <- mountains(start)
for(i in 2:n){
x[i, ] <- x[i-1, ] + rmvnorm(1, mean = c(0, 0),
sigma = stepmult * diag(2) / n)
solnew <- mountains(x[i, ])
# accept only a better solution:
if(solnew > sol) x[i, ] <- x[i-1, ]
if(solnew < sol) sol <- solnew
}
return(x)
}
## ----walk----------------------------------------------------------------
library("mvtnorm")
set.seed(12345)
n <- 200
x1 <- rmh(n, start = c(1.5,0))
x2 <- rmh(n, start = c(1.5,0))
## ----B05113_05_06--------------------------------------------------------
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
points(x1[1, 1], x1[1, 2], pch = 4, cex = 3)
points(x2[n, 1], x2[n, 2], pch = 20, col = "red", cex = 3)
points(x1[n, 1], x1[n, 2], pch = 20, col = "red", cex = 3)
lines(x1[, 1], x1[, 2], type = "o", pch = 3)
lines(x2[, 1], x2[, 2], type = "o", col = "blue", lty = 2)
## ----B05113_05_07code----------------------------------------------------
stoGrad <- function(start = c(0, -0.5), j = 1500, p = 0.1){
theta <- matrix(start, ncol=2)
diff <- iter <- 1
alpha <- sapply(1:100, function(x) 1 / (j+1) )
beta <- sapply(1:100, function(x) 1 / (j+1)^(p) )
while( diff > 10^-5 & !is.nan(diff) & !is.na(diff) ){
zeta <- rnorm(2)
zeta <- zeta / sqrt(t(zeta) %*% zeta)
grad <- alpha[iter] * zeta * (mountains(theta[iter, ] + beta[iter] * zeta) -
mountains(theta[iter, ] - beta[iter] * zeta)) / beta[iter]
theta <- rbind(theta, theta[iter, ] - grad)
diff <- sqrt(t(grad) %*% grad )
iter <- iter + 1
}
list(theta = theta[1:(iter-1), ], diff = diff, iter = iter-1)
}
## ----B05113_05_07--------------------------------------------------------
set.seed(123)
s1 <- stoGrad()
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
plotLine <- function(x, ...){
lines(x$theta[,1], x$theta[,2], type = "o", ...)
points(x$theta[x$iter, 1], x$theta[x$iter, 1], pch = 20, col = "red", cex = 3)
}
plotLine(s1, pch = 3)
points(0, -0.5, pch = 20, cex = 1.5)
plotLine(stoGrad(), col = "blue", pch = 4)
plotLine(stoGrad(start = c(1.5, 0)), pch = 3, lty = 2)
plotLine(stoGrad(start = c(1.5, 0)), col = "blue", pch = 4, lty = 2)
points(1.5, 0, pch = 20, cex = 1.5)
## ----B05113_05_08--------------------------------------------------------
set.seed(123)
s1 <- stoGrad(p = 2.5)
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
plotLine <- function(x, ...){
lines(x$theta[,1], x$theta[,2], type = "o", ...)
points(x$theta[x$iter, 1], x$theta[x$iter, 1], pch = 20, col = "red", cex = 3)
}
plotLine(s1, pch = 3)
points(0, -0.5, pch = 20, cex = 1.5)
plotLine(stoGrad(p = 2.5), col = "blue", pch = 4)
plotLine(stoGrad(start = c(1.5, 0), j=1500, p=2.5), pch = 3, lty = 2)
plotLine(stoGrad(start = c(1.5, 0), j=1500, p=2.5), col = "blue", pch = 4, lty = 2)
points(1.5, 0, pch = 20, cex = 1.5)
## ----B05113_05_09, warning=FALSE, message=FALSE--------------------------
library("nloptr")
set.seed(123)
## mountains function with modified function parameters
mountains1 <-
function(x) ((1 - x[1])^2 + 100 * (x[2] - x[1]*x[1])^2 +
0.3*(0.2 - 2*x[2])^2 + 100 * (x[1] - x[2]*x[2])^2 -
0.5*(x[1]^2 +5*x[2]^2))
x0 <- c(0.5, -1)
lb <- c(-3, -3)
ub <- c(3, 3)
sol <- matrix(, ncol=2,nrow=21)
## solution on each step
for(i in 1:20){
sol[i, ] <- isres(x0 = x0, fn = mountains1, lower = lb, upper = ub, maxeval = i)$par
}
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
## start
points(sol[1, 1], sol[1, 2], pch = 20, cex = 2)
## optima found
sol[21,] <- isres(x0 = x0, fn = mountains1, lower = lb, upper = ub)$par
points(sol[21, 1], sol[21, 2], pch = 20, col = "red", cex = 3)
## way to optima
lines(sol[,1], sol[,2], type = "o", pch = 3)
## ------------------------------------------------------------------------
sessionInfo()
| /Chapter 5/chapter5.R | permissive | PacktPublishing/Simulation-for-Data-Science-with-R | R | false | false | 8,067 | r | ## ----rosenbroeck---------------------------------------------------------
mountains <- function(v) {
(1 - v[1])^2 + 100 * (v[2] - v[1]*v[1])^2 +
0.3*(0.2 - 2*v[2])^2 + 100 * (v[1] - v[2]*v[2])^2 -
0.5*(v[1]^2 +5*v[2]^2)
}
## ---- eval=FALSE---------------------------------------------------------
## library("animation")
## grad.desc()
## ---- eval=FALSE---------------------------------------------------------
## ani.options(nmax = 70)
## par(mar = c(4, 4, 2, 0.1))
## f2 = function(x, y) sin(1/2 * x^2 - 1/4 * y^2 + 3) * cos(2 * x + 1 -
## exp(y))
## grad.desc(f2, c(-2, -2, 2, 2), c(-1, 0.5), gamma = 0.3, tol = 1e-04)
## ----B05113_05_02--------------------------------------------------------
n <- 300
## to define a grid
x <- seq(-1, 2, length.out = n)
y <- seq(-1, 2, length.out = n)
## evaluate on each grid point
z <- mountains(expand.grid(x, y))
## contour plot
par(mar = c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)),
xlab = "x", ylab = "y", nlevels = 20)
## starting value
sta <- c(0.5,-1)
points(sta[1], sta[2], cex = 2, pch = 20)
## solutions for each of 20 steps
sol <- matrix(, ncol=2, nrow = 21)
sol[1, ] <- sta
for(i in 2:20){
sol[i, ] <- nlm(mountains, sta, iterlim = i)$est
}
## optimal solution
sol[21, ] <- nlm(mountains, sta)$est
points(sol[21, 1], sol[21, 2], cex = 3, col = "red", pch = 20)
## path visually
lines(sol, pch=3, type="o")
## now let's start better (dashed line)
sta <- c(0,-1)
for(i in 2:20){
sol[i, ] <- nlm(mountains, sta, iterlim = i)$est
}
sol[1, ] <- sta
sol[21, ] <- nlm(mountains, sta)$est
points(sta[1], sta[2], cex = 2, pch = 20)
points(sol[21, 1], sol[21, 2], cex = 3, col = "red", pch = 20)
lines(sol, pch=3, type="o")
## ----B05113_05_03, cache=FALSE-------------------------------------------
## wrapper for all methods of optim
optims <- function(x, meth = "Nelder-Mead", start = c(0.5, -1)){
sol <- matrix(, ncol = 2, nrow = 21)
sol[1, ] <- start
for(i in 2:20){
sol[i, ] <- optim(start, mountains, method = meth,
control = list(maxit=i))$par
}
sol[21,] <- optim(start, mountains)$par
points(start[1], start[2], pch=20, cex = 2)
points(sol[21, ], sol[21, ], pch = 20, col = "red", cex = 3)
lines(sol[, 1], sol[, 2], type = "o", pch = 3)
}
## plot lines for all methods
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
optims() # Nelder-Mead
optims("BFGS")
optims("CG")
optims("L-BFGS-B")
optims("SANN")
optims("Brent")
optims(start = c(1.5,0.5))
## ----B05113_05_04, cache=TRUE--------------------------------------------
## define grid
n <- 1500
set.seed(1234567)
x1 <- runif(n, min = -2, max = 5)
y1 <- runif(n, min = -2, max = 5)
z1 <- matrix(, ncol = n, nrow = n)
## evaluate on each grid point
for(i in 1:n){
for(j in 1:n){
z1[i,j] <- mountains(c(x1[i], y1[j]))
}
}
## determine optima
w <- which(z1 == min(z1), arr.ind=TRUE)
## plot results
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
points(x1[w[1]], y1[w[2]], pch = 20, col = "red", cex = 3)
points(x1, y1, pch=3)
## ----B05113_05_05, cache=TRUE--------------------------------------------
library("RCEIM")
set.seed(123)
sol <- best <- list()
## save solution for each step
for(i in 2:20){
a <- ceimOpt(mountains, nParam = 2, maxIter = i)
sol[[i]] <- a$EliteMembers
best[[i]] <- a$BestMember
}
## plot the results for each step
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
greys <- grey(rev(2:20 / 20 - 0.099))
for(i in 2:20){
points(sol[[i]][,1], sol[[i]][,2], col = greys[i])
points(best[[i]][1], best[[i]][2], col = "red", pch = 3)
}
points(best[[i]][1], best[[i]][2], col = "red", pch = 20, cex = 3)
## ----randomwalk----------------------------------------------------------
## Simple random walk Metropolis Hastings:
rmh <- function(n = 20, start = c(0,-0.5), stepmult = 10){
x <- matrix(, ncol = 2, nrow = n)
x[1, ] <- start
sol <- mountains(start)
for(i in 2:n){
x[i, ] <- x[i-1, ] + rmvnorm(1, mean = c(0, 0),
sigma = stepmult * diag(2) / n)
solnew <- mountains(x[i, ])
# accept only a better solution:
if(solnew > sol) x[i, ] <- x[i-1, ]
if(solnew < sol) sol <- solnew
}
return(x)
}
## ----walk----------------------------------------------------------------
library("mvtnorm")
set.seed(12345)
n <- 200
x1 <- rmh(n, start = c(1.5,0))
x2 <- rmh(n, start = c(1.5,0))
## ----B05113_05_06--------------------------------------------------------
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
points(x1[1, 1], x1[1, 2], pch = 4, cex = 3)
points(x2[n, 1], x2[n, 2], pch = 20, col = "red", cex = 3)
points(x1[n, 1], x1[n, 2], pch = 20, col = "red", cex = 3)
lines(x1[, 1], x1[, 2], type = "o", pch = 3)
lines(x2[, 1], x2[, 2], type = "o", col = "blue", lty = 2)
## ----B05113_05_07code----------------------------------------------------
stoGrad <- function(start = c(0, -0.5), j = 1500, p = 0.1){
theta <- matrix(start, ncol=2)
diff <- iter <- 1
alpha <- sapply(1:100, function(x) 1 / (j+1) )
beta <- sapply(1:100, function(x) 1 / (j+1)^(p) )
while( diff > 10^-5 & !is.nan(diff) & !is.na(diff) ){
zeta <- rnorm(2)
zeta <- zeta / sqrt(t(zeta) %*% zeta)
grad <- alpha[iter] * zeta * (mountains(theta[iter, ] + beta[iter] * zeta) -
mountains(theta[iter, ] - beta[iter] * zeta)) / beta[iter]
theta <- rbind(theta, theta[iter, ] - grad)
diff <- sqrt(t(grad) %*% grad )
iter <- iter + 1
}
list(theta = theta[1:(iter-1), ], diff = diff, iter = iter-1)
}
## ----B05113_05_07--------------------------------------------------------
set.seed(123)
s1 <- stoGrad()
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
plotLine <- function(x, ...){
lines(x$theta[,1], x$theta[,2], type = "o", ...)
points(x$theta[x$iter, 1], x$theta[x$iter, 1], pch = 20, col = "red", cex = 3)
}
plotLine(s1, pch = 3)
points(0, -0.5, pch = 20, cex = 1.5)
plotLine(stoGrad(), col = "blue", pch = 4)
plotLine(stoGrad(start = c(1.5, 0)), pch = 3, lty = 2)
plotLine(stoGrad(start = c(1.5, 0)), col = "blue", pch = 4, lty = 2)
points(1.5, 0, pch = 20, cex = 1.5)
## ----B05113_05_08--------------------------------------------------------
set.seed(123)
s1 <- stoGrad(p = 2.5)
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
plotLine <- function(x, ...){
lines(x$theta[,1], x$theta[,2], type = "o", ...)
points(x$theta[x$iter, 1], x$theta[x$iter, 1], pch = 20, col = "red", cex = 3)
}
plotLine(s1, pch = 3)
points(0, -0.5, pch = 20, cex = 1.5)
plotLine(stoGrad(p = 2.5), col = "blue", pch = 4)
plotLine(stoGrad(start = c(1.5, 0), j=1500, p=2.5), pch = 3, lty = 2)
plotLine(stoGrad(start = c(1.5, 0), j=1500, p=2.5), col = "blue", pch = 4, lty = 2)
points(1.5, 0, pch = 20, cex = 1.5)
## ----B05113_05_09, warning=FALSE, message=FALSE--------------------------
library("nloptr")
set.seed(123)
## mountains function with modified function parameters
mountains1 <-
function(x) ((1 - x[1])^2 + 100 * (x[2] - x[1]*x[1])^2 +
0.3*(0.2 - 2*x[2])^2 + 100 * (x[1] - x[2]*x[2])^2 -
0.5*(x[1]^2 +5*x[2]^2))
x0 <- c(0.5, -1)
lb <- c(-3, -3)
ub <- c(3, 3)
sol <- matrix(, ncol=2,nrow=21)
## solution on each step
for(i in 1:20){
sol[i, ] <- isres(x0 = x0, fn = mountains1, lower = lb, upper = ub, maxeval = i)$par
}
par(mar=c(4,4,0.5,0.5))
contour(x, y, matrix(log10(z), length(x)), xlab = "x", ylab = "y", nlevels = 20)
## start
points(sol[1, 1], sol[1, 2], pch = 20, cex = 2)
## optima found
sol[21,] <- isres(x0 = x0, fn = mountains1, lower = lb, upper = ub)$par
points(sol[21, 1], sol[21, 2], pch = 20, col = "red", cex = 3)
## way to optima
lines(sol[,1], sol[,2], type = "o", pch = 3)
## ------------------------------------------------------------------------
sessionInfo()
|
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setinverse <- function(inverse) m <<- inverse
getinverse <- function() m
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Write a short comment describing this function
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getinverse()
if (!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data, ...)
x$setinverse(m)
m
}
| /cachematrix.R | no_license | francisivanclado/ProgrammingAssignment2 | R | false | false | 750 | r | ## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setinverse <- function(inverse) m <<- inverse
getinverse <- function() m
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Write a short comment describing this function
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getinverse()
if (!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data, ...)
x$setinverse(m)
m
}
|
\name{bag.o.words}
\alias{bag.o.words}
\alias{breaker}
\alias{word.split}
\title{Bag of Words}
\usage{
bag.o.words(text.var, apostrophe.remove = FALSE, ...)
breaker(text.var)
word.split(text.var)
}
\arguments{
\item{text.var}{The text variable.}
\item{apostrophe.remove}{logical. If TRUE removes
apostrophe's from the output.}
\item{\ldots}{further arguments passed to strip
function.}
}
\value{
Returns a vector of striped words.
\code{breaker} - returns a vector of striped words and
qdap recognized endmarks (i.e., \code{".", "!", "?", "*",
"-"}).
}
\description{
\code{bag.o.words} - Reduces a text column to a bag of
words.
\code{breaker} - Reduces a text column to a bag of words
and qdap recognized end marks.
\code{word.split} - Reduces a text column to a list of
vectors of bag of words and qdap recognized end marks
(i.e., \code{".", "!", "?", "*", "-"}).
}
\examples{
\dontrun{
bag.o.words("I'm going home!")
bag.o.words("I'm going home!", apostrophe.remove = TRUE)
bag.o.words(DATA$state)
by(DATA$state, DATA$person, bag.o.words)
lapply(DATA$state, bag.o.words)
breaker(DATA$state)
by(DATA$state, DATA$person, breaker)
lapply(DATA$state, breaker)
word.split(c(NA, DATA$state))
}
}
\keyword{bag-of-words}
| /man/bag.o.words.Rd | no_license | toledobastos/qdap | R | false | false | 1,268 | rd | \name{bag.o.words}
\alias{bag.o.words}
\alias{breaker}
\alias{word.split}
\title{Bag of Words}
\usage{
bag.o.words(text.var, apostrophe.remove = FALSE, ...)
breaker(text.var)
word.split(text.var)
}
\arguments{
\item{text.var}{The text variable.}
\item{apostrophe.remove}{logical. If TRUE removes
apostrophe's from the output.}
\item{\ldots}{further arguments passed to strip
function.}
}
\value{
Returns a vector of striped words.
\code{breaker} - returns a vector of striped words and
qdap recognized endmarks (i.e., \code{".", "!", "?", "*",
"-"}).
}
\description{
\code{bag.o.words} - Reduces a text column to a bag of
words.
\code{breaker} - Reduces a text column to a bag of words
and qdap recognized end marks.
\code{word.split} - Reduces a text column to a list of
vectors of bag of words and qdap recognized end marks
(i.e., \code{".", "!", "?", "*", "-"}).
}
\examples{
\dontrun{
bag.o.words("I'm going home!")
bag.o.words("I'm going home!", apostrophe.remove = TRUE)
bag.o.words(DATA$state)
by(DATA$state, DATA$person, bag.o.words)
lapply(DATA$state, bag.o.words)
breaker(DATA$state)
by(DATA$state, DATA$person, breaker)
lapply(DATA$state, breaker)
word.split(c(NA, DATA$state))
}
}
\keyword{bag-of-words}
|
#######################################
#### Example and Exercise
####
#### Cong Mu
#### 09/13/2019
#######################################
#### Example with gala dataset
## Load the package
library(faraway)
## Attach the data
data(gala, package = "faraway")
## Learn the data
head(gala[,-2])
## Fit a linear model
lmod <- lm(Species ~ Area + Elevation + Nearest + Scruz + Adjacent, data = gala)
summary(lmod)
## OLS by hand
x <- model.matrix( ~ Area + Elevation + Nearest + Scruz + Adjacent, gala)
y <- gala$Species
xtxi <- solve(t(x) %*% x)
xtxi %*% t(x) %*% y
solve(crossprod(x,x), crossprod(x,y))
## Regression quantities
names(lmod)
lmodsum <- summary(lmod)
names(lmodsum)
# sigma
sqrt(deviance(lmod)/df.residual(lmod))
lmodsum$sigma
# standard errors for the coefficients
xtxi <- lmodsum$cov.unscaled
sqrt(diag(xtxi))*60.975
lmodsum$coef[,2]
#### Exercise with teengamb dataset
## Attach the data
data(teengamb, package = "faraway")
## Fit a linear model
lmod <- lm(gamble ~ sex + status + income + verbal, data = teengamb)
summary(lmod)
lmod <- lm(gamble ~ ., data = teengamb)
summary(lmod)
# Residuals
e <- lmod$residuals
which.max(e)
mean(e)
median(e)
# Correlation
fitted <- lmod$fitted.values
cor(e, fitted)
cor(e, teengamb$income)
# Coefficients
lmod$coefficients
| /teaching/Applied Statistics and Data Analysis/section-9-13-11am.R | no_license | CongM/CongM.github.io | R | false | false | 1,310 | r | #######################################
#### Example and Exercise
####
#### Cong Mu
#### 09/13/2019
#######################################
#### Example with gala dataset
## Load the package
library(faraway)
## Attach the data
data(gala, package = "faraway")
## Learn the data
head(gala[,-2])
## Fit a linear model
lmod <- lm(Species ~ Area + Elevation + Nearest + Scruz + Adjacent, data = gala)
summary(lmod)
## OLS by hand
x <- model.matrix( ~ Area + Elevation + Nearest + Scruz + Adjacent, gala)
y <- gala$Species
xtxi <- solve(t(x) %*% x)
xtxi %*% t(x) %*% y
solve(crossprod(x,x), crossprod(x,y))
## Regression quantities
names(lmod)
lmodsum <- summary(lmod)
names(lmodsum)
# sigma
sqrt(deviance(lmod)/df.residual(lmod))
lmodsum$sigma
# standard errors for the coefficients
xtxi <- lmodsum$cov.unscaled
sqrt(diag(xtxi))*60.975
lmodsum$coef[,2]
#### Exercise with teengamb dataset
## Attach the data
data(teengamb, package = "faraway")
## Fit a linear model
lmod <- lm(gamble ~ sex + status + income + verbal, data = teengamb)
summary(lmod)
lmod <- lm(gamble ~ ., data = teengamb)
summary(lmod)
# Residuals
e <- lmod$residuals
which.max(e)
mean(e)
median(e)
# Correlation
fitted <- lmod$fitted.values
cor(e, fitted)
cor(e, teengamb$income)
# Coefficients
lmod$coefficients
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/user_interaction.R
\name{invalidateEvents}
\alias{invalidateEvents}
\title{Allow the user to determine a given movement event invalid}
\usage{
invalidateEvents(
displayed.moves,
all.moves,
detections,
tag,
GUI,
save.tables.locally
)
}
\arguments{
\item{displayed.moves}{The valid movements table for a specific tag.}
\item{all.moves}{The complete movements table for a specific tag.}
\item{detections}{The detections data.frame for a specific tag.}
\item{tag}{The tag being analysed.}
\item{GUI}{One of "needed", "always" or "never". If "needed", a new window is
opened to inspect the movements only if the movements table is too big to be
displayed in R's console. If "always", a graphical interface is always created
when the possibility to invalidate events emerges. If "never", a graphical
interface is never invoked. In this case, if the table to be displayed does
not fit in R's console, a temporary file will be saved and the user will be
prompted to open and examine that file. Defaults to "needed".}
\item{save.tables.locally}{Logical: If a table must be temporarily stored into a file
for user inspection, should it be saved in the current working directory, or
in R's temporary folder?}
}
\value{
A data frame with the movement events for the target tag and an updated 'Valid' column.
}
\description{
Allow the user to determine a given movement event invalid
}
\keyword{internal}
| /man/invalidateEvents.Rd | no_license | cran/actel | R | false | true | 1,530 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/user_interaction.R
\name{invalidateEvents}
\alias{invalidateEvents}
\title{Allow the user to determine a given movement event invalid}
\usage{
invalidateEvents(
displayed.moves,
all.moves,
detections,
tag,
GUI,
save.tables.locally
)
}
\arguments{
\item{displayed.moves}{The valid movements table for a specific tag.}
\item{all.moves}{The complete movements table for a specific tag.}
\item{detections}{The detections data.frame for a specific tag.}
\item{tag}{The tag being analysed.}
\item{GUI}{One of "needed", "always" or "never". If "needed", a new window is
opened to inspect the movements only if the movements table is too big to be
displayed in R's console. If "always", a graphical interface is always created
when the possibility to invalidate events emerges. If "never", a graphical
interface is never invoked. In this case, if the table to be displayed does
not fit in R's console, a temporary file will be saved and the user will be
prompted to open and examine that file. Defaults to "needed".}
\item{save.tables.locally}{Logical: If a table must be temporarily stored into a file
for user inspection, should it be saved in the current working directory, or
in R's temporary folder?}
}
\value{
A data frame with the movement events for the target tag and an updated 'Valid' column.
}
\description{
Allow the user to determine a given movement event invalid
}
\keyword{internal}
|
plotPost = function( paramSampleVec , credMass=0.95 , compVal=NULL ,
HDItextPlace=0.7 , ROPE=NULL , yaxt=NULL , ylab=NULL ,
xlab=NULL , cex.lab=NULL , cex=NULL , xlim=NULL , main=NULL ,
col=NULL , border=NULL , showMode=F , showCurve=F , breaks=NULL ,
... ) {
# Override defaults of hist function, if not specified by user:
# (additional arguments "..." are passed to the hist function)
if ( is.null(xlab) ) xlab="Parameter"
if ( is.null(cex.lab) ) cex.lab=1.5
if ( is.null(cex) ) cex=1.4
if ( is.null(xlim) ) xlim=range( c( compVal , paramSampleVec ) )
if ( is.null(main) ) main=""
if ( is.null(yaxt) ) yaxt="n"
if ( is.null(ylab) ) ylab=""
if ( is.null(col) ) col="skyblue"
if ( is.null(border) ) border="white"
postSummary = matrix( NA , nrow=1 , ncol=11 ,
dimnames=list( c( xlab ) ,
c("mean","median","mode",
"hdiMass","hdiLow","hdiHigh",
"compVal","pcGTcompVal",
"ROPElow","ROPEhigh","pcInROPE")))
postSummary[,"mean"] = mean(paramSampleVec)
postSummary[,"median"] = median(paramSampleVec)
mcmcDensity = density(paramSampleVec)
postSummary[,"mode"] = mcmcDensity$x[which.max(mcmcDensity$y)]
source("functions/HDIofMCMC.R")
HDI = HDIofMCMC( paramSampleVec , credMass )
postSummary[,"hdiMass"]=credMass
postSummary[,"hdiLow"]=HDI[1]
postSummary[,"hdiHigh"]=HDI[2]
# Plot histogram.
if ( is.null(breaks) ) {
breaks = c( seq( from=min(paramSampleVec) , to=max(paramSampleVec) ,
by=(HDI[2]-HDI[1])/18 ) , max(paramSampleVec) )
}
if ( !showCurve ) {
par(xpd=NA)
histinfo = hist( paramSampleVec , xlab=xlab , yaxt=yaxt , ylab=ylab ,
freq=F , border=border , col=col ,
xlim=xlim , main=main , cex=cex , cex.lab=cex.lab ,
breaks=breaks , ... )
}
if ( showCurve ) {
par(xpd=NA)
histinfo = hist( paramSampleVec , plot=F )
densCurve = density( paramSampleVec , adjust=2 )
plot( densCurve$x , densCurve$y , type="l" , lwd=5 , col=col , bty="n" ,
xlim=xlim , xlab=xlab , yaxt=yaxt , ylab=ylab ,
main=main , cex=cex , cex.lab=cex.lab , ... )
}
cenTendHt = 0.9*max(histinfo$density)
cvHt = 0.7*max(histinfo$density)
ROPEtextHt = 0.55*max(histinfo$density)
# Display mean or mode:
if ( showMode==F ) {
meanParam = mean( paramSampleVec )
text( meanParam , cenTendHt ,
bquote(mean==.(signif(meanParam,3))) , adj=c(.5,0) , cex=cex )
} else {
dres = density( paramSampleVec )
modeParam = dres$x[which.max(dres$y)]
text( modeParam , cenTendHt ,
bquote(mode==.(signif(modeParam,3))) , adj=c(.5,0) , cex=cex )
}
# Display the comparison value.
if ( !is.null( compVal ) ) {
cvCol = "darkgreen"
pcgtCompVal = round( 100 * sum( paramSampleVec > compVal )
/ length( paramSampleVec ) , 1 )
pcltCompVal = 100 - pcgtCompVal
lines( c(compVal,compVal) , c(0.96*cvHt,0) ,
lty="dotted" , lwd=1 , col=cvCol )
text( compVal , cvHt ,
bquote( .(pcltCompVal)*"% < " *
.(signif(compVal,3)) * " < "*.(pcgtCompVal)*"%" ) ,
adj=c(pcltCompVal/100,0) , cex=0.8*cex , col=cvCol )
postSummary[,"compVal"] = compVal
postSummary[,"pcGTcompVal"] = ( sum( paramSampleVec > compVal )
/ length( paramSampleVec ) )
}
# Display the ROPE.
if ( !is.null( ROPE ) ) {
ropeCol = "darkred"
pcInROPE = ( sum( paramSampleVec > ROPE[1] & paramSampleVec < ROPE[2] )
/ length( paramSampleVec ) )
lines( c(ROPE[1],ROPE[1]) , c(0.96*ROPEtextHt,0) , lty="dotted" , lwd=2 ,
col=ropeCol )
lines( c(ROPE[2],ROPE[2]) , c(0.96*ROPEtextHt,0) , lty="dotted" , lwd=2 ,
col=ropeCol)
text( mean(ROPE) , ROPEtextHt ,
bquote( .(round(100*pcInROPE))*"% in ROPE" ) ,
adj=c(.5,0) , cex=1 , col=ropeCol )
postSummary[,"ROPElow"]=ROPE[1]
postSummary[,"ROPEhigh"]=ROPE[2]
postSummary[,"pcInROPE"]=pcInROPE
}
# Display the HDI.
lines( HDI , c(0,0) , lwd=4 )
text( mean(HDI) , 0 , bquote(.(100*credMass) * "% HDI" ) ,
adj=c(.5,-1.7) , cex=cex )
text( HDI[1] , 0 , bquote(.(signif(HDI[1],3))) ,
adj=c(HDItextPlace,-0.5) , cex=cex )
text( HDI[2] , 0 , bquote(.(signif(HDI[2],3))) ,
adj=c(1.0-HDItextPlace,-0.5) , cex=cex )
par(xpd=F)
#
return( postSummary )
}
| /functions/plotPost.R | permissive | pjastam/r-bayesian-football-odds | R | false | false | 4,902 | r | plotPost = function( paramSampleVec , credMass=0.95 , compVal=NULL ,
HDItextPlace=0.7 , ROPE=NULL , yaxt=NULL , ylab=NULL ,
xlab=NULL , cex.lab=NULL , cex=NULL , xlim=NULL , main=NULL ,
col=NULL , border=NULL , showMode=F , showCurve=F , breaks=NULL ,
... ) {
# Override defaults of hist function, if not specified by user:
# (additional arguments "..." are passed to the hist function)
if ( is.null(xlab) ) xlab="Parameter"
if ( is.null(cex.lab) ) cex.lab=1.5
if ( is.null(cex) ) cex=1.4
if ( is.null(xlim) ) xlim=range( c( compVal , paramSampleVec ) )
if ( is.null(main) ) main=""
if ( is.null(yaxt) ) yaxt="n"
if ( is.null(ylab) ) ylab=""
if ( is.null(col) ) col="skyblue"
if ( is.null(border) ) border="white"
postSummary = matrix( NA , nrow=1 , ncol=11 ,
dimnames=list( c( xlab ) ,
c("mean","median","mode",
"hdiMass","hdiLow","hdiHigh",
"compVal","pcGTcompVal",
"ROPElow","ROPEhigh","pcInROPE")))
postSummary[,"mean"] = mean(paramSampleVec)
postSummary[,"median"] = median(paramSampleVec)
mcmcDensity = density(paramSampleVec)
postSummary[,"mode"] = mcmcDensity$x[which.max(mcmcDensity$y)]
source("functions/HDIofMCMC.R")
HDI = HDIofMCMC( paramSampleVec , credMass )
postSummary[,"hdiMass"]=credMass
postSummary[,"hdiLow"]=HDI[1]
postSummary[,"hdiHigh"]=HDI[2]
# Plot histogram.
if ( is.null(breaks) ) {
breaks = c( seq( from=min(paramSampleVec) , to=max(paramSampleVec) ,
by=(HDI[2]-HDI[1])/18 ) , max(paramSampleVec) )
}
if ( !showCurve ) {
par(xpd=NA)
histinfo = hist( paramSampleVec , xlab=xlab , yaxt=yaxt , ylab=ylab ,
freq=F , border=border , col=col ,
xlim=xlim , main=main , cex=cex , cex.lab=cex.lab ,
breaks=breaks , ... )
}
if ( showCurve ) {
par(xpd=NA)
histinfo = hist( paramSampleVec , plot=F )
densCurve = density( paramSampleVec , adjust=2 )
plot( densCurve$x , densCurve$y , type="l" , lwd=5 , col=col , bty="n" ,
xlim=xlim , xlab=xlab , yaxt=yaxt , ylab=ylab ,
main=main , cex=cex , cex.lab=cex.lab , ... )
}
cenTendHt = 0.9*max(histinfo$density)
cvHt = 0.7*max(histinfo$density)
ROPEtextHt = 0.55*max(histinfo$density)
# Display mean or mode:
if ( showMode==F ) {
meanParam = mean( paramSampleVec )
text( meanParam , cenTendHt ,
bquote(mean==.(signif(meanParam,3))) , adj=c(.5,0) , cex=cex )
} else {
dres = density( paramSampleVec )
modeParam = dres$x[which.max(dres$y)]
text( modeParam , cenTendHt ,
bquote(mode==.(signif(modeParam,3))) , adj=c(.5,0) , cex=cex )
}
# Display the comparison value.
if ( !is.null( compVal ) ) {
cvCol = "darkgreen"
pcgtCompVal = round( 100 * sum( paramSampleVec > compVal )
/ length( paramSampleVec ) , 1 )
pcltCompVal = 100 - pcgtCompVal
lines( c(compVal,compVal) , c(0.96*cvHt,0) ,
lty="dotted" , lwd=1 , col=cvCol )
text( compVal , cvHt ,
bquote( .(pcltCompVal)*"% < " *
.(signif(compVal,3)) * " < "*.(pcgtCompVal)*"%" ) ,
adj=c(pcltCompVal/100,0) , cex=0.8*cex , col=cvCol )
postSummary[,"compVal"] = compVal
postSummary[,"pcGTcompVal"] = ( sum( paramSampleVec > compVal )
/ length( paramSampleVec ) )
}
# Display the ROPE.
if ( !is.null( ROPE ) ) {
ropeCol = "darkred"
pcInROPE = ( sum( paramSampleVec > ROPE[1] & paramSampleVec < ROPE[2] )
/ length( paramSampleVec ) )
lines( c(ROPE[1],ROPE[1]) , c(0.96*ROPEtextHt,0) , lty="dotted" , lwd=2 ,
col=ropeCol )
lines( c(ROPE[2],ROPE[2]) , c(0.96*ROPEtextHt,0) , lty="dotted" , lwd=2 ,
col=ropeCol)
text( mean(ROPE) , ROPEtextHt ,
bquote( .(round(100*pcInROPE))*"% in ROPE" ) ,
adj=c(.5,0) , cex=1 , col=ropeCol )
postSummary[,"ROPElow"]=ROPE[1]
postSummary[,"ROPEhigh"]=ROPE[2]
postSummary[,"pcInROPE"]=pcInROPE
}
# Display the HDI.
lines( HDI , c(0,0) , lwd=4 )
text( mean(HDI) , 0 , bquote(.(100*credMass) * "% HDI" ) ,
adj=c(.5,-1.7) , cex=cex )
text( HDI[1] , 0 , bquote(.(signif(HDI[1],3))) ,
adj=c(HDItextPlace,-0.5) , cex=cex )
text( HDI[2] , 0 , bquote(.(signif(HDI[2],3))) ,
adj=c(1.0-HDItextPlace,-0.5) , cex=cex )
par(xpd=F)
#
return( postSummary )
}
|
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
makeCacheMatrix <- function(x = matrix()) {
i <- NULL
set <- function(y) {
x <<- y
i <<- NULL
}
get <- function() x
setinverse <- function(inverse) i <<- inverse
getinverse <- function() i
list(set=set, get=get, setinverse=setinverse, getinverse=getinverse)
}
## Write a short comment describing this function
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
i <- x$getinverse()
if (!is.null(i)) {
message("Getting cached inverse")
return(i)
}
rawMatrix <- x$get()
i <- solve(rawMatrix, ...)
x$setinverse(i)
i
}
| /cachematrix.R | no_license | msoltow261/ProgrammingAssignment2 | R | false | false | 776 | r | ## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
makeCacheMatrix <- function(x = matrix()) {
i <- NULL
set <- function(y) {
x <<- y
i <<- NULL
}
get <- function() x
setinverse <- function(inverse) i <<- inverse
getinverse <- function() i
list(set=set, get=get, setinverse=setinverse, getinverse=getinverse)
}
## Write a short comment describing this function
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
i <- x$getinverse()
if (!is.null(i)) {
message("Getting cached inverse")
return(i)
}
rawMatrix <- x$get()
i <- solve(rawMatrix, ...)
x$setinverse(i)
i
}
|
### final figures
library(tidyverse)
library(RColorBrewer)
library(ggthemes)
library(ggpubr)
#
##
###
#### Figure 1 - NMDS comparing AMR samples by unique sample (dilution and normal)
###
##
#
#
##
###
#### Figure 2 showing resistome composition and microbiome composition
###
##
#
AMR_class_sum <- amr_melted_analytic[Level_ID=="Class", .(sum_class= sum(Normalized_Count)),by=.(ID,sample, Name, Packaging, Treatment)][order(-Packaging )]
AMR_class_sum[,total:= sum(sum_class), by=.(ID)]
AMR_class_sum[,percentage:= sum_class/total ,by=.(ID, Name) ]
AMR_class_sum$Name = droplevels(AMR_class_sum$Name)
AMR_class_sum$Name = factor(AMR_class_sum$Name ,levels=c("Sulfonamides","Rifampin","Trimethoprim","Triclosan","Fluoroquinolones","Aminocoumarins","Nitrofuran","Fosfomycin" , "Elfamycins" ,"Phenicol","Bacitracin","Cationic antimicrobial peptides","Aminoglycosides", "MLS" ,"betalactams" , "Multi-drug resistance" , "Tetracyclines"))
AMR_class_sum$sample = factor(AMR_class_sum$sample ,levels=c("Sample 1.1","Sample 1.2","Sample 2.1","Sample 2.2","Sample 3.1","Sample 3.2","Sample 4.1",
"Sample 4.2","Sample 5.1","Sample 5.2","Sample 6.1","Sample 6.2","Sample 7.1","Sample 7.2","Sample 8.1","Sample 8.2",
"Sample 9.1","Sample 9.2","Sample 10.1","Sample 10.2","Sample 11.1","Sample 11.2","Sample 12.1","Sample 12.2","Sample 13.1","Sample 13.2","Sample 14.1",
"Sample 14.2","Sample 15.1","Sample 15.2","Sample 16.1","Sample 16.2"))
AMR_class_sum$Treatment = factor(AMR_class_sum$Treatment ,levels=c("RWA","CONV"))
AMR_class_sum$Class <- AMR_class_sum$Name
#AMR_class_sum[,percentage:= round(sum_class/total, digits=2) ,by=.(ID, Name) ] removes some with low proportions
fig1_A <- ggplot(AMR_class_sum, aes(x = sample, y = percentage, fill = Class)) +
geom_bar(stat = "identity",colour = "black")+
facet_wrap( ~ Treatment, scales='free',ncol = 2) +
#scale_fill_brewer(palette="Dark2") +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
strip.text.x=element_text(size=24),
strip.text.y=element_text(size=24, angle=0),
axis.text.x=element_text(size=24, angle=30, hjust=1),
axis.text.y=element_text(size=22),
axis.title=element_text(size=26),
legend.position="right",
panel.spacing=unit(0.1, "lines"),
plot.title=element_text(size=32, hjust=0.5),
legend.text=element_text(size=15),
legend.title=element_text(size=20),
panel.background = element_rect(fill = "white")
) +
#ggtitle("Resistome composition by sample") +
xlab('') +
ylab('Relative abundance') +
scale_fill_tableau("Tableau 20", direction = -1)
fig1_A
#
## Microbiome
#
microbiome_phylum_sum <- microbiome_melted_analytic[Level_ID=="Phylum", .(sum_phylum= sum(Normalized_Count)),by=.(ID,sample, Name, Packaging, Treatment)][order(-Packaging )]
microbiome_phylum_sum[,total:= sum(sum_phylum), by=.(ID)]
microbiome_phylum_sum[,percentage:= sum_phylum/total ,by=.(ID, Name) ]
# only keep taxa greater than 1%
microbiome_phylum_sum <- microbiome_phylum_sum[percentage < .01, Name := 'Low Abundance Phyla (< 1%)' ]
microbiome_phylum_sum[,total:= sum(sum_phylum), by=.(ID)]
microbiome_phylum_sum[,percentage:= sum_phylum/total ,by=.(ID, Name) ]
microbiome_phylum_sum$Name = droplevels(microbiome_phylum_sum$Name)
microbiome_phylum_sum$Name = factor(microbiome_phylum_sum$Name ,levels=c("Low Abundance Phyla (< 1%)","Planctomycetes","Gemmatimonadetes","Chloroflexi","Verrucomicrobia", "Acidobacteria","Actinobacteria" ,"Bacteroidetes" , "Proteobacteria" , "Firmicutes"))
microbiome_phylum_sum$Sample = factor(microbiome_phylum_sum$sample ,levels=c("Sample 1","Sample 2","Sample 3","Sample 4","Sample 5","Sample 6","Sample 7","Sample 8","Sample 9","Sample 10","Sample 11",
"Sample 12","Sample 13","Sample 14","Sample 15","Sample 16"))
microbiome_phylum_sum$Treatment = factor(microbiome_phylum_sum$Treatment ,levels=c("RWA","CONV"))
microbiome_phylum_sum$Phylum <- microbiome_phylum_sum$Name
#microbiome_phylum_sum[,percentage:= round(sum_class/total, digits=2) ,by=.(ID, Name) ] removes some with low proportions
fig1_B <- ggplot(microbiome_phylum_sum, aes(x = Sample, y = percentage, fill = Phylum)) +
geom_bar(stat = "identity")+
facet_wrap( ~ Treatment, scales='free',ncol = 2) +
#scale_fill_brewer(palette="Dark2") +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
strip.text.x=element_text(size=24),
strip.text.y=element_text(size=24, angle=0),
axis.text.x=element_text(size=24, angle=30, hjust=1),
axis.text.y=element_text(size=22),
axis.title=element_text(size=26),
legend.position="right",
panel.spacing=unit(0.1, "lines"),
plot.title=element_text(size=32, hjust=0.5),
legend.text=element_text(size=15),
legend.title=element_text(size=20),
panel.background = element_rect(fill = "white")
) +
scale_fill_tableau("Tableau 20", direction = "1") +
#ggtitle("Microbiome composition in by treatment (only taxa > 1% per sample)") +
xlab('') +
ylab('Relative abundance')
fig1_B
## Combine figures
figure <- ggarrange(fig1_A, fig1_B,
labels = c("A)", "B)"),
ncol = 1, nrow = 2, vjust = 1.4, font.label = list(size = 30, color = "black", face =
"bold", family = NULL))
# Output jpeg figure
jpeg("FC_ground_beef_manuscript_figures/Figure1-FC_meat_resistome_and_microbiome_composition_by_Treatment.jpeg", width =1850, height = 1250)
figure
dev.off()
#
##
###
#### Figure 3 - Resistome ordination by treatment
###
##
#
# Use figure "graphs/AMR/Treatment/NMDS_Treatment_Class.png"
#
##
###
#### Figure 4 - Resistome Diversity figures
###
##
#
par(mfrow = c(2, 2))
par(cex = 0.6)
par(mar = c(3, 4, 1, 1))
par(oma = c(4,3,4,1)) ## moves the plot area, not for individual plots
par(tcl = -0.25)
par(mgp = c(2, 0.6, 0))
boxplot(metadata$AMR_class_Richness ~ metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 3, "AMR Class", line = 1, cex=2)
mtext(side = 2, "Richness", line = 4, cex=2)
boxplot(metadata$AMR_mech_Richness ~ metadata$Treatment,col=c("Red","Grey"),names=FALSE)
#title("AMR mechanism richness by group")
mtext(side = 3, "AMR Mechanism", line = 1, cex=2)
boxplot(metadata$AMR_class_Shannon ~ metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 2, "Shannon\'s Diversity", line = 4, cex=2)
boxplot(metadata$AMR_mech_Shannon ~ metadata$Treatment, col=c("Red","Grey"),names=FALSE)
par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0), new = TRUE)
plot(0, 0, type = "n", bty = "n", xaxt = "n", yaxt = "n")
legend("bottom", c("CONV","RWA"),x.intersp = .3, xpd = TRUE, horiz = TRUE, inset = c(9, 0), bty = "n", pch = 15, fill = c("Red","Grey"), cex = 1.5)
# Export as png 1200 x 800
########################
##############
########
###
# MICROBIOME
###
########
##############
########################
#
##
###
#### Figure 5 - Microbiome ordination by treatment at the phylum level
###
##
#
# Use figure "graphs/Microbiome/Treatment/NMDS_Treatment_Phylum.png"
#
##
###
#### Figure 6 - Resistome Diversity figures
###
##
#
par(mfrow = c(2, 3))
par(cex = 0.6)
par(mar = c(3, 4, 1, 1))
par(oma = c(4,3,4,1)) ## moves the plot area, not for individual plots
par(tcl = -0.25)
par(mgp = c(2, 0.6, 0))
boxplot(microbiome_metadata$microbiome_phylum_Richness ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 3, "Phylum", line = 1, cex=2)
mtext(side = 2, "Richness", line = 4, cex=2)
boxplot(microbiome_metadata$microbiome_class_Richness ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 3, "Class", line = 1, cex=2)
boxplot(microbiome_metadata$microbiome_order_Richness ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 3, "Order", line = 1, cex=2)
boxplot(microbiome_metadata$microbiome_phylum_Shannon ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 2, "Shannon's Diversity", line = 4, cex=2)
boxplot(microbiome_metadata$microbiome_class_Shannon ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
boxplot(microbiome_metadata$microbiome_order_Shannon ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0), new = TRUE)
plot(0, 0, type = "n", bty = "n", xaxt = "n", yaxt = "n")
legend("bottom", c("CONV","RWA"),x.intersp = .5, xpd = TRUE, horiz = TRUE, inset = c(9, 0), bty = "n", pch = 15, fill = c("Red","Grey"), cex = 1.5)
# Export as png 1200 x 800
#
##
###
#### Figure 7 - Microbiome ordination by store at the phylum level
###
##
#
# Use figure "graphs/Microbiome/Store/NMDS_Blinded_Store_Phylum.png"
###################################################
## ##
## Supplemental figures ##
## ##
###################################################
#
##
###
#### Supplemental Figure 1 - Resistome ordination at the phylum level by dilution
###
##
#
#
##
###
#### Supplemental Figure 1 - Heatmap
###
##
#
### Looking for clinically important AMR genes
amr_group_check <- amr_group_raw[!group %in% snp_regex, ]
important_AMR_regex = c('OXA',
'SME',
'sme',
'IMI',
'NDM',
'GES',
'KPC',
'CPHA',
'TEM',
'SHV',
'CTX',
'CMY',
'VGA',
'VGAB',
'VGAD',
'VATA',
'VATB',
'VATC',
'VATD',
'VATE',
'CFRA')
amr_raw_important_AMR <- amr_group_check[group %in% important_AMR_regex, ]
melted_important_AMR <- amr_melted_raw_analytic[ Level_ID =='Group' & Name %in% important_AMR_regex, ][Normalized_Count > 0, .(num_samples= .N, Normalized_Count= sum(Normalized_Count),log_Normalized_Count= log(sum(Normalized_Count))),by=.(Name, Packaging_samples)]#[order(-sum_class )]
melted_important_AMR[,.(sum_important_genes = sum(Normalized_Count))]
ggplot(data = melted_important_AMR , aes(x = Packaging_samples, y = Name)) +
geom_tile(aes(fill = log(Normalized_Count))) +
scale_fill_gradient(low = "lightgrey", high = "steelblue") +
geom_text(aes(label = num_samples), size=5) +
labs(fill = "Number of samples", y = "Gene name", x = '') +
theme(panel.background = element_blank())
#ggsave("~/Dropbox/WRITING/FC_meat_2019/FC_meat_manuscript/FCmeat_figures/Supp_AMR_important_genes.jpeg", width = 30, height = 20, units = "cm")
ggsave("FC_ground_beef_manuscript_figures/Supplemental_figures/Supplemental_Figure_1_AMR_important_genes.png", width = 30, height = 20, units = "cm")
#
##
###
#### Supplemental figure 2 - Microbiome at the Genus level by Packaging
###
##
#
microbiome_genus_sum <- microbiome_melted_analytic[Level_ID=="Genus", .(sum_genus= sum(Normalized_Count)),by=.(ID,sample, Name, Packaging, Treatment)][order(-Packaging )]
microbiome_genus_sum[,total:= sum(sum_genus), by=.(ID)]
microbiome_genus_sum[,percentage:= sum_genus/total ,by=.(ID, Name) ]
# only keep taxa greater than 1%
microbiome_genus_sum <- microbiome_genus_sum[percentage < .01, Name := 'Low Abundance Genus (< 1%)' ]
microbiome_genus_sum[,total:= sum(sum_genus), by=.(ID)]
microbiome_genus_sum[,percentage:= sum_genus/total ,by=.(ID, Name) ]
microbiome_genus_sum$Name = droplevels(microbiome_genus_sum$Name)
microbiome_genus_sum$Sample = factor(microbiome_genus_sum$sample ,levels=c("Sample 1","Sample 2","Sample 3","Sample 4","Sample 5","Sample 6","Sample 7","Sample 8","Sample 9","Sample 10","Sample 11",
"Sample 12","Sample 13","Sample 14","Sample 15","Sample 16"))
microbiome_genus_sum$Genus <- microbiome_genus_sum$Name
ggplot(microbiome_genus_sum, aes(x = Sample, y = percentage, fill = Genus)) +
geom_bar(stat = "identity")+
facet_wrap( ~ Packaging, scales='free',ncol = 2) +
#scale_fill_brewer(palette="Dark2") +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
strip.text.x=element_text(size=24),
strip.text.y=element_text(size=24, angle=0),
axis.text.x=element_text(size=24, angle=30, hjust=1),
axis.text.y=element_text(size=22),
axis.title=element_text(size=26),
legend.position="right",
panel.spacing=unit(0.1, "lines"),
plot.title=element_text(size=32, hjust=0.5),
legend.text=element_text(size=15),
legend.title=element_text(size=20),
panel.background = element_rect(fill = "white")
) +
scale_fill_tableau("Tableau 20", direction = "1") +
xlab('') +
ylab('Relative abundance')
ggsave("FC_ground_beef_manuscript_figures/Supplemental_figures/Supplemental_Figure_2_Microbiome_genus_by_packaging.png", width = 60, height = 40, units = "cm")
#
##
###
#### Supplemental Figure 3 - Microbiome at the phylum level by Packaging
###
##
#
ggplot(microbiome_phylum_sum, aes(x = Sample, y = percentage, fill = Phylum)) +
geom_bar(stat = "identity")+
facet_wrap( ~ Packaging, scales='free',ncol = 2) +
#scale_fill_brewer(palette="Dark2") +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
strip.text.x=element_text(size=24),
strip.text.y=element_text(size=24, angle=0),
axis.text.x=element_text(size=24, angle=30, hjust=1),
axis.text.y=element_text(size=22),
axis.title=element_text(size=26),
legend.position="right",
panel.spacing=unit(0.1, "lines"),
plot.title=element_text(size=32, hjust=0.5),
legend.text=element_text(size=15),
legend.title=element_text(size=20),
panel.background = element_rect(fill = "white")
) +
scale_fill_tableau("Tableau 20", direction = "1") +
xlab('') +
ylab('Relative abundance')
ggsave("FC_ground_beef_manuscript_figures/Supplemental_figures/Supplemental_Figure_3_Microbiome_phylum_by_packaging.png", width = 60, height = 40, units = "cm")
#
##
###
#### Supplemental Figure 4 - Resistome composition at the Class level by Packaging
###
##
#
ggplot(AMR_class_sum, aes(x = sample, y = percentage, fill = Class)) +
geom_bar(stat = "identity",colour = "black")+
facet_wrap( ~ Packaging, scales='free',ncol = 2) +
#scale_fill_brewer(palette="Dark2") +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
strip.text.x=element_text(size=24),
strip.text.y=element_text(size=24, angle=0),
axis.text.x=element_text(size=24, angle=30, hjust=1),
axis.text.y=element_text(size=22),
axis.title=element_text(size=26),
legend.position="right",
panel.spacing=unit(0.1, "lines"),
plot.title=element_text(size=32, hjust=0.5),
legend.text=element_text(size=15),
legend.title=element_text(size=20),
panel.background = element_rect(fill = "white")
) +
xlab('') +
ylab('Relative abundance') +
scale_fill_tableau("Tableau 20", direction = -1)
ggsave("FC_ground_beef_manuscript_figures/Supplemental_figures/Supplemental_Figure_4_Resistome_class_by_packaging.png", width = 60, height = 40, units = "cm")
| /scripts/FC_ground_beef_manuscript_figures.R | no_license | meglab-metagenomics/Ground_beef_metagenomics_manuscript | R | false | false | 15,653 | r | ### final figures
library(tidyverse)
library(RColorBrewer)
library(ggthemes)
library(ggpubr)
#
##
###
#### Figure 1 - NMDS comparing AMR samples by unique sample (dilution and normal)
###
##
#
#
##
###
#### Figure 2 showing resistome composition and microbiome composition
###
##
#
AMR_class_sum <- amr_melted_analytic[Level_ID=="Class", .(sum_class= sum(Normalized_Count)),by=.(ID,sample, Name, Packaging, Treatment)][order(-Packaging )]
AMR_class_sum[,total:= sum(sum_class), by=.(ID)]
AMR_class_sum[,percentage:= sum_class/total ,by=.(ID, Name) ]
AMR_class_sum$Name = droplevels(AMR_class_sum$Name)
AMR_class_sum$Name = factor(AMR_class_sum$Name ,levels=c("Sulfonamides","Rifampin","Trimethoprim","Triclosan","Fluoroquinolones","Aminocoumarins","Nitrofuran","Fosfomycin" , "Elfamycins" ,"Phenicol","Bacitracin","Cationic antimicrobial peptides","Aminoglycosides", "MLS" ,"betalactams" , "Multi-drug resistance" , "Tetracyclines"))
AMR_class_sum$sample = factor(AMR_class_sum$sample ,levels=c("Sample 1.1","Sample 1.2","Sample 2.1","Sample 2.2","Sample 3.1","Sample 3.2","Sample 4.1",
"Sample 4.2","Sample 5.1","Sample 5.2","Sample 6.1","Sample 6.2","Sample 7.1","Sample 7.2","Sample 8.1","Sample 8.2",
"Sample 9.1","Sample 9.2","Sample 10.1","Sample 10.2","Sample 11.1","Sample 11.2","Sample 12.1","Sample 12.2","Sample 13.1","Sample 13.2","Sample 14.1",
"Sample 14.2","Sample 15.1","Sample 15.2","Sample 16.1","Sample 16.2"))
AMR_class_sum$Treatment = factor(AMR_class_sum$Treatment ,levels=c("RWA","CONV"))
AMR_class_sum$Class <- AMR_class_sum$Name
#AMR_class_sum[,percentage:= round(sum_class/total, digits=2) ,by=.(ID, Name) ] removes some with low proportions
fig1_A <- ggplot(AMR_class_sum, aes(x = sample, y = percentage, fill = Class)) +
geom_bar(stat = "identity",colour = "black")+
facet_wrap( ~ Treatment, scales='free',ncol = 2) +
#scale_fill_brewer(palette="Dark2") +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
strip.text.x=element_text(size=24),
strip.text.y=element_text(size=24, angle=0),
axis.text.x=element_text(size=24, angle=30, hjust=1),
axis.text.y=element_text(size=22),
axis.title=element_text(size=26),
legend.position="right",
panel.spacing=unit(0.1, "lines"),
plot.title=element_text(size=32, hjust=0.5),
legend.text=element_text(size=15),
legend.title=element_text(size=20),
panel.background = element_rect(fill = "white")
) +
#ggtitle("Resistome composition by sample") +
xlab('') +
ylab('Relative abundance') +
scale_fill_tableau("Tableau 20", direction = -1)
fig1_A
#
## Microbiome
#
microbiome_phylum_sum <- microbiome_melted_analytic[Level_ID=="Phylum", .(sum_phylum= sum(Normalized_Count)),by=.(ID,sample, Name, Packaging, Treatment)][order(-Packaging )]
microbiome_phylum_sum[,total:= sum(sum_phylum), by=.(ID)]
microbiome_phylum_sum[,percentage:= sum_phylum/total ,by=.(ID, Name) ]
# only keep taxa greater than 1%
microbiome_phylum_sum <- microbiome_phylum_sum[percentage < .01, Name := 'Low Abundance Phyla (< 1%)' ]
microbiome_phylum_sum[,total:= sum(sum_phylum), by=.(ID)]
microbiome_phylum_sum[,percentage:= sum_phylum/total ,by=.(ID, Name) ]
microbiome_phylum_sum$Name = droplevels(microbiome_phylum_sum$Name)
microbiome_phylum_sum$Name = factor(microbiome_phylum_sum$Name ,levels=c("Low Abundance Phyla (< 1%)","Planctomycetes","Gemmatimonadetes","Chloroflexi","Verrucomicrobia", "Acidobacteria","Actinobacteria" ,"Bacteroidetes" , "Proteobacteria" , "Firmicutes"))
microbiome_phylum_sum$Sample = factor(microbiome_phylum_sum$sample ,levels=c("Sample 1","Sample 2","Sample 3","Sample 4","Sample 5","Sample 6","Sample 7","Sample 8","Sample 9","Sample 10","Sample 11",
"Sample 12","Sample 13","Sample 14","Sample 15","Sample 16"))
microbiome_phylum_sum$Treatment = factor(microbiome_phylum_sum$Treatment ,levels=c("RWA","CONV"))
microbiome_phylum_sum$Phylum <- microbiome_phylum_sum$Name
#microbiome_phylum_sum[,percentage:= round(sum_class/total, digits=2) ,by=.(ID, Name) ] removes some with low proportions
fig1_B <- ggplot(microbiome_phylum_sum, aes(x = Sample, y = percentage, fill = Phylum)) +
geom_bar(stat = "identity")+
facet_wrap( ~ Treatment, scales='free',ncol = 2) +
#scale_fill_brewer(palette="Dark2") +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
strip.text.x=element_text(size=24),
strip.text.y=element_text(size=24, angle=0),
axis.text.x=element_text(size=24, angle=30, hjust=1),
axis.text.y=element_text(size=22),
axis.title=element_text(size=26),
legend.position="right",
panel.spacing=unit(0.1, "lines"),
plot.title=element_text(size=32, hjust=0.5),
legend.text=element_text(size=15),
legend.title=element_text(size=20),
panel.background = element_rect(fill = "white")
) +
scale_fill_tableau("Tableau 20", direction = "1") +
#ggtitle("Microbiome composition in by treatment (only taxa > 1% per sample)") +
xlab('') +
ylab('Relative abundance')
fig1_B
## Combine figures
figure <- ggarrange(fig1_A, fig1_B,
labels = c("A)", "B)"),
ncol = 1, nrow = 2, vjust = 1.4, font.label = list(size = 30, color = "black", face =
"bold", family = NULL))
# Output jpeg figure
jpeg("FC_ground_beef_manuscript_figures/Figure1-FC_meat_resistome_and_microbiome_composition_by_Treatment.jpeg", width =1850, height = 1250)
figure
dev.off()
#
##
###
#### Figure 3 - Resistome ordination by treatment
###
##
#
# Use figure "graphs/AMR/Treatment/NMDS_Treatment_Class.png"
#
##
###
#### Figure 4 - Resistome Diversity figures
###
##
#
par(mfrow = c(2, 2))
par(cex = 0.6)
par(mar = c(3, 4, 1, 1))
par(oma = c(4,3,4,1)) ## moves the plot area, not for individual plots
par(tcl = -0.25)
par(mgp = c(2, 0.6, 0))
boxplot(metadata$AMR_class_Richness ~ metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 3, "AMR Class", line = 1, cex=2)
mtext(side = 2, "Richness", line = 4, cex=2)
boxplot(metadata$AMR_mech_Richness ~ metadata$Treatment,col=c("Red","Grey"),names=FALSE)
#title("AMR mechanism richness by group")
mtext(side = 3, "AMR Mechanism", line = 1, cex=2)
boxplot(metadata$AMR_class_Shannon ~ metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 2, "Shannon\'s Diversity", line = 4, cex=2)
boxplot(metadata$AMR_mech_Shannon ~ metadata$Treatment, col=c("Red","Grey"),names=FALSE)
par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0), new = TRUE)
plot(0, 0, type = "n", bty = "n", xaxt = "n", yaxt = "n")
legend("bottom", c("CONV","RWA"),x.intersp = .3, xpd = TRUE, horiz = TRUE, inset = c(9, 0), bty = "n", pch = 15, fill = c("Red","Grey"), cex = 1.5)
# Export as png 1200 x 800
########################
##############
########
###
# MICROBIOME
###
########
##############
########################
#
##
###
#### Figure 5 - Microbiome ordination by treatment at the phylum level
###
##
#
# Use figure "graphs/Microbiome/Treatment/NMDS_Treatment_Phylum.png"
#
##
###
#### Figure 6 - Resistome Diversity figures
###
##
#
par(mfrow = c(2, 3))
par(cex = 0.6)
par(mar = c(3, 4, 1, 1))
par(oma = c(4,3,4,1)) ## moves the plot area, not for individual plots
par(tcl = -0.25)
par(mgp = c(2, 0.6, 0))
boxplot(microbiome_metadata$microbiome_phylum_Richness ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 3, "Phylum", line = 1, cex=2)
mtext(side = 2, "Richness", line = 4, cex=2)
boxplot(microbiome_metadata$microbiome_class_Richness ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 3, "Class", line = 1, cex=2)
boxplot(microbiome_metadata$microbiome_order_Richness ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 3, "Order", line = 1, cex=2)
boxplot(microbiome_metadata$microbiome_phylum_Shannon ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
mtext(side = 2, "Shannon's Diversity", line = 4, cex=2)
boxplot(microbiome_metadata$microbiome_class_Shannon ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
boxplot(microbiome_metadata$microbiome_order_Shannon ~ microbiome_metadata$Treatment, col=c("Red","Grey"),names=FALSE)
par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0), new = TRUE)
plot(0, 0, type = "n", bty = "n", xaxt = "n", yaxt = "n")
legend("bottom", c("CONV","RWA"),x.intersp = .5, xpd = TRUE, horiz = TRUE, inset = c(9, 0), bty = "n", pch = 15, fill = c("Red","Grey"), cex = 1.5)
# Export as png 1200 x 800
#
##
###
#### Figure 7 - Microbiome ordination by store at the phylum level
###
##
#
# Use figure "graphs/Microbiome/Store/NMDS_Blinded_Store_Phylum.png"
###################################################
## ##
## Supplemental figures ##
## ##
###################################################
#
##
###
#### Supplemental Figure 1 - Resistome ordination at the phylum level by dilution
###
##
#
#
##
###
#### Supplemental Figure 1 - Heatmap
###
##
#
### Looking for clinically important AMR genes
amr_group_check <- amr_group_raw[!group %in% snp_regex, ]
important_AMR_regex = c('OXA',
'SME',
'sme',
'IMI',
'NDM',
'GES',
'KPC',
'CPHA',
'TEM',
'SHV',
'CTX',
'CMY',
'VGA',
'VGAB',
'VGAD',
'VATA',
'VATB',
'VATC',
'VATD',
'VATE',
'CFRA')
amr_raw_important_AMR <- amr_group_check[group %in% important_AMR_regex, ]
melted_important_AMR <- amr_melted_raw_analytic[ Level_ID =='Group' & Name %in% important_AMR_regex, ][Normalized_Count > 0, .(num_samples= .N, Normalized_Count= sum(Normalized_Count),log_Normalized_Count= log(sum(Normalized_Count))),by=.(Name, Packaging_samples)]#[order(-sum_class )]
melted_important_AMR[,.(sum_important_genes = sum(Normalized_Count))]
ggplot(data = melted_important_AMR , aes(x = Packaging_samples, y = Name)) +
geom_tile(aes(fill = log(Normalized_Count))) +
scale_fill_gradient(low = "lightgrey", high = "steelblue") +
geom_text(aes(label = num_samples), size=5) +
labs(fill = "Number of samples", y = "Gene name", x = '') +
theme(panel.background = element_blank())
#ggsave("~/Dropbox/WRITING/FC_meat_2019/FC_meat_manuscript/FCmeat_figures/Supp_AMR_important_genes.jpeg", width = 30, height = 20, units = "cm")
ggsave("FC_ground_beef_manuscript_figures/Supplemental_figures/Supplemental_Figure_1_AMR_important_genes.png", width = 30, height = 20, units = "cm")
#
##
###
#### Supplemental figure 2 - Microbiome at the Genus level by Packaging
###
##
#
microbiome_genus_sum <- microbiome_melted_analytic[Level_ID=="Genus", .(sum_genus= sum(Normalized_Count)),by=.(ID,sample, Name, Packaging, Treatment)][order(-Packaging )]
microbiome_genus_sum[,total:= sum(sum_genus), by=.(ID)]
microbiome_genus_sum[,percentage:= sum_genus/total ,by=.(ID, Name) ]
# only keep taxa greater than 1%
microbiome_genus_sum <- microbiome_genus_sum[percentage < .01, Name := 'Low Abundance Genus (< 1%)' ]
microbiome_genus_sum[,total:= sum(sum_genus), by=.(ID)]
microbiome_genus_sum[,percentage:= sum_genus/total ,by=.(ID, Name) ]
microbiome_genus_sum$Name = droplevels(microbiome_genus_sum$Name)
microbiome_genus_sum$Sample = factor(microbiome_genus_sum$sample ,levels=c("Sample 1","Sample 2","Sample 3","Sample 4","Sample 5","Sample 6","Sample 7","Sample 8","Sample 9","Sample 10","Sample 11",
"Sample 12","Sample 13","Sample 14","Sample 15","Sample 16"))
microbiome_genus_sum$Genus <- microbiome_genus_sum$Name
ggplot(microbiome_genus_sum, aes(x = Sample, y = percentage, fill = Genus)) +
geom_bar(stat = "identity")+
facet_wrap( ~ Packaging, scales='free',ncol = 2) +
#scale_fill_brewer(palette="Dark2") +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
strip.text.x=element_text(size=24),
strip.text.y=element_text(size=24, angle=0),
axis.text.x=element_text(size=24, angle=30, hjust=1),
axis.text.y=element_text(size=22),
axis.title=element_text(size=26),
legend.position="right",
panel.spacing=unit(0.1, "lines"),
plot.title=element_text(size=32, hjust=0.5),
legend.text=element_text(size=15),
legend.title=element_text(size=20),
panel.background = element_rect(fill = "white")
) +
scale_fill_tableau("Tableau 20", direction = "1") +
xlab('') +
ylab('Relative abundance')
ggsave("FC_ground_beef_manuscript_figures/Supplemental_figures/Supplemental_Figure_2_Microbiome_genus_by_packaging.png", width = 60, height = 40, units = "cm")
#
##
###
#### Supplemental Figure 3 - Microbiome at the phylum level by Packaging
###
##
#
ggplot(microbiome_phylum_sum, aes(x = Sample, y = percentage, fill = Phylum)) +
geom_bar(stat = "identity")+
facet_wrap( ~ Packaging, scales='free',ncol = 2) +
#scale_fill_brewer(palette="Dark2") +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
strip.text.x=element_text(size=24),
strip.text.y=element_text(size=24, angle=0),
axis.text.x=element_text(size=24, angle=30, hjust=1),
axis.text.y=element_text(size=22),
axis.title=element_text(size=26),
legend.position="right",
panel.spacing=unit(0.1, "lines"),
plot.title=element_text(size=32, hjust=0.5),
legend.text=element_text(size=15),
legend.title=element_text(size=20),
panel.background = element_rect(fill = "white")
) +
scale_fill_tableau("Tableau 20", direction = "1") +
xlab('') +
ylab('Relative abundance')
ggsave("FC_ground_beef_manuscript_figures/Supplemental_figures/Supplemental_Figure_3_Microbiome_phylum_by_packaging.png", width = 60, height = 40, units = "cm")
#
##
###
#### Supplemental Figure 4 - Resistome composition at the Class level by Packaging
###
##
#
ggplot(AMR_class_sum, aes(x = sample, y = percentage, fill = Class)) +
geom_bar(stat = "identity",colour = "black")+
facet_wrap( ~ Packaging, scales='free',ncol = 2) +
#scale_fill_brewer(palette="Dark2") +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
strip.text.x=element_text(size=24),
strip.text.y=element_text(size=24, angle=0),
axis.text.x=element_text(size=24, angle=30, hjust=1),
axis.text.y=element_text(size=22),
axis.title=element_text(size=26),
legend.position="right",
panel.spacing=unit(0.1, "lines"),
plot.title=element_text(size=32, hjust=0.5),
legend.text=element_text(size=15),
legend.title=element_text(size=20),
panel.background = element_rect(fill = "white")
) +
xlab('') +
ylab('Relative abundance') +
scale_fill_tableau("Tableau 20", direction = -1)
ggsave("FC_ground_beef_manuscript_figures/Supplemental_figures/Supplemental_Figure_4_Resistome_class_by_packaging.png", width = 60, height = 40, units = "cm")
|
#' Create a description object for a parameter of a machine learning algorithm.
#'
#' This specializes \code{\link{Param}} by adding a few more attributes,
#' like a default value, whether it refers to a training or a predict function, etc.
#'
#' The S3 class is a \code{\link{Param}} which additionally stores these elements:
#' \describe{
#' \item{default [any]}{See argument of same name.}
#' \item{has.default [\code{logical(1)}]}{Was a default value provided?}
#' \item{when [\code{character(1)}]}{See argument of same name.}
#' }
#'
#' @param id [\code{character(1)}]\cr
#' See \code{\link{Param}}.
#' @param len [\code{integer(1)}]\cr
#' See \code{\link{Param}}.
# For vector parameters of a learner it is sometimes useful to not explicitly set
# the length. For this reason, \code{NA} is also allowed, which means
# vectors of any length are ok as values.
#' @param lower [\code{numeric}]\cr
#' See \code{\link{Param}}.
#' @param upper [\code{numeric}]\cr
#' See \code{\link{Param}}.
#' @param values [\code{vector} | \code{list}]\cr
#' See \code{\link{Param}}.
#' @param allow.inf [\code{logical(1)}]\cr
#' See \code{\link{Param}}.
#' @param requires [\code{NULL} | R expression]\cr
#' See \code{\link{Param}}.
#' @param default [any]\cr
#' See \code{\link{Param}}.
#' @param tunable [\code{logical(1)}]\cr
#' See \code{\link{Param}}.
#' @param when [\code{character(1)}]\cr
#' Specifies when parameter is used in the learner: \dQuote{train}, \dQuote{predict} or \dQuote{both}.
#' Default is \dQuote{train}.
#' @return [\code{\link{LearnerParam}}].
#' @name LearnerParam
#' @rdname LearnerParam
NULL
makeLearnerParam = function(p, when) {
p$when = when
class(p) = c("LearnerParam", "Param")
return(p)
}
#' @export
print.LearnerParam = function(x, ..., trafo = TRUE, used = TRUE) {
print.Param(x, trafo = trafo)
if (used)
catf("Used: %s.", x$when)
}
| /ParamHelpers/R/LearnerParam.R | no_license | ingted/R-Examples | R | false | false | 1,905 | r | #' Create a description object for a parameter of a machine learning algorithm.
#'
#' This specializes \code{\link{Param}} by adding a few more attributes,
#' like a default value, whether it refers to a training or a predict function, etc.
#'
#' The S3 class is a \code{\link{Param}} which additionally stores these elements:
#' \describe{
#' \item{default [any]}{See argument of same name.}
#' \item{has.default [\code{logical(1)}]}{Was a default value provided?}
#' \item{when [\code{character(1)}]}{See argument of same name.}
#' }
#'
#' @param id [\code{character(1)}]\cr
#' See \code{\link{Param}}.
#' @param len [\code{integer(1)}]\cr
#' See \code{\link{Param}}.
# For vector parameters of a learner it is sometimes useful to not explicitly set
# the length. For this reason, \code{NA} is also allowed, which means
# vectors of any length are ok as values.
#' @param lower [\code{numeric}]\cr
#' See \code{\link{Param}}.
#' @param upper [\code{numeric}]\cr
#' See \code{\link{Param}}.
#' @param values [\code{vector} | \code{list}]\cr
#' See \code{\link{Param}}.
#' @param allow.inf [\code{logical(1)}]\cr
#' See \code{\link{Param}}.
#' @param requires [\code{NULL} | R expression]\cr
#' See \code{\link{Param}}.
#' @param default [any]\cr
#' See \code{\link{Param}}.
#' @param tunable [\code{logical(1)}]\cr
#' See \code{\link{Param}}.
#' @param when [\code{character(1)}]\cr
#' Specifies when parameter is used in the learner: \dQuote{train}, \dQuote{predict} or \dQuote{both}.
#' Default is \dQuote{train}.
#' @return [\code{\link{LearnerParam}}].
#' @name LearnerParam
#' @rdname LearnerParam
NULL
makeLearnerParam = function(p, when) {
p$when = when
class(p) = c("LearnerParam", "Param")
return(p)
}
#' @export
print.LearnerParam = function(x, ..., trafo = TRUE, used = TRUE) {
print.Param(x, trafo = trafo)
if (used)
catf("Used: %s.", x$when)
}
|
## plots Plot2 and create the Plot2.png
##get dataset
getData <- function(){
if(!file.exists("household_power_consumption.txt")) {
##download and unzip file into current workind directory
download.file(url="https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip",destfile="ElecticPowerConsumption.zip", method="auto")
unzip("ElecticPowerConsumption.zip",exdir=".",overwrite = TRUE )
}
##get dataset
household_power_consumption <- read.table("household_power_consumption.txt",header=TRUE,sep=";",quote="", na.strings="?" )
##remove missing fields observations
household_power_consumption_complete <- household_power_consumption[complete.cases(household_power_consumption),]
##Convert Date Column to Date Type
household_power_consumption_complete$Date <- as.Date(household_power_consumption_complete$Date,"%d/%m/%Y")
##Convert Time Column to POSIXlt and POSIXct Type
household_power_consumption_complete$Time <- strptime(paste(household_power_consumption_complete$Date, household_power_consumption_complete$Time,sep=" "), "%Y-%m-%d %H:%M:%S")
##data from the dates 2007-02-01 and 2007-02-02.
household_consumptionFiltered <-household_power_consumption_complete[which(household_power_consumption_complete$Date>="2007-02-01" & household_power_consumption_complete$Date<="2007-02-02"),]
household_consumptionFiltered
}
##Main Program
##get the data to plot
data <- getData()
##Construct a png file
png(file = "Plot2.png", bg = "transparent",width = 480, height = 480)
##Plot graph - Plot 2
plot(data$Time, data$Global_active_power,type="n",ylab = "Global Active Power (kilowatts)",xlab="")
lines(data$Time, data$Global_active_power)
##Close PNG device
dev.off()
| /Plot2.R | no_license | works123/ExData_Plotting1 | R | false | false | 1,951 | r | ## plots Plot2 and create the Plot2.png
##get dataset
getData <- function(){
if(!file.exists("household_power_consumption.txt")) {
##download and unzip file into current workind directory
download.file(url="https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip",destfile="ElecticPowerConsumption.zip", method="auto")
unzip("ElecticPowerConsumption.zip",exdir=".",overwrite = TRUE )
}
##get dataset
household_power_consumption <- read.table("household_power_consumption.txt",header=TRUE,sep=";",quote="", na.strings="?" )
##remove missing fields observations
household_power_consumption_complete <- household_power_consumption[complete.cases(household_power_consumption),]
##Convert Date Column to Date Type
household_power_consumption_complete$Date <- as.Date(household_power_consumption_complete$Date,"%d/%m/%Y")
##Convert Time Column to POSIXlt and POSIXct Type
household_power_consumption_complete$Time <- strptime(paste(household_power_consumption_complete$Date, household_power_consumption_complete$Time,sep=" "), "%Y-%m-%d %H:%M:%S")
##data from the dates 2007-02-01 and 2007-02-02.
household_consumptionFiltered <-household_power_consumption_complete[which(household_power_consumption_complete$Date>="2007-02-01" & household_power_consumption_complete$Date<="2007-02-02"),]
household_consumptionFiltered
}
##Main Program
##get the data to plot
data <- getData()
##Construct a png file
png(file = "Plot2.png", bg = "transparent",width = 480, height = 480)
##Plot graph - Plot 2
plot(data$Time, data$Global_active_power,type="n",ylab = "Global Active Power (kilowatts)",xlab="")
lines(data$Time, data$Global_active_power)
##Close PNG device
dev.off()
|
# Define UI ----
ui <- fluidPage(
titlePanel("QC Tool"),
sidebarLayout(
sidebarPanel(
titlePanel("Controls"),
helpText("Select the required parameters"),
uiOutput("choose_haulSubset"),
uiOutput("choose_species"),
helpText(paste("We are operating on cruise year", maxYear)),
uiOutput("list_hauls"),
titlePanel("Legends"),
helpText("Top Plot: Comparing catch weight per haul (sample condition index, K) with the estimated weight based on the lengths of the fish in the haul. In RED: the mean and the standard deviation of K for this specific cruise (based on the last 5 years of data). Orange: Highlighted haul(s)"),
helpText("Bottom Plot: ORANGE line: Length frequency distribution for selected haul from Top Plot compared to the BLUE line: five years historical length frequency from the same station of the haul.")
),
mainPanel(
titlePanel("Main Panel"),
# Main Plot
plotlyOutput("plot_main"),
plotOutput("plot_sub"),
verbatimTextOutput("info")
)
)
)
| /inst/app/ui.R | permissive | iambaim/icesHackathon2018 | R | false | false | 1,059 | r | # Define UI ----
ui <- fluidPage(
titlePanel("QC Tool"),
sidebarLayout(
sidebarPanel(
titlePanel("Controls"),
helpText("Select the required parameters"),
uiOutput("choose_haulSubset"),
uiOutput("choose_species"),
helpText(paste("We are operating on cruise year", maxYear)),
uiOutput("list_hauls"),
titlePanel("Legends"),
helpText("Top Plot: Comparing catch weight per haul (sample condition index, K) with the estimated weight based on the lengths of the fish in the haul. In RED: the mean and the standard deviation of K for this specific cruise (based on the last 5 years of data). Orange: Highlighted haul(s)"),
helpText("Bottom Plot: ORANGE line: Length frequency distribution for selected haul from Top Plot compared to the BLUE line: five years historical length frequency from the same station of the haul.")
),
mainPanel(
titlePanel("Main Panel"),
# Main Plot
plotlyOutput("plot_main"),
plotOutput("plot_sub"),
verbatimTextOutput("info")
)
)
)
|
# Endpoints
#
# Endpoints API for different services in SKIL
#
# OpenAPI spec version: 1.2.0-rc1
#
# Generated by: https://github.com/swagger-api/swagger-codegen.git
#' SingleRecord Class
#'
#' @field values
#' @field uri
#'
#' @importFrom R6 R6Class
#' @importFrom jsonlite fromJSON toJSON
#' @export
SingleRecord <- R6::R6Class(
'SingleRecord',
public = list(
`values` = NULL,
`uri` = NULL,
initialize = function(`values`, `uri`){
if (!missing(`values`)) {
stopifnot(is.list(`values`), length(`values`) != 0)
lapply(`values`, function(x) stopifnot(is.character(x)))
self$`values` <- `values`
}
if (!missing(`uri`)) {
stopifnot(is.character(`uri`), length(`uri`) == 1)
self$`uri` <- `uri`
}
},
toJSON = function() {
SingleRecordObject <- list()
if (!is.null(self$`values`)) {
SingleRecordObject[['values']] <- self$`values`
}
if (!is.null(self$`uri`)) {
SingleRecordObject[['uri']] <- self$`uri`
}
SingleRecordObject
},
fromJSON = function(SingleRecordJson) {
SingleRecordObject <- jsonlite::fromJSON(SingleRecordJson)
if (!is.null(SingleRecordObject$`values`)) {
self$`values` <- SingleRecordObject$`values`
}
if (!is.null(SingleRecordObject$`uri`)) {
self$`uri` <- SingleRecordObject$`uri`
}
},
toJSONString = function() {
sprintf(
'{
"values": [%s],
"uri": %s
}',
lapply(self$`values`, function(x) paste(paste0('"', x, '"'), sep=",")),
self$`uri`
)
},
fromJSONString = function(SingleRecordJson) {
SingleRecordObject <- jsonlite::fromJSON(SingleRecordJson)
self$`values` <- SingleRecordObject$`values`
self$`uri` <- SingleRecordObject$`uri`
}
)
)
| /r/R/SingleRecord.r | permissive | farizrahman4u/skil-clients | R | false | false | 1,928 | r | # Endpoints
#
# Endpoints API for different services in SKIL
#
# OpenAPI spec version: 1.2.0-rc1
#
# Generated by: https://github.com/swagger-api/swagger-codegen.git
#' SingleRecord Class
#'
#' @field values
#' @field uri
#'
#' @importFrom R6 R6Class
#' @importFrom jsonlite fromJSON toJSON
#' @export
SingleRecord <- R6::R6Class(
'SingleRecord',
public = list(
`values` = NULL,
`uri` = NULL,
initialize = function(`values`, `uri`){
if (!missing(`values`)) {
stopifnot(is.list(`values`), length(`values`) != 0)
lapply(`values`, function(x) stopifnot(is.character(x)))
self$`values` <- `values`
}
if (!missing(`uri`)) {
stopifnot(is.character(`uri`), length(`uri`) == 1)
self$`uri` <- `uri`
}
},
toJSON = function() {
SingleRecordObject <- list()
if (!is.null(self$`values`)) {
SingleRecordObject[['values']] <- self$`values`
}
if (!is.null(self$`uri`)) {
SingleRecordObject[['uri']] <- self$`uri`
}
SingleRecordObject
},
fromJSON = function(SingleRecordJson) {
SingleRecordObject <- jsonlite::fromJSON(SingleRecordJson)
if (!is.null(SingleRecordObject$`values`)) {
self$`values` <- SingleRecordObject$`values`
}
if (!is.null(SingleRecordObject$`uri`)) {
self$`uri` <- SingleRecordObject$`uri`
}
},
toJSONString = function() {
sprintf(
'{
"values": [%s],
"uri": %s
}',
lapply(self$`values`, function(x) paste(paste0('"', x, '"'), sep=",")),
self$`uri`
)
},
fromJSONString = function(SingleRecordJson) {
SingleRecordObject <- jsonlite::fromJSON(SingleRecordJson)
self$`values` <- SingleRecordObject$`values`
self$`uri` <- SingleRecordObject$`uri`
}
)
)
|
library(magic)
### Name: hadamard
### Title: Hadamard matrices
### Aliases: hadamard is.hadamard sylvester
### Keywords: array
### ** Examples
is.hadamard(sylvester(4))
image(sylvester(5))
| /data/genthat_extracted_code/magic/examples/hadamard.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 197 | r | library(magic)
### Name: hadamard
### Title: Hadamard matrices
### Aliases: hadamard is.hadamard sylvester
### Keywords: array
### ** Examples
is.hadamard(sylvester(4))
image(sylvester(5))
|
library(shiny)
shinyUI(fluidPage(
# Application title
titlePanel("Skewed Normal Distributions"),
column(12,
helpText("This page lets you vary the shape of a skewed normal distribution.",
"The case of a standard normal distribution is also included when shape and location are 0 and scale is 1.",
"You can play around with the parameters and see the shape of the curve change.",
"At any time you can return to the standard normal case by pressing reset.")
),
sidebarLayout(
sidebarPanel(
# This function creates a HTML DIV block which is initially replaced with the
# actual input controls by the server function.
# After pressing the reset button below, the input controls are reset to
# their initial values (actually the are completely replaced).
uiOutput("input_controls"),
hr(),
actionButton("resetButton", "Reset")
),
mainPanel(
plotOutput("normPlot"),
p(textOutput("mean", inline = TRUE),
textOutput("variance", inline = TRUE),
textOutput("median", inline = TRUE)),
p(),
p("For more information see the ",
a("github repository", href="https://github.com/rubberbandman62/skewedDistributions", target="_blank"),
br(),
"You're also welcome to check the pitch presentation on ",
a("github.io", href="http://rubberbandman62.github.io/skewedDistributionsPitch", target="_blank"))
)
)
))
| /ui.r | no_license | pra1981/skewedDistributions | R | false | false | 1,581 | r | library(shiny)
shinyUI(fluidPage(
# Application title
titlePanel("Skewed Normal Distributions"),
column(12,
helpText("This page lets you vary the shape of a skewed normal distribution.",
"The case of a standard normal distribution is also included when shape and location are 0 and scale is 1.",
"You can play around with the parameters and see the shape of the curve change.",
"At any time you can return to the standard normal case by pressing reset.")
),
sidebarLayout(
sidebarPanel(
# This function creates a HTML DIV block which is initially replaced with the
# actual input controls by the server function.
# After pressing the reset button below, the input controls are reset to
# their initial values (actually the are completely replaced).
uiOutput("input_controls"),
hr(),
actionButton("resetButton", "Reset")
),
mainPanel(
plotOutput("normPlot"),
p(textOutput("mean", inline = TRUE),
textOutput("variance", inline = TRUE),
textOutput("median", inline = TRUE)),
p(),
p("For more information see the ",
a("github repository", href="https://github.com/rubberbandman62/skewedDistributions", target="_blank"),
br(),
"You're also welcome to check the pitch presentation on ",
a("github.io", href="http://rubberbandman62.github.io/skewedDistributionsPitch", target="_blank"))
)
)
))
|
testlist <- list(m = NULL, repetitions = 0L, in_m = structure(c(2.09573821228693e-236, 3.88583085748592e-208, 9.35124901230701e-235, 0, 0, 0), .Dim = c(6L, 1L)))
result <- do.call(CNull:::communities_individual_based_sampling_beta_interleaved_matrices,testlist)
str(result) | /CNull/inst/testfiles/communities_individual_based_sampling_beta_interleaved_matrices/AFL_communities_individual_based_sampling_beta_interleaved_matrices/communities_individual_based_sampling_beta_interleaved_matrices_valgrind_files/1615840817-test.R | no_license | akhikolla/updatedatatype-list2 | R | false | false | 275 | r | testlist <- list(m = NULL, repetitions = 0L, in_m = structure(c(2.09573821228693e-236, 3.88583085748592e-208, 9.35124901230701e-235, 0, 0, 0), .Dim = c(6L, 1L)))
result <- do.call(CNull:::communities_individual_based_sampling_beta_interleaved_matrices,testlist)
str(result) |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fars_functions.R
\name{fars_summarize_years}
\alias{fars_summarize_years}
\title{Summarize fars accident data for a given set of years}
\usage{
fars_summarize_years(years)
}
\arguments{
\item{years}{A vector containing the years for which data is required
If the input parameter is not convertable to a string, a warning message will be produced.
The warning message for an input of "foo" reads: 'In make_filename("foo") : NAs introduced by coercion'
The function fars_summarize_years imports from packages as follows:}
}
\value{
dataframe
For an input parameter of "1994", the returned string is "accident_1994.csv.bz2". For a non-integer input value of,
for example, "foo", the returned string is ""accident_NA.csv.bz2"
}
\description{
This function takes a set of years, and returns accident data from the corresponding fars files.
}
\examples{
fars_summarize_years(c(2013,2014))
}
| /man/fars_summarize_years.Rd | no_license | monotreme/Asswk4Package | R | false | true | 968 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fars_functions.R
\name{fars_summarize_years}
\alias{fars_summarize_years}
\title{Summarize fars accident data for a given set of years}
\usage{
fars_summarize_years(years)
}
\arguments{
\item{years}{A vector containing the years for which data is required
If the input parameter is not convertable to a string, a warning message will be produced.
The warning message for an input of "foo" reads: 'In make_filename("foo") : NAs introduced by coercion'
The function fars_summarize_years imports from packages as follows:}
}
\value{
dataframe
For an input parameter of "1994", the returned string is "accident_1994.csv.bz2". For a non-integer input value of,
for example, "foo", the returned string is ""accident_NA.csv.bz2"
}
\description{
This function takes a set of years, and returns accident data from the corresponding fars files.
}
\examples{
fars_summarize_years(c(2013,2014))
}
|
#' @title DataBlock
#'
#' @description Generic container to quickly build `Datasets` and `DataLoaders`
#'
#'
#' @param blocks blocks
#' @param dl_type dl_type
#' @param getters getters
#' @param n_inp n_inp is the number of elements in the tuples that should be considered part of the input and will default to 1 if tfms consists of one set of transforms
#' @param item_tfms One or several transforms applied to the items before batching them
#' @param batch_tfms One or several transforms applied to the batches once they are formed
#'
#' @export
DataBlock <- function(blocks = NULL, dl_type = NULL, getters = NULL,
n_inp = NULL, item_tfms = NULL, batch_tfms = NULL,
...) {
args <- list(
blocks = blocks,
dl_type = dl_type,
getters = getters,
n_inp = n_inp,
item_tfms = item_tfms,
batch_tfms = batch_tfms,
...
)
if(!is.null(args$batch_tfms)) {
args$batch_tfms <- unlist(args$batch_tfms)
}
do.call(vision$gan$DataBlock, args)
}
#' @title TransformBlock
#'
#' @description A basic wrapper that links defaults transforms for the data block API
#'
#'
#' @param type_tfms type_tfms
#' @param item_tfms item_tfms
#' @param batch_tfms one or several transforms applied to the batches once they are formed
#' @param dl_type dl_type
#' @param dls_kwargs dls_kwargs
#'
#' @export
TransformBlock <- function(type_tfms = NULL, item_tfms = NULL,
batch_tfms = NULL, dl_type = NULL,
dls_kwargs = NULL) {
if(missing(type_tfms) & missing(item_tfms) & missing(batch_tfms) & missing(dl_type) & missing(dls_kwargs)) {
invisible(vision$gan$TransformBlock)
} else {
args <- list(
type_tfms = type_tfms,
item_tfms = item_tfms,
batch_tfms = batch_tfms,
dl_type = dl_type,
dls_kwargs = dls_kwargs
)
do.call(vision$gan$TransformBlock, args)
}
}
#' @title ImageBlock
#'
#' @description A `TransformBlock` for images of `cls`
#'
#'
#' @export
ImageBlock <- function() {
invisible(vision$gan$ImageBlock)
}
#' @title Generate_noise
#'
#'
#' @param fn fn
#' @param size size
#'
#' @export
generate_noise <- function(fn, size = 100) {
if(missing(fn)) {
invisible(vision$gan$generate_noise)
} else {
args <- list(
fn = fn,
size = as.integer(size)
)
do.call(vision$gan$generate_noise,args)
}
}
#' @title IndexSplitter
#'
#' @description Split `items` so that `val_idx` are in the validation set and the others in the training set
#'
#'
#' @param valid_idx The indices to use for the validation set (defaults to a random split otherwise)
#'
#' @export
IndexSplitter <- function(valid_idx) {
if(missing(valid_idx)) {
invisible(vision$gan$IndexSplitter)
} else {
args <- list(
valid_idx = valid_idx
)
do.call(vision$gan$IndexSplitter,args)
}
}
#' @title FileSplitter
#'
#' @description Split `items` by providing file `fname` (contains names of valid items separated by newline).
#'
#'
#' @param fname fname
#'
#' @export
FileSplitter <- function(fname) {
if(missing(fname)) {
vision$gan$FileSplitter
} else {
vision$gan$FileSplitter(
fname = fname
)
}
}
#' @title dataloaders
#'
#' @description Create a `DataLoaders` object from `source`
#'
#'
#' @param source source
#' @param ... additional parameters to pass
#'
#' @export
dataloaders <- function(object, ...) {
my_list <- list(
source = source,
...
)
for (i in 1:length(my_list)) {
if(names(my_list)[[i]]=='bs') {
my_list[['bs']] = as.integer(my_list[['bs']])
} else if (names(my_list)[[i]]=='batch_size') {
my_list[['batch_size']] = as.integer(my_list[['batch_size']])
} else if (names(my_list)[[i]]=='seq_len') {
my_list[['seq_len']] = as.integer(my_list[['seq_len']])
}
}
do.call(object$dataloaders,my_list)
}
#' @title Basic_generator
#'
#' @description A basic generator from `in_sz` to images `n_channels` x `out_size` x `out_size`.
#'
#'
#' @param out_size out_size
#' @param n_channels n_channels
#' @param in_sz in_sz
#' @param n_features The number of features
#' @param n_extra_layers The number of extra layers
#' @param ... additional params to pass
#' @param bias bias
#' @param ndim ndim
#' @param norm_type norm_type
#' @param bn_1st bn_1st
#' @param act_cls act_cls
#' @param transpose transpose
#' @param init init
#' @param xtra xtra
#' @param bias_std bias_std
#' @param dilation dilation
#' @param groups groups
#'
#' @export
basic_generator <- function(out_size, n_channels, in_sz = 100,
n_features = 64, n_extra_layers = 0,
bias = NULL, ndim = 2,
norm_type = 1, bn_1st = TRUE,
act_cls = nn$ReLU, init = "auto",
xtra = NULL, bias_std = 0.01, dilation = 1,
groups = 1,
...) {
args <- list(
out_size = out_size,
n_channels = as.integer(n_channels),
in_sz = as.integer(in_sz),
n_features = as.integer(n_features),
n_extra_layers = as.integer(n_extra_layers),
bias = bias,
ndim = as.integer(ndim),
norm_type = as.integer(norm_type),
bn_1st = bn_1st,
act_cls = act_cls,
init = init,
xtra = xtra,
bias_std = bias_std,
dilation = as.integer(dilation),
groups = as.integer(groups),
...
)
do.call(vision$gan$basic_generator, args)
}
#' @title Basic_critic
#'
#' @description A basic critic for images `n_channels` x `in_size` x `in_size`.
#'
#'
#' @param in_size in_size
#' @param n_channels The number of channels
#' @param n_features The number of features
#' @param n_extra_layers The number of extra layers
#' @param norm_type norm_type
#' @param bias bias
#' @param ndim ndim
#' @param bn_1st bn_1st
#' @param act_cls act_cls
#' @param transpose transpose
#' @param xtra xtra
#' @param bias_std bias_std
#' @param dilation dilation
#' @param groups groups
#' @param padding_mode Mode of padding
#' @param ... additional parameters to pass
#'
#' @export
basic_critic <- function(in_size, n_channels, n_features = 64,
n_extra_layers = 0, norm_type = 1,
bias = NULL,
ndim = 2, bn_1st = TRUE, act_cls = nn$ReLU,
transpose = FALSE,
xtra = NULL, bias_std = 0.01, dilation = 1,
groups = 1, padding_mode = "zeros",
...) {
args <- list(
in_size = in_size,
n_channels = as.integer(n_channels),
n_features = as.integer(n_features),
n_extra_layers = as.integer(n_extra_layers),
norm_type = as.integer(norm_type),
bias = bias,
ndim = as.integer(ndim),
bn_1st = bn_1st,
act_cls = act_cls,
transpose = transpose,
xtra = xtra,
bias_std = bias_std,
dilation = as.integer(dilation),
groups = as.integer(groups),
padding_mode = padding_mode,
...
)
do.call(vision$gan$basic_critic, args)
}
#' @title Wgan
#'
#' @description Create a WGAN from `data`, `generator` and `critic`.
#'
#' @param dls dls
#' @param generator generator
#' @param critic critic
#' @param switcher switcher
#' @param clip clip
#' @param switch_eval switch_eval
#' @param gen_first gen_first
#' @param show_img show_img
#' @param cbs cbs
#' @param metrics metrics
#' @param opt_func opt_func
#' @param lr lr
#' @param splitter splitter
#' @param path path
#' @param model_dir model_dir
#' @param wd wd
#' @param wd_bn_bias wd_bn_bias
#' @param train_bn train_bn
#' @param moms moms
#'
#' @export
GANLearner_wgan <- function(dls, generator, critic, switcher = NULL, clip = 0.01,
switch_eval = FALSE, gen_first = FALSE, show_img = TRUE,
cbs = NULL, metrics = NULL, opt_func = Adam(),
lr = 0.001, splitter = trainable_params, path = NULL,
model_dir = "models", wd = NULL, wd_bn_bias = FALSE,
train_bn = TRUE, moms = list(0.95, 0.85, 0.95)) {
args <- list(
dls = dls,
generator = generator,
critic = critic,
switcher = switcher,
clip = clip,
switch_eval = switch_eval,
gen_first = gen_first,
show_img = show_img,
cbs = cbs,
metrics = metrics,
opt_func = opt_func,
lr = lr,
splitter = splitter,
path = path,
model_dir = model_dir,
wd = wd,
wd_bn_bias = wd_bn_bias,
train_bn = train_bn,
moms = moms
)
do.call(vision$gan$GANLearner$wgan, args)
}
#' @title Fit
#' @description Fit the model on this learner with `lr` learning rate, `wd` weight decay for `epochs` with `callbacks`.
#'
#' @param epochs epochs
#' @param lr lr
#' @param wd wd
#' @param callbacks callbacks
#'
#' @export
fit.fastai.vision.gan.GANLearner <- function(object, ...) {
args <- list(
...
)
if(!is.null(args[[1]]) & is.null(names(args[[1]]))) {
args[[1]] = as.integer(args[[1]])
}
find_epoch = which(names(args)=='n_epoch')
if(length(find_epoch)>0) {
args[[find_epoch]] = as.integer(args[[find_epoch]])
}
# fit the model
do.call(object$fit, args)
if (length(length(object$recorder$values))==1) {
history = data.frame(values = do.call(rbind,lapply(1:length(object$recorder$values),
function(x) object$recorder$values[[x]]$items))
)
} else {
history = data.frame(values = t(do.call(rbind,lapply(1:length(object$recorder$values),
function(x) object$recorder$values[[x]]$items)))
)
}
nm = object$recorder$metric_names$items
colnames(history) = nm[!nm %in% c('epoch','time')]
if(nrow(history)==1) {
history['epoch'] = 0
} else {
history['epoch'] = 0:(nrow(history)-1)
}
history = history[,c(which(colnames(history)=="epoch"),which(colnames(history)!="epoch"))]
invisible(history)
}
#' @title GANModule
#'
#' @description Wrapper around a `generator` and a `critic` to create a GAN.
#'
#'
#' @param generator generator
#' @param critic critic
#' @param gen_mode gen_mode
#'
#' @export
GANModule <- function(generator = NULL, critic = NULL, gen_mode = FALSE) {
args <- list(
generator = generator,
critic = critic,
gen_mode = gen_mode
)
do.call(vision$gan$GANModule, args)
}
#' @title GANDiscriminativeLR
#'
#' @description `Callback` that handles multiplying the learning rate by `mult_lr` for the critic.
#'
#'
#' @param mult_lr mult_lr
#'
#' @export
GANDiscriminativeLR <- function(mult_lr = 5.0) {
vision$gan$GANDiscriminativeLR(
mult_lr = mult_lr
)
}
#' @title MaskBlock
#'
#' @description A `TransformBlock` for segmentation masks, potentially with `codes`
#'
#'
#' @param codes codes
#'
#' @export
MaskBlock <- function(codes = NULL) {
if(is.null(codes)) {
vision$all$MaskBlock
} else {
vision$all$MaskBlock(
codes = codes
)
}
}
#' @title AddChannels
#'
#' @description Add `n_dim` channels at the end of the input.
#'
#'
#' @param n_dim n_dim
#'
#' @export
AddChannels <- function(n_dim) {
vision$gan$AddChannels(
n_dim = as.integer(n_dim)
)
}
#' @title DenseResBlock
#'
#' @description Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`.
#'
#' @details
#'
#' @param nf nf
#' @param norm_type norm_type
#' @param ks ks
#' @param stride stride
#' @param padding padding
#' @param bias bias
#' @param ndim ndim
#' @param bn_1st bn_1st
#' @param act_cls act_cls
#' @param transpose transpose
#' @param init init
#' @param xtra xtra
#' @param bias_std bias_std
#' @param dilation dilation
#' @param groups groups
#' @param padding_mode padding_mode
#'
#' @export
DenseResBlock <- function(nf, norm_type = 1,
ks = 3, stride = 1, padding = NULL,
bias = NULL, ndim = 2, bn_1st = TRUE,
act_cls = nn$ReLU, transpose = FALSE, init = "auto", xtra = NULL,
bias_std = 0.01, dilation = 1, groups = 1,
padding_mode = "zeros") {
args <- list(
nf = nf,
norm_type = as.integer(norm_type),
ks = as.integer(ks),
stride = as.integer(stride),
padding = padding,
bias = bias,
ndim = as.integer(ndim),
bn_1st = bn_1st,
act_cls = act_cls,
transpose = transpose,
init = init,
xtra = xtra,
bias_std = bias_std,
dilation = as.integer(dilation),
groups = as.integer(groups),
padding_mode = padding_mode
)
do.call(vision$gan$DenseResBlock, args)
}
#' @title gan_critic
#'
#' @description Critic to train a `GAN`.
#'
#'
#' @param n_channels n_channels
#' @param nf nf
#' @param n_blocks n_blocks
#' @param p p
#'
#' @export
gan_critic <- function(n_channels = 3, nf = 128, n_blocks = 3, p = 0.15) {
vision$gan$gan_critic(
n_channels = as.integer(n_channels),
nf = as.integer(nf),
n_blocks = as.integer(n_blocks),
p = p
)
}
#' @title GANLoss
#'
#' @description Wrapper around `crit_loss_func` and `gen_loss_func`
#'
#'
#' @param gen_loss_func gen_loss_func
#' @param crit_loss_func crit_loss_func
#' @param gan_model gan_model
#'
#' @export
GANLoss <- function(gen_loss_func, crit_loss_func, gan_model) {
vision$gan$GANLoss(
gen_loss_func = gen_loss_func,
crit_loss_func = crit_loss_func,
gan_model = gan_model
)
}
#' @title AdaptiveLoss
#'
#' @description Expand the `target` to match the `output` size before applying `crit`.
#'
#'
#' @param crit crit
#'
#' @export
AdaptiveLoss <- function(crit) {
vision$gan$AdaptiveLoss(
crit = crit
)
}
#' @title accuracy_thresh_expand
#'
#' @description Compute accuracy after expanding `y_true` to the size of `y_pred`.
#'
#'
#' @param y_pred y_pred
#' @param y_true y_true
#' @param thresh thresh
#' @param sigmoid sigmoid
#'
#' @export
accuracy_thresh_expand <- function(y_pred, y_true, thresh = 0.5, sigmoid = TRUE) {
vision$gan$accuracy_thresh_expand(
y_pred = y_pred,
y_true = y_true,
thresh = thresh,
sigmoid = sigmoid
)
}
#' @title set_freeze_model
#'
#'
#' @param m m
#' @param rg rg
#'
#' @export
set_freeze_model <- function(m, rg) {
vision$gan$set_freeze_model(
m = m,
rg = rg
)
}
#' @title GANTrainer
#'
#' @description Handles GAN Training.
#'
#'
#' @param switch_eval switch_eval
#' @param clip clip
#' @param beta beta
#' @param gen_first gen_first
#' @param show_img show_img
#'
#' @export
GANTrainer <- function(switch_eval = FALSE, clip = NULL, beta = 0.98,
gen_first = FALSE, show_img = TRUE) {
vision$gan$GANTrainer(
switch_eval = switch_eval,
clip = clip,
beta = beta,
gen_first = gen_first,
show_img = show_img
)
}
#' @title FixedGANSwitcher
#'
#' @description Switcher to do `n_crit` iterations of the critic then `n_gen` iterations of the generator.
#'
#' @details
#'
#' @param n_crit n_crit
#' @param n_gen n_gen
#'
#' @export
FixedGANSwitcher <- function(n_crit = 1, n_gen = 1) {
vision$gan$FixedGANSwitcher(
n_crit = as.integer(n_crit),
n_gen = as.integer(n_gen)
)
}
#' @title AdaptiveGANSwitcher
#'
#' @description Switcher that goes back to generator/critic when the loss goes below `gen_thresh`/`crit_thresh`.
#'
#'
#' @param gen_thresh gen_thresh
#' @param critic_thresh critic_thresh
#'
#' @export
AdaptiveGANSwitcher <- function(gen_thresh = NULL, critic_thresh = NULL) {
vision$gan$AdaptiveGANSwitcher(
gen_thresh = gen_thresh,
critic_thresh = critic_thresh
)
}
#' @title GANDiscriminativeLR
#'
#' @description `Callback` that handles multiplying the learning rate by `mult_lr` for the critic.
#'
#'
#' @param mult_lr mult_lr
#'
#' @export
GANDiscriminativeLR <- function(mult_lr = 5.0) {
vision$gan$GANDiscriminativeLR(
mult_lr = mult_lr
)
}
#' @title InvisibleTensor
#'
#' @param x x
#'
#' @export
InvisibleTensor <- function(x) {
vision$gan$InvisibleTensor(
x = x
)
}
#' @title gan_loss_from_func
#'
#' @description Define loss functions for a GAN from `loss_gen` and `loss_crit`.
#'
#'
#' @param loss_gen loss_gen
#' @param loss_crit loss_crit
#' @param weights_gen weights_gen
#'
#' @export
gan_loss_from_func <- function(loss_gen, loss_crit, weights_gen = NULL) {
vision$gan$gan_loss_from_func(
loss_gen = loss_gen,
loss_crit = loss_crit,
weights_gen = weights_gen
)
}
| /R/GAN.R | permissive | ysnghr/fastai | R | false | false | 16,451 | r | #' @title DataBlock
#'
#' @description Generic container to quickly build `Datasets` and `DataLoaders`
#'
#'
#' @param blocks blocks
#' @param dl_type dl_type
#' @param getters getters
#' @param n_inp n_inp is the number of elements in the tuples that should be considered part of the input and will default to 1 if tfms consists of one set of transforms
#' @param item_tfms One or several transforms applied to the items before batching them
#' @param batch_tfms One or several transforms applied to the batches once they are formed
#'
#' @export
DataBlock <- function(blocks = NULL, dl_type = NULL, getters = NULL,
n_inp = NULL, item_tfms = NULL, batch_tfms = NULL,
...) {
args <- list(
blocks = blocks,
dl_type = dl_type,
getters = getters,
n_inp = n_inp,
item_tfms = item_tfms,
batch_tfms = batch_tfms,
...
)
if(!is.null(args$batch_tfms)) {
args$batch_tfms <- unlist(args$batch_tfms)
}
do.call(vision$gan$DataBlock, args)
}
#' @title TransformBlock
#'
#' @description A basic wrapper that links defaults transforms for the data block API
#'
#'
#' @param type_tfms type_tfms
#' @param item_tfms item_tfms
#' @param batch_tfms one or several transforms applied to the batches once they are formed
#' @param dl_type dl_type
#' @param dls_kwargs dls_kwargs
#'
#' @export
TransformBlock <- function(type_tfms = NULL, item_tfms = NULL,
batch_tfms = NULL, dl_type = NULL,
dls_kwargs = NULL) {
if(missing(type_tfms) & missing(item_tfms) & missing(batch_tfms) & missing(dl_type) & missing(dls_kwargs)) {
invisible(vision$gan$TransformBlock)
} else {
args <- list(
type_tfms = type_tfms,
item_tfms = item_tfms,
batch_tfms = batch_tfms,
dl_type = dl_type,
dls_kwargs = dls_kwargs
)
do.call(vision$gan$TransformBlock, args)
}
}
#' @title ImageBlock
#'
#' @description A `TransformBlock` for images of `cls`
#'
#'
#' @export
ImageBlock <- function() {
invisible(vision$gan$ImageBlock)
}
#' @title Generate_noise
#'
#'
#' @param fn fn
#' @param size size
#'
#' @export
generate_noise <- function(fn, size = 100) {
if(missing(fn)) {
invisible(vision$gan$generate_noise)
} else {
args <- list(
fn = fn,
size = as.integer(size)
)
do.call(vision$gan$generate_noise,args)
}
}
#' @title IndexSplitter
#'
#' @description Split `items` so that `val_idx` are in the validation set and the others in the training set
#'
#'
#' @param valid_idx The indices to use for the validation set (defaults to a random split otherwise)
#'
#' @export
IndexSplitter <- function(valid_idx) {
if(missing(valid_idx)) {
invisible(vision$gan$IndexSplitter)
} else {
args <- list(
valid_idx = valid_idx
)
do.call(vision$gan$IndexSplitter,args)
}
}
#' @title FileSplitter
#'
#' @description Split `items` by providing file `fname` (contains names of valid items separated by newline).
#'
#'
#' @param fname fname
#'
#' @export
FileSplitter <- function(fname) {
if(missing(fname)) {
vision$gan$FileSplitter
} else {
vision$gan$FileSplitter(
fname = fname
)
}
}
#' @title dataloaders
#'
#' @description Create a `DataLoaders` object from `source`
#'
#'
#' @param source source
#' @param ... additional parameters to pass
#'
#' @export
dataloaders <- function(object, ...) {
my_list <- list(
source = source,
...
)
for (i in 1:length(my_list)) {
if(names(my_list)[[i]]=='bs') {
my_list[['bs']] = as.integer(my_list[['bs']])
} else if (names(my_list)[[i]]=='batch_size') {
my_list[['batch_size']] = as.integer(my_list[['batch_size']])
} else if (names(my_list)[[i]]=='seq_len') {
my_list[['seq_len']] = as.integer(my_list[['seq_len']])
}
}
do.call(object$dataloaders,my_list)
}
#' @title Basic_generator
#'
#' @description A basic generator from `in_sz` to images `n_channels` x `out_size` x `out_size`.
#'
#'
#' @param out_size out_size
#' @param n_channels n_channels
#' @param in_sz in_sz
#' @param n_features The number of features
#' @param n_extra_layers The number of extra layers
#' @param ... additional params to pass
#' @param bias bias
#' @param ndim ndim
#' @param norm_type norm_type
#' @param bn_1st bn_1st
#' @param act_cls act_cls
#' @param transpose transpose
#' @param init init
#' @param xtra xtra
#' @param bias_std bias_std
#' @param dilation dilation
#' @param groups groups
#'
#' @export
basic_generator <- function(out_size, n_channels, in_sz = 100,
n_features = 64, n_extra_layers = 0,
bias = NULL, ndim = 2,
norm_type = 1, bn_1st = TRUE,
act_cls = nn$ReLU, init = "auto",
xtra = NULL, bias_std = 0.01, dilation = 1,
groups = 1,
...) {
args <- list(
out_size = out_size,
n_channels = as.integer(n_channels),
in_sz = as.integer(in_sz),
n_features = as.integer(n_features),
n_extra_layers = as.integer(n_extra_layers),
bias = bias,
ndim = as.integer(ndim),
norm_type = as.integer(norm_type),
bn_1st = bn_1st,
act_cls = act_cls,
init = init,
xtra = xtra,
bias_std = bias_std,
dilation = as.integer(dilation),
groups = as.integer(groups),
...
)
do.call(vision$gan$basic_generator, args)
}
#' @title Basic_critic
#'
#' @description A basic critic for images `n_channels` x `in_size` x `in_size`.
#'
#'
#' @param in_size in_size
#' @param n_channels The number of channels
#' @param n_features The number of features
#' @param n_extra_layers The number of extra layers
#' @param norm_type norm_type
#' @param bias bias
#' @param ndim ndim
#' @param bn_1st bn_1st
#' @param act_cls act_cls
#' @param transpose transpose
#' @param xtra xtra
#' @param bias_std bias_std
#' @param dilation dilation
#' @param groups groups
#' @param padding_mode Mode of padding
#' @param ... additional parameters to pass
#'
#' @export
basic_critic <- function(in_size, n_channels, n_features = 64,
n_extra_layers = 0, norm_type = 1,
bias = NULL,
ndim = 2, bn_1st = TRUE, act_cls = nn$ReLU,
transpose = FALSE,
xtra = NULL, bias_std = 0.01, dilation = 1,
groups = 1, padding_mode = "zeros",
...) {
args <- list(
in_size = in_size,
n_channels = as.integer(n_channels),
n_features = as.integer(n_features),
n_extra_layers = as.integer(n_extra_layers),
norm_type = as.integer(norm_type),
bias = bias,
ndim = as.integer(ndim),
bn_1st = bn_1st,
act_cls = act_cls,
transpose = transpose,
xtra = xtra,
bias_std = bias_std,
dilation = as.integer(dilation),
groups = as.integer(groups),
padding_mode = padding_mode,
...
)
do.call(vision$gan$basic_critic, args)
}
#' @title Wgan
#'
#' @description Create a WGAN from `data`, `generator` and `critic`.
#'
#' @param dls dls
#' @param generator generator
#' @param critic critic
#' @param switcher switcher
#' @param clip clip
#' @param switch_eval switch_eval
#' @param gen_first gen_first
#' @param show_img show_img
#' @param cbs cbs
#' @param metrics metrics
#' @param opt_func opt_func
#' @param lr lr
#' @param splitter splitter
#' @param path path
#' @param model_dir model_dir
#' @param wd wd
#' @param wd_bn_bias wd_bn_bias
#' @param train_bn train_bn
#' @param moms moms
#'
#' @export
GANLearner_wgan <- function(dls, generator, critic, switcher = NULL, clip = 0.01,
switch_eval = FALSE, gen_first = FALSE, show_img = TRUE,
cbs = NULL, metrics = NULL, opt_func = Adam(),
lr = 0.001, splitter = trainable_params, path = NULL,
model_dir = "models", wd = NULL, wd_bn_bias = FALSE,
train_bn = TRUE, moms = list(0.95, 0.85, 0.95)) {
args <- list(
dls = dls,
generator = generator,
critic = critic,
switcher = switcher,
clip = clip,
switch_eval = switch_eval,
gen_first = gen_first,
show_img = show_img,
cbs = cbs,
metrics = metrics,
opt_func = opt_func,
lr = lr,
splitter = splitter,
path = path,
model_dir = model_dir,
wd = wd,
wd_bn_bias = wd_bn_bias,
train_bn = train_bn,
moms = moms
)
do.call(vision$gan$GANLearner$wgan, args)
}
#' @title Fit
#' @description Fit the model on this learner with `lr` learning rate, `wd` weight decay for `epochs` with `callbacks`.
#'
#' @param epochs epochs
#' @param lr lr
#' @param wd wd
#' @param callbacks callbacks
#'
#' @export
fit.fastai.vision.gan.GANLearner <- function(object, ...) {
args <- list(
...
)
if(!is.null(args[[1]]) & is.null(names(args[[1]]))) {
args[[1]] = as.integer(args[[1]])
}
find_epoch = which(names(args)=='n_epoch')
if(length(find_epoch)>0) {
args[[find_epoch]] = as.integer(args[[find_epoch]])
}
# fit the model
do.call(object$fit, args)
if (length(length(object$recorder$values))==1) {
history = data.frame(values = do.call(rbind,lapply(1:length(object$recorder$values),
function(x) object$recorder$values[[x]]$items))
)
} else {
history = data.frame(values = t(do.call(rbind,lapply(1:length(object$recorder$values),
function(x) object$recorder$values[[x]]$items)))
)
}
nm = object$recorder$metric_names$items
colnames(history) = nm[!nm %in% c('epoch','time')]
if(nrow(history)==1) {
history['epoch'] = 0
} else {
history['epoch'] = 0:(nrow(history)-1)
}
history = history[,c(which(colnames(history)=="epoch"),which(colnames(history)!="epoch"))]
invisible(history)
}
#' @title GANModule
#'
#' @description Wrapper around a `generator` and a `critic` to create a GAN.
#'
#'
#' @param generator generator
#' @param critic critic
#' @param gen_mode gen_mode
#'
#' @export
GANModule <- function(generator = NULL, critic = NULL, gen_mode = FALSE) {
args <- list(
generator = generator,
critic = critic,
gen_mode = gen_mode
)
do.call(vision$gan$GANModule, args)
}
#' @title GANDiscriminativeLR
#'
#' @description `Callback` that handles multiplying the learning rate by `mult_lr` for the critic.
#'
#'
#' @param mult_lr mult_lr
#'
#' @export
GANDiscriminativeLR <- function(mult_lr = 5.0) {
vision$gan$GANDiscriminativeLR(
mult_lr = mult_lr
)
}
#' @title MaskBlock
#'
#' @description A `TransformBlock` for segmentation masks, potentially with `codes`
#'
#'
#' @param codes codes
#'
#' @export
MaskBlock <- function(codes = NULL) {
if(is.null(codes)) {
vision$all$MaskBlock
} else {
vision$all$MaskBlock(
codes = codes
)
}
}
#' @title AddChannels
#'
#' @description Add `n_dim` channels at the end of the input.
#'
#'
#' @param n_dim n_dim
#'
#' @export
AddChannels <- function(n_dim) {
vision$gan$AddChannels(
n_dim = as.integer(n_dim)
)
}
#' @title DenseResBlock
#'
#' @description Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`.
#'
#' @details
#'
#' @param nf nf
#' @param norm_type norm_type
#' @param ks ks
#' @param stride stride
#' @param padding padding
#' @param bias bias
#' @param ndim ndim
#' @param bn_1st bn_1st
#' @param act_cls act_cls
#' @param transpose transpose
#' @param init init
#' @param xtra xtra
#' @param bias_std bias_std
#' @param dilation dilation
#' @param groups groups
#' @param padding_mode padding_mode
#'
#' @export
DenseResBlock <- function(nf, norm_type = 1,
ks = 3, stride = 1, padding = NULL,
bias = NULL, ndim = 2, bn_1st = TRUE,
act_cls = nn$ReLU, transpose = FALSE, init = "auto", xtra = NULL,
bias_std = 0.01, dilation = 1, groups = 1,
padding_mode = "zeros") {
args <- list(
nf = nf,
norm_type = as.integer(norm_type),
ks = as.integer(ks),
stride = as.integer(stride),
padding = padding,
bias = bias,
ndim = as.integer(ndim),
bn_1st = bn_1st,
act_cls = act_cls,
transpose = transpose,
init = init,
xtra = xtra,
bias_std = bias_std,
dilation = as.integer(dilation),
groups = as.integer(groups),
padding_mode = padding_mode
)
do.call(vision$gan$DenseResBlock, args)
}
#' @title gan_critic
#'
#' @description Critic to train a `GAN`.
#'
#'
#' @param n_channels n_channels
#' @param nf nf
#' @param n_blocks n_blocks
#' @param p p
#'
#' @export
gan_critic <- function(n_channels = 3, nf = 128, n_blocks = 3, p = 0.15) {
vision$gan$gan_critic(
n_channels = as.integer(n_channels),
nf = as.integer(nf),
n_blocks = as.integer(n_blocks),
p = p
)
}
#' @title GANLoss
#'
#' @description Wrapper around `crit_loss_func` and `gen_loss_func`
#'
#'
#' @param gen_loss_func gen_loss_func
#' @param crit_loss_func crit_loss_func
#' @param gan_model gan_model
#'
#' @export
GANLoss <- function(gen_loss_func, crit_loss_func, gan_model) {
vision$gan$GANLoss(
gen_loss_func = gen_loss_func,
crit_loss_func = crit_loss_func,
gan_model = gan_model
)
}
#' @title AdaptiveLoss
#'
#' @description Expand the `target` to match the `output` size before applying `crit`.
#'
#'
#' @param crit crit
#'
#' @export
AdaptiveLoss <- function(crit) {
vision$gan$AdaptiveLoss(
crit = crit
)
}
#' @title accuracy_thresh_expand
#'
#' @description Compute accuracy after expanding `y_true` to the size of `y_pred`.
#'
#'
#' @param y_pred y_pred
#' @param y_true y_true
#' @param thresh thresh
#' @param sigmoid sigmoid
#'
#' @export
accuracy_thresh_expand <- function(y_pred, y_true, thresh = 0.5, sigmoid = TRUE) {
vision$gan$accuracy_thresh_expand(
y_pred = y_pred,
y_true = y_true,
thresh = thresh,
sigmoid = sigmoid
)
}
#' @title set_freeze_model
#'
#'
#' @param m m
#' @param rg rg
#'
#' @export
set_freeze_model <- function(m, rg) {
vision$gan$set_freeze_model(
m = m,
rg = rg
)
}
#' @title GANTrainer
#'
#' @description Handles GAN Training.
#'
#'
#' @param switch_eval switch_eval
#' @param clip clip
#' @param beta beta
#' @param gen_first gen_first
#' @param show_img show_img
#'
#' @export
GANTrainer <- function(switch_eval = FALSE, clip = NULL, beta = 0.98,
gen_first = FALSE, show_img = TRUE) {
vision$gan$GANTrainer(
switch_eval = switch_eval,
clip = clip,
beta = beta,
gen_first = gen_first,
show_img = show_img
)
}
#' @title FixedGANSwitcher
#'
#' @description Switcher to do `n_crit` iterations of the critic then `n_gen` iterations of the generator.
#'
#' @details
#'
#' @param n_crit n_crit
#' @param n_gen n_gen
#'
#' @export
FixedGANSwitcher <- function(n_crit = 1, n_gen = 1) {
vision$gan$FixedGANSwitcher(
n_crit = as.integer(n_crit),
n_gen = as.integer(n_gen)
)
}
#' @title AdaptiveGANSwitcher
#'
#' @description Switcher that goes back to generator/critic when the loss goes below `gen_thresh`/`crit_thresh`.
#'
#'
#' @param gen_thresh gen_thresh
#' @param critic_thresh critic_thresh
#'
#' @export
AdaptiveGANSwitcher <- function(gen_thresh = NULL, critic_thresh = NULL) {
vision$gan$AdaptiveGANSwitcher(
gen_thresh = gen_thresh,
critic_thresh = critic_thresh
)
}
#' @title GANDiscriminativeLR
#'
#' @description `Callback` that handles multiplying the learning rate by `mult_lr` for the critic.
#'
#'
#' @param mult_lr mult_lr
#'
#' @export
GANDiscriminativeLR <- function(mult_lr = 5.0) {
vision$gan$GANDiscriminativeLR(
mult_lr = mult_lr
)
}
#' @title InvisibleTensor
#'
#' @param x x
#'
#' @export
InvisibleTensor <- function(x) {
vision$gan$InvisibleTensor(
x = x
)
}
#' @title gan_loss_from_func
#'
#' @description Define loss functions for a GAN from `loss_gen` and `loss_crit`.
#'
#'
#' @param loss_gen loss_gen
#' @param loss_crit loss_crit
#' @param weights_gen weights_gen
#'
#' @export
gan_loss_from_func <- function(loss_gen, loss_crit, weights_gen = NULL) {
vision$gan$gan_loss_from_func(
loss_gen = loss_gen,
loss_crit = loss_crit,
weights_gen = weights_gen
)
}
|
require(devEMF)
library(quantmod)
library(RHmm)
library(parallel)
#postscript('AAPL.eps')
getSymbols("AAPL", src = "google")
#getSymbols("AAPL")
chartSeries(AAPL, theme="white")
#trainset <- window(AAPL, start = as.Date("2000-01-01"), end = as.Date("2013-04-01"))
trainsetraw <- window(AAPL, start = as.Date("2000-01-01"), end = as.Date("2013-04-01"))
print(ncol(trainsetraw)-1)
print(trainsetraw[,1:ncol(trainsetraw)-1])
trainset <- na.omit(trainsetraw[,1:ncol(trainsetraw)-1])
print(trainset)
#AAPL_Subset <- window(AAPL, start = as.Date("2000-01-01"), end = as.Date("2013-04-01"))
#AAPL_Train <- cbind(AAPL_Subset$AAPL.Close - AAPL_Subset$AAPL.Open, AAPL_Subset$AAPL.Volume)
train <- cbind(trainset$AAPL.Close - trainset$AAPL.Open)
#print(train)
testset <- window(AAPL, start = as.Date("2013-04-02"), end = as.Date("2014-04-01"))
test <- cbind(testset$AAPL.Close - testset$AAPL.Open)
print(testset)
# Baum-Welch Algorithm to find the model for the given observations
#hm_model <- HMMFit(obs = AAPL_Train, nStates = 5)
hm_model <- HMMFit(obs = train, nStates = 5, nMixt = 4, dis = "MIXTURE")
print(hm_model)
# Viterbi Algorithm to find the most probable state sequence
VitPath <- viterbi (hm_model, train)
print(VitPath)
# scatter plot
postscript('AAPL.eps')
AAPL_Predict <- cbind(trainset$AAPL.Close, VitPath$states)
#AAPL_Predict <- cbind(AAPL_Subset$AAPL.Close, VitPath$states)
#print(AAPL_Subset[,4] - AAPL_Predict [,1])
# predict next stock value m = nMixt, n = nStates
#sum(a[last(v),] * .colSums((matrix(unlist(a), nrow=4,ncol=5)) * (matrix(unlist(a), nrow=4,ncol=5)), m=4,n=5))
# gaussian mixture HMM: nrow = nMixture, ncol = nStates
#print(hm_model$HMM$transMat[last(VitPath$states),])
#print(hm_model$HMM$distribution$mean[, seq(1, ncol(hm_model$HMM$distribution$mean), by = 2)])
#print(unlist(hm_model$HMM$distribution$mean))
#print(matrix(unlist(hm_model$HMM$distribution$proportion[1,])))
# add a new colum "Pred"
testset <- cbind(testset, Pred = 0)
#testset <- cbind(testset$AAPL.Close, Pred = 0)
#print(testset)
#chartSeries(testset, theme="white")
#chartSeries(test, theme="white")
# number of rows of test set data
rows = nrow(testset)
MAPEsum = 0
NRMSEsum = 0
#MAPEsum <- 0
# predict and update HMM to include the new actual value
#for (i in 1: 251) {
#for (i in 1: 3) {
for (i in 1: rows) {
#if (i == rows) break
if(i != 0) {
testrow <- testset[i, ]
#print(testrow)
todayopen <- testset$AAPL.Open[i, ]
actual <- testset$AAPL.Close[i, ]
#todayclose <- testset$AAPL.Close[i, ]
}
# predict the closing value of today
change <- sum(hm_model$HMM$transMat[last(VitPath$states),] * .colSums((matrix(unlist(hm_model$HMM$distribution$mean), nrow=4,ncol=5)) * (matrix(unlist(hm_model$HMM$distribution$proportion), nrow=4,ncol=5)), m=4,n=5))
#sum(hm_model$HMM$transMat[last(VitPath$states),] * .colSums((matrix(unlist(hm_model$HMM$distribution$mean[1,]), nrow=4,ncol=5)) * (matrix(unlist(hm_model$HMM$distribution$proportion[1,]), nrow=4,ncol=5)), m=4,n=5))
print(change)
pred <- todayopen + change
#testrow$Pred <- pred
#print(pred)
# update today's predicted value
testset[i, ]$Pred <- pred
print(testset[i, ])
# MAPE = sum(|pred - actual|/|actual|)*100/n
diff = (abs ((pred - actual)/ actual))[1,]$AAPL.Open
#print (diff)
#MAPEsum <- MAPEsum + diff$AAPL.Open
MAPEsum <- sum(MAPEsum, diff[1,1])
#MAPEsum = MAPEsum + abs((pred - actual)/todayclose)
#print(MAPEsum)
#MAPE <- MAPEsum*100/rows
#print(MAPE)
# NRMSE = sqrt(sum((pred - actual)^2) / n)
NRMSEsum <- sum(NRMSEsum, (pred - actual)^2)
# ROC
# [Optional] Returns: sell or buy
# if stock would increase sell, otherwise buy
# single HMM
#sum(hm_model$HMM$transMat[last(VitPath$states),] * .colSums((matrix(unlist(hm_model$HMM$distribution$mean), nrow=1,ncol=5)) * (matrix(unlist(hm_model$HMM$distribution$proportion), nrow=1,ncol=5)), m=1,n=5))
# update train data
train <- rbind (train, todayclose - todayopen)
# update HMM with the new data
# Baum-Welch Algorithm to find the model for the given observations
hm_model <- HMMFit(obs = train, nStates = 5, nMixt = 4, dis = "MIXTURE")
# Viterbi Algorithm to find the most probable state sequence
VitPath <- viterbi (hm_model, train)
}
cat("Rows = ", rows)
#print(rows)
MAPE <- MAPEsum*100/rows
cat("MAPE = ", MAPE)
#print(MAPE)
actuals <- testset$AAPL.Close
ymax = max (actuals)
ymin = min (actuals)
NRMSE <- sqrt(NRMSEsum)/(rows * (ymax - ymin))
cat("NRMSE = ", NRMSE)
#print(NRMSE)
# plot actual with predicted values added
# compare actual closing value and predicted closing value
#chartSeries(testset[2:rows, 4], theme='white', col = 'green', name = "AAPL", legend = "Actual",
chartSeries(testset[1:rows, 1], theme= chartTheme('white', up.col = 'blue'), name = "AAPL", legend = "Actual",
TA = "addTA(testset[1:rows, ncol(testset)], on = 1, col='red')") #
#chartSeries(testset[2:rows, 1], theme='white.mono', name = 'Actual', TA = "addTA(testset[2:rows, 7], on = 1, col='yellow', legend = \"Predicted\")") #
#chartSeries(testset[, 1], name = 'Actual', TA = "addTA(testset[, 7], on = 1, col='blue', legend = \"Predicted\")") #
#chartSeries(testset)
| /rhmm/AAPL.R | no_license | HarryXueTJU/stock | R | false | false | 5,147 | r | require(devEMF)
library(quantmod)
library(RHmm)
library(parallel)
#postscript('AAPL.eps')
getSymbols("AAPL", src = "google")
#getSymbols("AAPL")
chartSeries(AAPL, theme="white")
#trainset <- window(AAPL, start = as.Date("2000-01-01"), end = as.Date("2013-04-01"))
trainsetraw <- window(AAPL, start = as.Date("2000-01-01"), end = as.Date("2013-04-01"))
print(ncol(trainsetraw)-1)
print(trainsetraw[,1:ncol(trainsetraw)-1])
trainset <- na.omit(trainsetraw[,1:ncol(trainsetraw)-1])
print(trainset)
#AAPL_Subset <- window(AAPL, start = as.Date("2000-01-01"), end = as.Date("2013-04-01"))
#AAPL_Train <- cbind(AAPL_Subset$AAPL.Close - AAPL_Subset$AAPL.Open, AAPL_Subset$AAPL.Volume)
train <- cbind(trainset$AAPL.Close - trainset$AAPL.Open)
#print(train)
testset <- window(AAPL, start = as.Date("2013-04-02"), end = as.Date("2014-04-01"))
test <- cbind(testset$AAPL.Close - testset$AAPL.Open)
print(testset)
# Baum-Welch Algorithm to find the model for the given observations
#hm_model <- HMMFit(obs = AAPL_Train, nStates = 5)
hm_model <- HMMFit(obs = train, nStates = 5, nMixt = 4, dis = "MIXTURE")
print(hm_model)
# Viterbi Algorithm to find the most probable state sequence
VitPath <- viterbi (hm_model, train)
print(VitPath)
# scatter plot
postscript('AAPL.eps')
AAPL_Predict <- cbind(trainset$AAPL.Close, VitPath$states)
#AAPL_Predict <- cbind(AAPL_Subset$AAPL.Close, VitPath$states)
#print(AAPL_Subset[,4] - AAPL_Predict [,1])
# predict next stock value m = nMixt, n = nStates
#sum(a[last(v),] * .colSums((matrix(unlist(a), nrow=4,ncol=5)) * (matrix(unlist(a), nrow=4,ncol=5)), m=4,n=5))
# gaussian mixture HMM: nrow = nMixture, ncol = nStates
#print(hm_model$HMM$transMat[last(VitPath$states),])
#print(hm_model$HMM$distribution$mean[, seq(1, ncol(hm_model$HMM$distribution$mean), by = 2)])
#print(unlist(hm_model$HMM$distribution$mean))
#print(matrix(unlist(hm_model$HMM$distribution$proportion[1,])))
# add a new colum "Pred"
testset <- cbind(testset, Pred = 0)
#testset <- cbind(testset$AAPL.Close, Pred = 0)
#print(testset)
#chartSeries(testset, theme="white")
#chartSeries(test, theme="white")
# number of rows of test set data
rows = nrow(testset)
MAPEsum = 0
NRMSEsum = 0
#MAPEsum <- 0
# predict and update HMM to include the new actual value
#for (i in 1: 251) {
#for (i in 1: 3) {
for (i in 1: rows) {
#if (i == rows) break
if(i != 0) {
testrow <- testset[i, ]
#print(testrow)
todayopen <- testset$AAPL.Open[i, ]
actual <- testset$AAPL.Close[i, ]
#todayclose <- testset$AAPL.Close[i, ]
}
# predict the closing value of today
change <- sum(hm_model$HMM$transMat[last(VitPath$states),] * .colSums((matrix(unlist(hm_model$HMM$distribution$mean), nrow=4,ncol=5)) * (matrix(unlist(hm_model$HMM$distribution$proportion), nrow=4,ncol=5)), m=4,n=5))
#sum(hm_model$HMM$transMat[last(VitPath$states),] * .colSums((matrix(unlist(hm_model$HMM$distribution$mean[1,]), nrow=4,ncol=5)) * (matrix(unlist(hm_model$HMM$distribution$proportion[1,]), nrow=4,ncol=5)), m=4,n=5))
print(change)
pred <- todayopen + change
#testrow$Pred <- pred
#print(pred)
# update today's predicted value
testset[i, ]$Pred <- pred
print(testset[i, ])
# MAPE = sum(|pred - actual|/|actual|)*100/n
diff = (abs ((pred - actual)/ actual))[1,]$AAPL.Open
#print (diff)
#MAPEsum <- MAPEsum + diff$AAPL.Open
MAPEsum <- sum(MAPEsum, diff[1,1])
#MAPEsum = MAPEsum + abs((pred - actual)/todayclose)
#print(MAPEsum)
#MAPE <- MAPEsum*100/rows
#print(MAPE)
# NRMSE = sqrt(sum((pred - actual)^2) / n)
NRMSEsum <- sum(NRMSEsum, (pred - actual)^2)
# ROC
# [Optional] Returns: sell or buy
# if stock would increase sell, otherwise buy
# single HMM
#sum(hm_model$HMM$transMat[last(VitPath$states),] * .colSums((matrix(unlist(hm_model$HMM$distribution$mean), nrow=1,ncol=5)) * (matrix(unlist(hm_model$HMM$distribution$proportion), nrow=1,ncol=5)), m=1,n=5))
# update train data
train <- rbind (train, todayclose - todayopen)
# update HMM with the new data
# Baum-Welch Algorithm to find the model for the given observations
hm_model <- HMMFit(obs = train, nStates = 5, nMixt = 4, dis = "MIXTURE")
# Viterbi Algorithm to find the most probable state sequence
VitPath <- viterbi (hm_model, train)
}
cat("Rows = ", rows)
#print(rows)
MAPE <- MAPEsum*100/rows
cat("MAPE = ", MAPE)
#print(MAPE)
actuals <- testset$AAPL.Close
ymax = max (actuals)
ymin = min (actuals)
NRMSE <- sqrt(NRMSEsum)/(rows * (ymax - ymin))
cat("NRMSE = ", NRMSE)
#print(NRMSE)
# plot actual with predicted values added
# compare actual closing value and predicted closing value
#chartSeries(testset[2:rows, 4], theme='white', col = 'green', name = "AAPL", legend = "Actual",
chartSeries(testset[1:rows, 1], theme= chartTheme('white', up.col = 'blue'), name = "AAPL", legend = "Actual",
TA = "addTA(testset[1:rows, ncol(testset)], on = 1, col='red')") #
#chartSeries(testset[2:rows, 1], theme='white.mono', name = 'Actual', TA = "addTA(testset[2:rows, 7], on = 1, col='yellow', legend = \"Predicted\")") #
#chartSeries(testset[, 1], name = 'Actual', TA = "addTA(testset[, 7], on = 1, col='blue', legend = \"Predicted\")") #
#chartSeries(testset)
|
\name{readSnpMatrix}
\alias{readSnpMatrix}
\title{Read in the SNP read count matrix file}
\description{
Reads a snp read count matrix generated by the snp-pileup code
included and prepares the read counts data frame needed for
\code{preProcSample}
}
\usage{readSnpMatrix(filename, skip=0L, err.thresh=Inf, del.thresh=Inf,
perl.pileup=FALSE, MandUnormal=FALSE)}
\arguments{
\item{filename}{absolute or relative path of the data file.}
\item{skip}{number of lines to skip. Defaults is none.}
\item{err.thresh}{threshold level for reads with error at that
position. Loci where the count exceeds threshold will be discarded.}
\item{del.thresh}{threshold level for reads with deletions at that
position. Loci where the count exceeds threshold will be discarded.}
\item{perl.pileup}{logical indicating whether the data file was
created using the earlier perl version (package in Google-site).}
\item{MandUnormal}{indicator of whether the counts from unmatched
normal is also included in the counts file. Defaults is FALSE.}
}
\value{
A data frame consisting of 6 variables for each SNP (or pseudo-SNP).
\item{Chrom}{chromosome that SNP is on}
\item{Pos}{genomic position. This value depends on the genome build.}
\item{NOR.DP}{number of reads covering the snp in the normal sample.}
\item{NOR.RD}{number of reads with ref allele in the normal sample.}
\item{TUM.DP}{number of reads covering the snp in the tumor sample.}
\item{TUM.RD}{number of reads with ref allele in the tumor sample.}
\item{UMN.DP}{number of reads covering the snp in the unmatched
normal sample. This column is only present if MandUnormal is TRUE.}
}
\details{
The SNPs used for generating the data file are the set of polymorphic
loci with single nucleotide change. In order to cover regions that are
sparse in polymorphic loci a set of non-polymorphic loci (pseudo-SNPs)
are used.
For copy number analysis the DNA fragment is the independent unit of
analysis. This loci with overlapping paired end reads should not be
counted twice (older versions of samtools mpileup will do this).
This function is written for the counter written by Venkat Seshan (in
perl) and re-implemented in C++ by Alex Studer. The file format for
the c++ version is different from the perl version. Alternate counters
can be accommodated by writing a similar function.
This function expects the read counts to be in normal-tumor order. So
use snp-pileup with the bam files given in normal-tumor order.
For WGS data this function will be slow and memory intensive. As an
alternate you can use the function \code{readSnpMatrixDT} [written by
Dario Beraldi] which uses the data.table package available from the
\code{extRfns} directory. It can be accessed using
\code{source(system.file("extRfns", "readSnpMatrixDT.R", package="facets"))}
}
| /man/readSnpMatrix.Rd | no_license | 1512474508/facets2n | R | false | false | 2,896 | rd | \name{readSnpMatrix}
\alias{readSnpMatrix}
\title{Read in the SNP read count matrix file}
\description{
Reads a snp read count matrix generated by the snp-pileup code
included and prepares the read counts data frame needed for
\code{preProcSample}
}
\usage{readSnpMatrix(filename, skip=0L, err.thresh=Inf, del.thresh=Inf,
perl.pileup=FALSE, MandUnormal=FALSE)}
\arguments{
\item{filename}{absolute or relative path of the data file.}
\item{skip}{number of lines to skip. Defaults is none.}
\item{err.thresh}{threshold level for reads with error at that
position. Loci where the count exceeds threshold will be discarded.}
\item{del.thresh}{threshold level for reads with deletions at that
position. Loci where the count exceeds threshold will be discarded.}
\item{perl.pileup}{logical indicating whether the data file was
created using the earlier perl version (package in Google-site).}
\item{MandUnormal}{indicator of whether the counts from unmatched
normal is also included in the counts file. Defaults is FALSE.}
}
\value{
A data frame consisting of 6 variables for each SNP (or pseudo-SNP).
\item{Chrom}{chromosome that SNP is on}
\item{Pos}{genomic position. This value depends on the genome build.}
\item{NOR.DP}{number of reads covering the snp in the normal sample.}
\item{NOR.RD}{number of reads with ref allele in the normal sample.}
\item{TUM.DP}{number of reads covering the snp in the tumor sample.}
\item{TUM.RD}{number of reads with ref allele in the tumor sample.}
\item{UMN.DP}{number of reads covering the snp in the unmatched
normal sample. This column is only present if MandUnormal is TRUE.}
}
\details{
The SNPs used for generating the data file are the set of polymorphic
loci with single nucleotide change. In order to cover regions that are
sparse in polymorphic loci a set of non-polymorphic loci (pseudo-SNPs)
are used.
For copy number analysis the DNA fragment is the independent unit of
analysis. This loci with overlapping paired end reads should not be
counted twice (older versions of samtools mpileup will do this).
This function is written for the counter written by Venkat Seshan (in
perl) and re-implemented in C++ by Alex Studer. The file format for
the c++ version is different from the perl version. Alternate counters
can be accommodated by writing a similar function.
This function expects the read counts to be in normal-tumor order. So
use snp-pileup with the bam files given in normal-tumor order.
For WGS data this function will be slow and memory intensive. As an
alternate you can use the function \code{readSnpMatrixDT} [written by
Dario Beraldi] which uses the data.table package available from the
\code{extRfns} directory. It can be accessed using
\code{source(system.file("extRfns", "readSnpMatrixDT.R", package="facets"))}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/perm.significance.R
\name{perm.significance}
\alias{perm.significance}
\title{A Function for Computing a Vector of Pearson Correlation Coefficients}
\usage{
perm.significance(exp.mat, cn.mat, gene.annot, method = "pearson",
digits = 5, num.perms = 100, random.seed = NULL,
alternative = "greater")
}
\arguments{
\item{exp.mat}{A matrix of gene-level expression data (rows = genes, columns = samples). Missing values are not permitted.}
\item{cn.mat}{A matrix of gene-level DNA copy number data (rows = genes, columns = samples). Both genes and samples should
appear in the same order as exp.mat. Missing values are not permitted.}
\item{gene.annot}{A three-column matrix containing gene position information. Column 1 = chromosome number written in
the form 'chr1' (note that chrX and chrY should be written chr23 and chr24), Column 2 = position (in base pairs), Column 3 = cytoband.
Genes should appear in the same order as exp.mat and cn.mat.}
\item{method}{A character string (either "pearson" or "spearman") specifying the method used to calculate the correlation coefficient
(default = "pearson").}
\item{digits}{Used with signif() to specify the number of significant digits (default = 5).}
\item{num.perms}{Number of permutations used to assess significance (default = 1e2).}
\item{random.seed}{Random seed (default = NULL).}
\item{alternative}{A character string ("greater" or "less") that specifies the direction of the alternative hypothesis,
either rho > 0 or rho < 0 (default = "greater").}
}
\value{
Returns a five-column matrix. The first three columns are the same as gene.annot. The fourth column contains
gene-specific Pearson or Spearman correlation coefficients based on the entries in each row of exp.mat and cn.mat,
respectively (column name = "R"). The fifth column contains squared Pearson correlation coefficients (column name = "R^2").
The sixth column contains the permutation-based right-tailed p-value of the correlation coefficient (column name = "perm_pValue").
The seventh column contains Benjamini-Hochberg q-values corresponding to the p-values. Genes with constant gene expression
or DNA copy number are removed because they have zero variance.
}
\description{
This function computes Pearson correlation coefficients on a row-by-row basis for two numerical input matrices of the same size.
}
\examples{
exp.mat = tcga.exp.convert(exp.mat)
cn.mat = tcga.cn.convert(cn.mat)
prepped.data = data.prep(exp.mat, cn.mat, gene.annot, sample.annot, log.exp = FALSE)
perm.significance(prepped.data[["exp"]], prepped.data[["cn"]], prepped.data[["gene.annot"]])
}
| /man/perm.significance.Rd | no_license | cran/MVisAGe | R | false | true | 2,748 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/perm.significance.R
\name{perm.significance}
\alias{perm.significance}
\title{A Function for Computing a Vector of Pearson Correlation Coefficients}
\usage{
perm.significance(exp.mat, cn.mat, gene.annot, method = "pearson",
digits = 5, num.perms = 100, random.seed = NULL,
alternative = "greater")
}
\arguments{
\item{exp.mat}{A matrix of gene-level expression data (rows = genes, columns = samples). Missing values are not permitted.}
\item{cn.mat}{A matrix of gene-level DNA copy number data (rows = genes, columns = samples). Both genes and samples should
appear in the same order as exp.mat. Missing values are not permitted.}
\item{gene.annot}{A three-column matrix containing gene position information. Column 1 = chromosome number written in
the form 'chr1' (note that chrX and chrY should be written chr23 and chr24), Column 2 = position (in base pairs), Column 3 = cytoband.
Genes should appear in the same order as exp.mat and cn.mat.}
\item{method}{A character string (either "pearson" or "spearman") specifying the method used to calculate the correlation coefficient
(default = "pearson").}
\item{digits}{Used with signif() to specify the number of significant digits (default = 5).}
\item{num.perms}{Number of permutations used to assess significance (default = 1e2).}
\item{random.seed}{Random seed (default = NULL).}
\item{alternative}{A character string ("greater" or "less") that specifies the direction of the alternative hypothesis,
either rho > 0 or rho < 0 (default = "greater").}
}
\value{
Returns a five-column matrix. The first three columns are the same as gene.annot. The fourth column contains
gene-specific Pearson or Spearman correlation coefficients based on the entries in each row of exp.mat and cn.mat,
respectively (column name = "R"). The fifth column contains squared Pearson correlation coefficients (column name = "R^2").
The sixth column contains the permutation-based right-tailed p-value of the correlation coefficient (column name = "perm_pValue").
The seventh column contains Benjamini-Hochberg q-values corresponding to the p-values. Genes with constant gene expression
or DNA copy number are removed because they have zero variance.
}
\description{
This function computes Pearson correlation coefficients on a row-by-row basis for two numerical input matrices of the same size.
}
\examples{
exp.mat = tcga.exp.convert(exp.mat)
cn.mat = tcga.cn.convert(cn.mat)
prepped.data = data.prep(exp.mat, cn.mat, gene.annot, sample.annot, log.exp = FALSE)
perm.significance(prepped.data[["exp"]], prepped.data[["cn"]], prepped.data[["gene.annot"]])
}
|
### booster.R ###
##### Setup #####
source('R_Pipeline/initialize.R')
load_package('rutils', version = rutils.version)
load_package('rbig', version = rbig.version)
load_package('rfun', version = rfun.version)
load_package('rml', version = rml.version)
source('R_Pipeline/libraries/ext_rml.R')
################ Inputs ################
config_filename = 'b_config_01.yml'
args = commandArgs(trailingOnly = T)
if(!is.empty(args)){
config_filename = args[1]
}
################ Read & Validate config ################
yaml::read_yaml(mc$path_configs %>% paste('modules', 'booster', config_filename, sep = '/')) -> bc
# To be completed ... | /event_prediction_pipeline/modules/booster.R | no_license | genpack/tutorials | R | false | false | 638 | r | ### booster.R ###
##### Setup #####
source('R_Pipeline/initialize.R')
load_package('rutils', version = rutils.version)
load_package('rbig', version = rbig.version)
load_package('rfun', version = rfun.version)
load_package('rml', version = rml.version)
source('R_Pipeline/libraries/ext_rml.R')
################ Inputs ################
config_filename = 'b_config_01.yml'
args = commandArgs(trailingOnly = T)
if(!is.empty(args)){
config_filename = args[1]
}
################ Read & Validate config ################
yaml::read_yaml(mc$path_configs %>% paste('modules', 'booster', config_filename, sep = '/')) -> bc
# To be completed ... |
#
# Perform the parant roll selection optimization
#
print("Seleting Optimal Parent Rolls for each Possible Number of Parents")
# Test this with a specific grade and calipeer
#rawData <- filter(rawData, Grade == "SUS" & CalDW == "26-72-W")
# select all the unique parents
parent_types <- rawData %>% group_by(Grade, CalDW, Mill) %>%
summarize(Sizes = n_distinct(Width))
# create data frame to hold slitter limitation information
allNoSlitter <- data.frame("Grade"=c(0),"CalDW"=c(0),"Width"=c(0),
"Plant"=c(0))
# iterate through each plant with slitter limiation
# slitterLimitPlants defined in User Inputs.R
for (tplant in slitterLimitPlants){
# selects data from specified plant with slitter limitation
# select only Grade, CalDW, Width, Plant
noSlitter <- rawData %>% select (Grade, CalDW, Width, Plant)
# select data only from Plant that has slitter limitation
noSlitter <- noSlitter %>% filter (Plant == tplant)
# select only the distinct Grade, CalDW, Widths from that plant
noSlitter <- noSlitter %>% distinct(Grade, CalDW, Width, Plant)
# append to larger data frame
allNoSlitter <- rbind(allNoSlitter,noSlitter)
}
# remove first row of zeros
allNoSlitter <- allNoSlitter[-c(1),]
# create empty data frame to hold options for all grade, CalDW combinations
AllRollSelOptions <- data.frame(list())
parent_stats_all <- list()
# specify number of cores to use for parallel processing
#registerDoParallel(cores=3)
#print("Par Registered")
# Run optimization to get the cost of each possible number of rolls
# for each Grade/CalDW combination
print("Selecting Parent Roll Assignments")
ptype <- 2 # For testing
for (ptype in 1:nrow(parent_types)) {
# filter to find data for one parent
one_parent_grade <- parent_types$Grade[ptype] # Grade
one_parent_calDW <- parent_types$CalDW[ptype] # CalDW
one_parent_mill <- parent_types$Mill[ptype]
print(paste("Parent ", ptype, "/", nrow(parent_types), ", Grade = ",
one_parent_grade, ", CalDW = ",
one_parent_calDW, ", ", parent_types$Sizes[ptype],
" Sizes", sep = ""))
# Get the lead time for this grade/CalDW. Note we use the same logic
# in the simulation file.
cycle_dbr <- cycle_length_list$Mean.DBR[which(
cycle_length_list$Mill.Machine == one_parent_mill &
cycle_length_list$Grade == one_parent_grade &
cycle_length_list$Caliper == str_sub(one_parent_calDW, 1, 2))]
# If we didn't find the lead time, try without the machine number
# gsub("[0-9]", "", str) will remove numbers from a string
if (length(cycle_dbr) == 0 | is.null(cycle_dbr)) {
cycle_dbr <- cycle_length_list$Mean.DBR[which(
gsub("[0-9]", "", cycle_length_list$Mill.Machine) ==
gsub("[0-9]", "", one_parent_mill) &
cycle_length_list$Grade == one_parent_grade &
cycle_length_list$Caliper == str_sub(one_parent_calDW, 1, 2))]
}
# If we still didn't get a match, stop
if (length(cycle_dbr) == 0 | is.null(cycle_dbr)) {
stop("Lead Time not Found")
}
roll_lead_time <- cycle_dbr + order_proc_length + transportation_length
# Get the demand statistics out of the rd_stats_df and convert to the
# appropriate value over the lead time
op_lt_stats <- rd_stats_df %>%
filter(Grade == one_parent_grade, CalDW == one_parent_calDW) %>%
select(Grade, CalDW, Width, dmd_count = nz_dmd_count, dmd_sum,
dmd_mean, dmd_sd, dclass) %>%
mutate(sd_lt = dmd_sd * sqrt(roll_lead_time/dmd_lt_conv),
dmd_lt = dmd_mean * roll_lead_time/dmd_lt_conv,
dmd_review = dmd_mean * cycle_dbr/dmd_lt_conv)
# Add the stats back to the one_parent table
one_parent <- op_lt_stats %>%
select(Grade, CalDW, Width, dmd_count, dmd_sum, sd_lt, dmd_lt,
dmd_review, dclass) %>%
arrange(Grade, CalDW, Width) %>%
ungroup()
# Add the trim freight to be used in the trim cost calculation later
one_parent <-
left_join(one_parent, filter(trim_freight_plant, Mill == ifac),
c("Grade" = "Grade",
"CalDW" = "CalDW",
"Width" = "Width"))
# list of potential parent roll widths
rwidth <- as.numeric(one_parent$Width)
# list of products and rename some columns
pwidth <- one_parent %>% select(width = Width, dmd_count, dmd_sum, dmd_lt,
sd_lt, dmd_review, dclass, Trim.Frt.Cost)
pwidth$width <- as.numeric(pwidth$width)
# noSlitter subset - widths that cannot be split
slitter_limits <- allNoSlitter %>%
filter (Grade == one_parent_grade & CalDW == one_parent_calDW) %>%
select (Width)
# formatting
slitter_limits <- as.data.frame(slitter_limits)
# make into list
slitter_limits_list <- slitter_limits[,1]
# run parent roll selection
source(file.path(basepath, "R", "4a.Sub Parent Roll Optimization.R"))
# the output of this is the RollSelOptions dataframe which includes
# the trim cost and safety stock costs
#
# add roll selection options to list of all roll selection options
AllRollSelOptions <- rbind(AllRollSelOptions,
RollSelOptions)
# Append the parent_stats to the all table to be used in the simulation
parent_stats_all <- rbind(parent_stats_all, parent_stats)
}
# ungroup data frame and rearrange the columns to make it look nice
AllRollSelOptions <- AllRollSelOptions %>% ungroup() %>%
select(Grade, CalDW, Sol.Num.Parents, Sol.Gross.Tons, Sol.Trim.Tons,
Sol.Trim.Cost, Sol.Handling.Cost, Sol.SS.Tons, Sol.SS.Cost,
Sol.OTL.Tons, Sol.Exp.OH.Tons, Sol.Exp.OH.Inv.Cost,
Sol.Exp.OH.Storage.Cost, Sol.Total.Cost,
Parent.Width, Parent.dclass, Parent.Distrib, Parent.SS_Calc,
Parent.Nbr.Subs, Parent.DMD.Count,
Parent.DMD, Parent.SS.Tons, Parent.SS.DOH, Parent.Exp.OH.Tons,
Parent.Exp.OH.Inv.Cost,
Parent.OTL, Prod.Width, Prod.DMD.Tons, Prod.DMD.Count,
Prod.Gross.Tons, Prod.LT.Tons, Prod.dclass,
Prod.Trim.Fact, Prod.Trim.Width, Prod.Trim.Tons)
# select Grade, CalDW, # Parents, & Costs
numOptions <- AllRollSelOptions %>%
select(Grade, CalDW, Sol.Num.Parents, Sol.Trim.Cost,
Sol.Trim.Tons, Sol.Handling.Cost,
Sol.Exp.OH.Storage.Cost, Sol.Exp.OH.Inv.Cost,
Sol.Exp.OH.Tons,
Sol.SS.Cost, Sol.SS.Tons,
Sol.Total.Cost) %>% distinct()
# Determine the optimal grouping of parent rolls for all the
# possible combinations from min to max parent rolls. This will be based on
# minimum total cost: trim cost plus safety stock cost. The output
# goes into the tresults data frame
source(file.path(basepath, "R", "4b.Sub Parent Roll Grouping.R"))
# Now that we know the optimal groupings of parents, add this info
# back tothe AllRollSelOptions table
solutionRollDetails <-
left_join(AllRollSelOptions,
select(solresults, solutionGrade, solutionCalDW, parentNbrs,
solutionNbr, SolParentCount),
by = c("Grade" = "solutionGrade",
"CalDW" = "solutionCalDW",
"Sol.Num.Parents" = "parentNbrs"))
# Remove the options that are not part of an optimal solution
solutionRollDetails <- solutionRollDetails %>%
filter(!is.na(solutionNbr))
# solresults_sum comes from the Sub Parent Roll Grouping.R script
solresults_sum %>% ungroup() %>%
filter(Total.Cost == min(Total.Cost))
# Add the facility we are working on
solresults_sum <- solresults_sum %>%
mutate(Fac = ifac) %>%
select(Fac, everything())
min_sol <- solresults_sum %>% slice(which.min(Total.Cost)) %>%
select(NbrParents, Total.Cost)
solresults_sum$Min.Nbr.Parents <- min_sol$NbrParents
solresults_sum$Min.Total.Cost <- min_sol$Total.Cost
# Put the data in long format for plotting
solresults_sum_plot <- solresults_sum %>%
select(Fac, NbrParents, Total.Cost, Trim.Cost, Handling.Cost, Storage.Cost,
Inv.Carrying.Cost, Min.Nbr.Parents, Min.Total.Cost) %>%
gather(key = `Cost Component`, value = Cost,
Total.Cost:Inv.Carrying.Cost)
psol <- ggplot(solresults_sum_plot,
aes(x = NbrParents, color = `Cost Component`)) +
geom_line(aes(y = Cost), size = 1) +
scale_y_continuous(labels = unit_format(unit = "M", scale = 1e-6)) +
geom_text(aes(label = as.character(Min.Nbr.Parents),
x = Min.Nbr.Parents, y = Min.Total.Cost/2), color = "black") +
geom_segment(aes(x = Min.Nbr.Parents, xend = Min.Nbr.Parents,
y = 0, yend = Min.Total.Cost),
size = 0.4, color = "black") +
scale_color_discrete(breaks = c("Total.Cost", "Handling.Cost",
"Inv.Carrying.Cost",
"Storage.Cost", "Trim.Cost"))
rm(solresults_sum_plot)
ggplotly(psol)
# Plot the trim width by roll demand
min_sol_trim <- solutionRollDetails %>%
filter(SolParentCount == min_sol$NbrParents)
# Try dummy faceting
d1 <- min_sol_trim %>%
select(CalDW, Prod.Width, Prod.Trim.Width) %>%
mutate(y = Prod.Trim.Width, Prod.Roll = paste(CalDW, Prod.Width))
d1$panel <- "Trim Loss Width"
d2 <- min_sol_trim %>%
select(CalDW, Prod.Width, Prod.Trim.Width, y = Prod.Gross.Tons) %>%
mutate(Prod.Roll = paste(CalDW, Prod.Width))
d2$panel <- "Tons"
d <- bind_rows(d1, d2) %>%
arrange(desc(Prod.Trim.Width)) %>%
mutate(Prod.Roll = factor(Prod.Roll, unique(Prod.Roll)))
# use faceting - I think this looks the best
trimplot_all <- ggplot(data = d, aes(x = Prod.Roll, fill = CalDW)) +
geom_bar(stat = "identity", aes(y = y)) +
theme(axis.text.x=element_text(size = 3, angle = 90,hjust = 1,vjust = 0.5)) +
facet_grid(panel ~ ., scales = "free_y") +
scale_y_continuous(labels = comma) +
ggtitle(paste(ifac, "Trim Width by Roll"))
# Make sure we have trim over 2"
if (nrow(filter(d, Prod.Trim.Width >= 2)) > 0) {
trimplot_gt2 <- ggplot(data = filter(d, Prod.Trim.Width >= 2),
aes(x = Prod.Roll, fill = CalDW)) +
geom_bar(stat = "identity", aes(y = y)) +
theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5)) +
facet_grid(panel ~ ., scales = "free_y") +
scale_y_continuous(labels = comma) +
ggtitle(paste(ifac, "Demand Tons & Trim Width for Rolls > 2 inches"))
ggplotly(trimplot_all)
} else (trimplot_gt2 <- NULL)
# # Back to Back plot tests
# ggplot(data = d, aes(x = Prod.Roll, fill = CalDW)) +
# geom_bar(data = subset(d, panel == "Trim Loss Width"), stat = "identity",
# aes(y = y)) +
# geom_bar(data = subset(d, panel == "Tons"), stat = "identity",
# aes(y = -y)) +
# theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))
#
#
# # Use Gridextra
# twidth <- ggplot(data = d, aes(x = Prod.Roll)) +
# geom_bar(data = subset(d, panel == "Trim Loss Width"), stat = "identity",
# aes(y = y))
# tons <- ggplot(data = d, aes(x = Prod.Roll)) +
# geom_bar(data = subset(d, panel == "Tons"), stat = "identity",
# aes(y = y)) +
# scale_y_reverse()
# library(gridExtra)
# grid.arrange(twidth, tons, ncol = 1)
print("Finished Seleting Optimal Parent Rolls for each Possible Number of Parents")
# First get the raw data
| /4.Parent Roll Selection.R | no_license | rschroeder70/test | R | false | false | 11,454 | r | #
# Perform the parant roll selection optimization
#
print("Seleting Optimal Parent Rolls for each Possible Number of Parents")
# Test this with a specific grade and calipeer
#rawData <- filter(rawData, Grade == "SUS" & CalDW == "26-72-W")
# select all the unique parents
parent_types <- rawData %>% group_by(Grade, CalDW, Mill) %>%
summarize(Sizes = n_distinct(Width))
# create data frame to hold slitter limitation information
allNoSlitter <- data.frame("Grade"=c(0),"CalDW"=c(0),"Width"=c(0),
"Plant"=c(0))
# iterate through each plant with slitter limiation
# slitterLimitPlants defined in User Inputs.R
for (tplant in slitterLimitPlants){
# selects data from specified plant with slitter limitation
# select only Grade, CalDW, Width, Plant
noSlitter <- rawData %>% select (Grade, CalDW, Width, Plant)
# select data only from Plant that has slitter limitation
noSlitter <- noSlitter %>% filter (Plant == tplant)
# select only the distinct Grade, CalDW, Widths from that plant
noSlitter <- noSlitter %>% distinct(Grade, CalDW, Width, Plant)
# append to larger data frame
allNoSlitter <- rbind(allNoSlitter,noSlitter)
}
# remove first row of zeros
allNoSlitter <- allNoSlitter[-c(1),]
# create empty data frame to hold options for all grade, CalDW combinations
AllRollSelOptions <- data.frame(list())
parent_stats_all <- list()
# specify number of cores to use for parallel processing
#registerDoParallel(cores=3)
#print("Par Registered")
# Run optimization to get the cost of each possible number of rolls
# for each Grade/CalDW combination
print("Selecting Parent Roll Assignments")
ptype <- 2 # For testing
for (ptype in 1:nrow(parent_types)) {
# filter to find data for one parent
one_parent_grade <- parent_types$Grade[ptype] # Grade
one_parent_calDW <- parent_types$CalDW[ptype] # CalDW
one_parent_mill <- parent_types$Mill[ptype]
print(paste("Parent ", ptype, "/", nrow(parent_types), ", Grade = ",
one_parent_grade, ", CalDW = ",
one_parent_calDW, ", ", parent_types$Sizes[ptype],
" Sizes", sep = ""))
# Get the lead time for this grade/CalDW. Note we use the same logic
# in the simulation file.
cycle_dbr <- cycle_length_list$Mean.DBR[which(
cycle_length_list$Mill.Machine == one_parent_mill &
cycle_length_list$Grade == one_parent_grade &
cycle_length_list$Caliper == str_sub(one_parent_calDW, 1, 2))]
# If we didn't find the lead time, try without the machine number
# gsub("[0-9]", "", str) will remove numbers from a string
if (length(cycle_dbr) == 0 | is.null(cycle_dbr)) {
cycle_dbr <- cycle_length_list$Mean.DBR[which(
gsub("[0-9]", "", cycle_length_list$Mill.Machine) ==
gsub("[0-9]", "", one_parent_mill) &
cycle_length_list$Grade == one_parent_grade &
cycle_length_list$Caliper == str_sub(one_parent_calDW, 1, 2))]
}
# If we still didn't get a match, stop
if (length(cycle_dbr) == 0 | is.null(cycle_dbr)) {
stop("Lead Time not Found")
}
roll_lead_time <- cycle_dbr + order_proc_length + transportation_length
# Get the demand statistics out of the rd_stats_df and convert to the
# appropriate value over the lead time
op_lt_stats <- rd_stats_df %>%
filter(Grade == one_parent_grade, CalDW == one_parent_calDW) %>%
select(Grade, CalDW, Width, dmd_count = nz_dmd_count, dmd_sum,
dmd_mean, dmd_sd, dclass) %>%
mutate(sd_lt = dmd_sd * sqrt(roll_lead_time/dmd_lt_conv),
dmd_lt = dmd_mean * roll_lead_time/dmd_lt_conv,
dmd_review = dmd_mean * cycle_dbr/dmd_lt_conv)
# Add the stats back to the one_parent table
one_parent <- op_lt_stats %>%
select(Grade, CalDW, Width, dmd_count, dmd_sum, sd_lt, dmd_lt,
dmd_review, dclass) %>%
arrange(Grade, CalDW, Width) %>%
ungroup()
# Add the trim freight to be used in the trim cost calculation later
one_parent <-
left_join(one_parent, filter(trim_freight_plant, Mill == ifac),
c("Grade" = "Grade",
"CalDW" = "CalDW",
"Width" = "Width"))
# list of potential parent roll widths
rwidth <- as.numeric(one_parent$Width)
# list of products and rename some columns
pwidth <- one_parent %>% select(width = Width, dmd_count, dmd_sum, dmd_lt,
sd_lt, dmd_review, dclass, Trim.Frt.Cost)
pwidth$width <- as.numeric(pwidth$width)
# noSlitter subset - widths that cannot be split
slitter_limits <- allNoSlitter %>%
filter (Grade == one_parent_grade & CalDW == one_parent_calDW) %>%
select (Width)
# formatting
slitter_limits <- as.data.frame(slitter_limits)
# make into list
slitter_limits_list <- slitter_limits[,1]
# run parent roll selection
source(file.path(basepath, "R", "4a.Sub Parent Roll Optimization.R"))
# the output of this is the RollSelOptions dataframe which includes
# the trim cost and safety stock costs
#
# add roll selection options to list of all roll selection options
AllRollSelOptions <- rbind(AllRollSelOptions,
RollSelOptions)
# Append the parent_stats to the all table to be used in the simulation
parent_stats_all <- rbind(parent_stats_all, parent_stats)
}
# ungroup data frame and rearrange the columns to make it look nice
AllRollSelOptions <- AllRollSelOptions %>% ungroup() %>%
select(Grade, CalDW, Sol.Num.Parents, Sol.Gross.Tons, Sol.Trim.Tons,
Sol.Trim.Cost, Sol.Handling.Cost, Sol.SS.Tons, Sol.SS.Cost,
Sol.OTL.Tons, Sol.Exp.OH.Tons, Sol.Exp.OH.Inv.Cost,
Sol.Exp.OH.Storage.Cost, Sol.Total.Cost,
Parent.Width, Parent.dclass, Parent.Distrib, Parent.SS_Calc,
Parent.Nbr.Subs, Parent.DMD.Count,
Parent.DMD, Parent.SS.Tons, Parent.SS.DOH, Parent.Exp.OH.Tons,
Parent.Exp.OH.Inv.Cost,
Parent.OTL, Prod.Width, Prod.DMD.Tons, Prod.DMD.Count,
Prod.Gross.Tons, Prod.LT.Tons, Prod.dclass,
Prod.Trim.Fact, Prod.Trim.Width, Prod.Trim.Tons)
# select Grade, CalDW, # Parents, & Costs
numOptions <- AllRollSelOptions %>%
select(Grade, CalDW, Sol.Num.Parents, Sol.Trim.Cost,
Sol.Trim.Tons, Sol.Handling.Cost,
Sol.Exp.OH.Storage.Cost, Sol.Exp.OH.Inv.Cost,
Sol.Exp.OH.Tons,
Sol.SS.Cost, Sol.SS.Tons,
Sol.Total.Cost) %>% distinct()
# Determine the optimal grouping of parent rolls for all the
# possible combinations from min to max parent rolls. This will be based on
# minimum total cost: trim cost plus safety stock cost. The output
# goes into the tresults data frame
source(file.path(basepath, "R", "4b.Sub Parent Roll Grouping.R"))
# Now that we know the optimal groupings of parents, add this info
# back tothe AllRollSelOptions table
solutionRollDetails <-
left_join(AllRollSelOptions,
select(solresults, solutionGrade, solutionCalDW, parentNbrs,
solutionNbr, SolParentCount),
by = c("Grade" = "solutionGrade",
"CalDW" = "solutionCalDW",
"Sol.Num.Parents" = "parentNbrs"))
# Remove the options that are not part of an optimal solution
solutionRollDetails <- solutionRollDetails %>%
filter(!is.na(solutionNbr))
# solresults_sum comes from the Sub Parent Roll Grouping.R script
solresults_sum %>% ungroup() %>%
filter(Total.Cost == min(Total.Cost))
# Add the facility we are working on
solresults_sum <- solresults_sum %>%
mutate(Fac = ifac) %>%
select(Fac, everything())
min_sol <- solresults_sum %>% slice(which.min(Total.Cost)) %>%
select(NbrParents, Total.Cost)
solresults_sum$Min.Nbr.Parents <- min_sol$NbrParents
solresults_sum$Min.Total.Cost <- min_sol$Total.Cost
# Put the data in long format for plotting
solresults_sum_plot <- solresults_sum %>%
select(Fac, NbrParents, Total.Cost, Trim.Cost, Handling.Cost, Storage.Cost,
Inv.Carrying.Cost, Min.Nbr.Parents, Min.Total.Cost) %>%
gather(key = `Cost Component`, value = Cost,
Total.Cost:Inv.Carrying.Cost)
psol <- ggplot(solresults_sum_plot,
aes(x = NbrParents, color = `Cost Component`)) +
geom_line(aes(y = Cost), size = 1) +
scale_y_continuous(labels = unit_format(unit = "M", scale = 1e-6)) +
geom_text(aes(label = as.character(Min.Nbr.Parents),
x = Min.Nbr.Parents, y = Min.Total.Cost/2), color = "black") +
geom_segment(aes(x = Min.Nbr.Parents, xend = Min.Nbr.Parents,
y = 0, yend = Min.Total.Cost),
size = 0.4, color = "black") +
scale_color_discrete(breaks = c("Total.Cost", "Handling.Cost",
"Inv.Carrying.Cost",
"Storage.Cost", "Trim.Cost"))
rm(solresults_sum_plot)
ggplotly(psol)
# Plot the trim width by roll demand
min_sol_trim <- solutionRollDetails %>%
filter(SolParentCount == min_sol$NbrParents)
# Try dummy faceting
d1 <- min_sol_trim %>%
select(CalDW, Prod.Width, Prod.Trim.Width) %>%
mutate(y = Prod.Trim.Width, Prod.Roll = paste(CalDW, Prod.Width))
d1$panel <- "Trim Loss Width"
d2 <- min_sol_trim %>%
select(CalDW, Prod.Width, Prod.Trim.Width, y = Prod.Gross.Tons) %>%
mutate(Prod.Roll = paste(CalDW, Prod.Width))
d2$panel <- "Tons"
d <- bind_rows(d1, d2) %>%
arrange(desc(Prod.Trim.Width)) %>%
mutate(Prod.Roll = factor(Prod.Roll, unique(Prod.Roll)))
# use faceting - I think this looks the best
trimplot_all <- ggplot(data = d, aes(x = Prod.Roll, fill = CalDW)) +
geom_bar(stat = "identity", aes(y = y)) +
theme(axis.text.x=element_text(size = 3, angle = 90,hjust = 1,vjust = 0.5)) +
facet_grid(panel ~ ., scales = "free_y") +
scale_y_continuous(labels = comma) +
ggtitle(paste(ifac, "Trim Width by Roll"))
# Make sure we have trim over 2"
if (nrow(filter(d, Prod.Trim.Width >= 2)) > 0) {
trimplot_gt2 <- ggplot(data = filter(d, Prod.Trim.Width >= 2),
aes(x = Prod.Roll, fill = CalDW)) +
geom_bar(stat = "identity", aes(y = y)) +
theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5)) +
facet_grid(panel ~ ., scales = "free_y") +
scale_y_continuous(labels = comma) +
ggtitle(paste(ifac, "Demand Tons & Trim Width for Rolls > 2 inches"))
ggplotly(trimplot_all)
} else (trimplot_gt2 <- NULL)
# # Back to Back plot tests
# ggplot(data = d, aes(x = Prod.Roll, fill = CalDW)) +
# geom_bar(data = subset(d, panel == "Trim Loss Width"), stat = "identity",
# aes(y = y)) +
# geom_bar(data = subset(d, panel == "Tons"), stat = "identity",
# aes(y = -y)) +
# theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))
#
#
# # Use Gridextra
# twidth <- ggplot(data = d, aes(x = Prod.Roll)) +
# geom_bar(data = subset(d, panel == "Trim Loss Width"), stat = "identity",
# aes(y = y))
# tons <- ggplot(data = d, aes(x = Prod.Roll)) +
# geom_bar(data = subset(d, panel == "Tons"), stat = "identity",
# aes(y = y)) +
# scale_y_reverse()
# library(gridExtra)
# grid.arrange(twidth, tons, ncol = 1)
print("Finished Seleting Optimal Parent Rolls for each Possible Number of Parents")
# First get the raw data
|
library(tidyverse)
library(tabulizer)
pdfFile <- tempfile()
download.file('https://github.com/openelections/openelections-sources-tx/raw/master/2016/2016%20DALLAS%201108G%20General%20Final%20PctbyPct%20Totals.pdf',
pdfFile, mode='wb')
INTERACTIVE <- FALSE
dfs <- list()
dfs$RegisteredVoters <- extract_tables(pdfFile, 1:15) %>%
map_df(function(pageMatrix) {
pageMatrix %>%
as_data_frame() %>%
mutate(precinct=gsub(x=V1, pattern='[0-9]+ (.+)', replacement='\\1'),
V2=gsub(x=V2, pattern=' \\.', replacement=' ')) %>%
mutate(V2=gsub(x=V2, pattern=' [ ]*', replacement=' ')) %>%
separate(V2, c('rv', 'bc', 'p'), sep=' ') %>%
select(-V1, -p) %>%
gather(key='office', value='vote', -precinct) %>%
mutate(office=case_when(
office=='rv' ~ 'Registered Voters',
office=='bc' ~ 'Ballots Cast'
)) %>%
mutate(vote=as.integer(vote))
}) %>% bind_rows(
# had to do this by hand...tabulizer extract_tables by area wouldn't work...
tibble(
precinct=rep(c('4662-6550','4664-6554','4664-6555'), 2),
office=c(rep('Registered Voters', 3), rep('Ballots Cast', 3)),
vote=c(249,984,723,127,608,540)
)
) %>% mutate(candidate=office, district=NA_integer_, party=NA_character_)
parseOfficePages <- function(columnNames, partyLookup=character(), officeName, pages, district=NA_integer_, precinctCountChecksum=800) {
ret <- extract_tables(pdfFile, pages) %>%
map_df(parseOfficeMatrix, columnNames=columnNames, partyLookup=partyLookup, officeName=officeName, district=district)
if (!is.null(precinctCountChecksum)) {
if (nrow(ret)/length(columnNames) != precinctCountChecksum) {
warning(paste0('Missing precincts detected for office ', officeName, '. Expecting ', precinctCountChecksum, ' but found ', nrow(ret), ' records and ',
length(columnNames), ' ballot options, or ', (nrow(ret)/length(columnNames)), ' precincts.'))
}
}
ret
}
parseOfficeMatrix <- function(pageMatrix, columnNames, partyLookup=character(), officeName, district=NA_integer_) {
lookup <- columnNames
names(lookup) <- paste0('V', 1 + seq_len(length(columnNames)))
pageMatrix %>%
as_data_frame() %>%
mutate(precinct=gsub(x=V1, pattern='[0-9]+ (.+)', replacement='\\1')) %>%
select(-V1) %>%
gather(key='candidate', value='vote', -precinct) %>%
mutate(candidate=lookup[candidate]) %>%
mutate(office=officeName, district=district, party=partyLookup[candidate], vote=as.integer(vote))
}
dfs$StraightParty <- parseOfficePages(
columnNames=c('Republican Party', 'Democratic Party', 'Libertarian Party', 'Green Party', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Republican Party'='REP', 'Democratic Party'='DEM', 'Libertarian Party'='LIB', 'Green Party'='GRN'),
officeName='Straight Party',
pages=16:30
)
dfs$President <- parseOfficePages(
columnNames=c('Donald J. Trump', 'Hillary Clinton', 'Gary Johnson', 'Jill Stein', 'WRITE-IN', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Donald J. Trump'='REP', 'Hillary Clinton'='DEM', 'Gary Johnson'='LIB', 'Jill Stein'='GRN'),
officeName='President and Vice President',
pages=31:46
)
dfs$House5 <- parseOfficePages(
columnNames=c('Jeb Hensarling', 'Ken Ashby', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Jeb Hensarling'='REP', 'Ken Ashby'='DEM'),
officeName='U.S. House',
district=5,
pages=47:48,
precinctCountChecksum=103
)
dfs$House24 <- parseOfficePages(
columnNames=c('Kenny E. Marchant', 'Jan McDowell', 'Mike Kolls', 'Kevin McCormick', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Kenny E. Marchant'='REP', 'Jan McDowell'='DEM', 'Mike Kolls'='LIB', 'Kevin McCormick'='GRN'),
officeName='U.S. House',
district=24,
pages=49:51,
precinctCountChecksum=132
)
# tabulizer wouldn't parse
dfs$House26 <- tibble(
precinct=c(rep('2910-5709', 5), rep('2911-5710', 5)),
candidate=rep(c('Michael C. Burgess', 'Eric Mauck', 'Mark Boler', 'OVER VOTES', 'UNDER VOTES'), 2),
vote=c(13,9,0,0,1,89,61,6,0,3),
office='U.S. House',
district=26,
party=rep(c('REP','DEM','LIB', NA_character_, NA_character_), 2)
)
dfs$House30 <- parseOfficePages(
columnNames=c('Charles Lingerfelt', 'Eddie Bernice Johnson', 'Jarrett R. Woods', 'Thom Prentice', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Charles Lingerfelt'='REP', 'Eddie Bernice Johnson'='DEM', 'Jarrett R. Woods'='LIB', 'Thom Prentice'='GRN'),
officeName='U.S. House',
district=30,
pages=53:57,
precinctCountChecksum=254
)
dfs$House32 <- parseOfficePages(
columnNames=c('Pete Sessions', 'Ed Rankin', 'Gary Stuard', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Pete Sessions'='REP', 'Ed Rankin'='DEM', 'Gary Stuard'='GRN'),
officeName='U.S. House',
district=32,
pages=58:61,
precinctCountChecksum=200
)
dfs$House33 <- parseOfficePages(
columnNames=c('M.Mark Mitchell', 'Marc Veasey', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('M.Mark Mitchell'='REP', 'Marc Veasey'='DEM'),
officeName='U.S. House',
district=33,
pages=62:63,
precinctCountChecksum=109
)
dfs$RailroadCommissioner <- parseOfficePages(
columnNames=c('Wayne Christian', 'Grady Yarbrough', 'Mark Miller', 'Martina Salinas', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Wayne Christian'='REP', 'Grady Yarbrough'='DEM', 'Mark Miller'='LIB', 'Martina Salinas'='GRN'),
officeName='U.S. House',
pages=64:78
)
dfs$Justice3 <- parseOfficePages(
columnNames=c('Debra Lehrmann', 'Mike Westergren', 'Kathie Glass', 'Rodolfo Rivera Munoz', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Debra Lehrmann'='REP', 'Mike Westergren'='DEM', 'Kathie Glass'='LIB', 'Rodolfo Rivera Munoz'='GRN'),
officeName='Justice, Supreme Court, Pl 3',
pages=79:93
)
dfs$Justice5 <- parseOfficePages(
columnNames=c('Paul Green', 'Dori Contreras Garza', 'Tom Oxford', 'Charles E. Waterbury', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Paul Green'='REP', 'Dori Contreras Garza'='DEM', 'Tom Oxford'='LIB', 'Charles E. Waterbury'='GRN'),
officeName='Justice, Supreme Court, Pl 5',
pages=94:108
)
dfs$Justice9 <- parseOfficePages(
columnNames=c('Eva Guzman', 'Savannah Robinson', 'Don Fulton', 'Jim Chisholm', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Eva Guzman'='REP', 'Savannah Robinson'='DEM', 'Don Fulton'='LIB', 'Jim Chisholm'='GRN'),
officeName='Justice, Supreme Court, Pl 9 DAL COUNTY WIDE',
pages=109:123
)
dfs$Appeals2 <- parseOfficePages(
columnNames=c('Mary Lou Keel', 'Lawrence "Larry" Meyers', 'Mark Ash', 'Adam King Blackwell Reposa', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Mary Lou Keel'='REP', 'Lawrence "Larry" Meyers'='DEM', 'Mark Ash'='LIB', 'Adam King Blackwell Reposa'='GRN'),
officeName='Judge, Ct of Criminal Appeals, Pl 2',
pages=124:138
)
dfs$Appeals5 <- parseOfficePages(
columnNames=c('Scott Walker', 'Betsy Johnson', 'William Bryan Strange, III', 'Judith Sanders-Castro', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Scott Walker'='REP', 'Betsy Johnson'='DEM', 'William Bryan Strange, III'='LIB', 'Judith Sanders-Castro'='GRN'),
officeName='Judge, Ct of Criminal Appeals, Pl 5',
pages=139:153
)
dfs$Appeals6 <- parseOfficePages(
columnNames=c('Michael E. Keasler', 'Robert Burns', 'Mark W. Bennett', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Michael E. Keasler'='REP', 'Robert Burns'='DEM', 'Mark W. Bennett'='LIB'),
officeName='Judge, Ct of Criminal Appeals, Pl 6',
pages=154:168
)
# have to manually find the table on page 170
if (INTERACTIVE) p170 <- extract_areas(pdfFile, 170) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Eric Johnson', 'Heather Marcus', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Eric Johnson'='DEM', 'Heather Marcus'='LIB'),
officeName='State Representative',
district=100
)
dfs$StateRep100 <- parseOfficePages(
columnNames=c('Eric Johnson', 'Heather Marcus', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Eric Johnson'='DEM', 'Heather Marcus'='LIB'),
officeName='State Representative',
district=100,
pages=169,
precinctCountChecksum=NULL
) %>% bind_rows(p170)
dfs$StateRep102 <- parseOfficePages(
columnNames=c('Linda Koop', 'Laura Irvin', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Linda Koop'='REP', 'Laura Irvin'='DEM'),
officeName='State Representative',
district=102,
pages=171,
precinctCountChecksum=47
)
dfs$StateRep103 <- parseOfficePages(
columnNames=c('Rafael M. Anchia', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Rafael M. Anchia'='DEM'),
officeName='State Representative',
district=103,
pages=172:173,
precinctCountChecksum=69
)
dfs$StateRep104 <- parseOfficePages(
columnNames=c('Roberto R. Alonzo', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Roberto R. Alonzo'='DEM'),
officeName='State Representative',
district=104,
pages=174,
precinctCountChecksum=51
)
dfs$StateRep105 <- parseOfficePages(
columnNames=c('Rodney Anderson', 'Terry Meza', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Rodney Anderson'='REP', 'Terry Meza'='DEM'),
officeName='State Representative',
district=105,
pages=175,
precinctCountChecksum=54
)
dfs$StateRep107 <- parseOfficePages(
columnNames=c('Kenneth Sheets', 'Victoria Neave', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Kenneth Sheets'='REP', 'Victoria Neave'='DEM'),
officeName='State Representative',
district=107,
pages=176,
precinctCountChecksum=52
)
dfs$StateRep108 <- parseOfficePages(
columnNames=c('Morgan Meyer', 'Scott Smith', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Morgan Meyer'='REP', 'Scott Smith'='LIB'),
officeName='State Representative',
district=108,
pages=177:178,
precinctCountChecksum=65
)
dfs$StateRep109 <- parseOfficePages(
columnNames=c('A. Denise Russell', 'Helen Giddings', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('A. Denise Russell'='REP', 'Helen Giddings'='DEM'),
officeName='State Representative',
district=109,
pages=179:180,
precinctCountChecksum=66
)
dfs$StateRep110 <- parseOfficePages(
columnNames=c('Toni Rose', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Toni Rose'='DEM'),
officeName='State Representative',
district=110,
pages=181,
precinctCountChecksum=52
)
if (INTERACTIVE) p183 <- extract_areas(pdfFile, 183) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Chad O. Jackson', 'Yvonne Davis', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Chad O. Jackson'='REP', 'Yvonne Davis'='DEM'),
officeName='State Representative',
district=111
)
dfs$StateRep111 <- parseOfficePages(
columnNames=c('Chad O. Jackson', 'Yvonne Davis', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Chad O. Jackson'='REP', 'Yvonne Davis'='DEM'),
officeName='State Representative',
district=111,
pages=182,
precinctCountChecksum=NULL
) %>% bind_rows(p183)
dfs$StateRep112 <- parseOfficePages(
columnNames=c('Angie Chen Button', 'Jack Blackshear', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Angie Chen Button'='REP', 'Jack Blackshear'='DEM'),
officeName='State Representative',
district=112,
pages=184,
precinctCountChecksum=37
)
dfs$StateRep113 <- parseOfficePages(
columnNames=c('Cindy Burkett', 'Rhetta Andrews Bowers', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Cindy Burkett'='REP', 'Rhetta Andrews Bowers'='DEM'),
officeName='State Representative',
district=113,
pages=185,
precinctCountChecksum=43
)
dfs$StateRep114 <- parseOfficePages(
columnNames=c('Jason Villalba', 'Jim Burke', 'Anthony Holan', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Jason Villalba'='REP', 'Jim Burke'='DEM', 'Anthony Holan'='LIB'),
officeName='State Representative',
district=114,
pages=186:187,
precinctCountChecksum=68
)
dfs$StateRep115 <- parseOfficePages(
columnNames=c('Matt Rinaldi', 'Dorotha M. Ocker', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Matt Rinaldi'='REP', 'Dorotha M. Ocker'='DEM'),
officeName='State Representative',
district=115,
pages=188:189,
precinctCountChecksum=66
)
dfs$CoA5Pl4 <- parseOfficePages(
columnNames=c('Lana Myers', 'Gena Slaughter', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Lana Myers'='REP', 'Gena Slaughter'='DEM'),
officeName='Justice, 5th Ct of App Dist, Pl 4',
pages=190:204
)
dfs$CoA5Pl7 <- parseOfficePages(
columnNames=c('David John Schenck', 'Dennise Garcia', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('David John Schenck'='REP', 'Dennise Garcia'='DEM'),
officeName='Justice, 5th Ct of App Dist, Pl 7',
pages=205:219
)
dfs$Judge14 <- parseOfficePages(
columnNames=c('Barry Johnson', 'Eric Moye', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Barry Johnson'='REP', 'Eric Moye'='DEM'),
officeName='Judge, 14th Judicial District',
pages=220:234
)
dfs$Judge95 <- parseOfficePages(
columnNames=c('Ken Molberg', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Ken Molberg'='DEM'),
officeName='Judge, 95th Judicial District',
pages=235:249
)
dfs$Judge162 <- parseOfficePages(
columnNames=c('Gregory Gorman', 'Maricela Moore', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Gregory Gorman'='REP', 'Maricela Moore'='DEM'),
officeName='Judge, 162nd Judicial District',
pages=250:264
)
dfs$Judge195 <- parseOfficePages(
columnNames=c('Mike Lee', 'Hector Garza', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Mike Lee'='REP', 'Hector Garza'='DEM'),
officeName='Judge, 195th Judicial Dist Unexpired',
pages=265:279
)
dfs$Judge254 <- parseOfficePages(
columnNames=c('Susan Rankin', 'Darlene Ewing', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Susan Rankin'='REP', 'Darlene Ewing'='DEM'),
officeName='Judge, 254th Judicial Dist Unexpired',
pages=280:294
)
dfs$CrimJudge2 <- parseOfficePages(
columnNames=c('Tom Spackman', 'Nancy Kennedy', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Tom Spackman'='REP', 'Nancy Kennedy'='DEM'),
officeName='Criminal Dist Judge, Ct No. 2',
pages=295:309
)
dfs$CrimJudge3 <- parseOfficePages(
columnNames=c('Gracie Lewis', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Gracie Lewis'='DEM'),
officeName='Criminal Dist Judge, Ct No. 3',
pages=310:324
)
dfs$CrimJudge4 <- parseOfficePages(
columnNames=c('Dominique Collins', 'William R. Barr', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Dominique Collins'='DEM', 'William R. Barr'='GRN'),
officeName='Criminal Dist Judge, Ct No. 4',
pages=325:339
)
dfs$Sheriff <- parseOfficePages(
columnNames=c('Kirk Launius', 'Lupe Valdez', 'David Geoffrey Morris', 'J. C. Osborne', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Kirk Launius'='REP', 'Lupe Valdez'='DEM', 'David Geoffrey Morris'='LIB', 'J. C. Osborne'='GRN'),
officeName='Sheriff',
pages=340:354
)
dfs$Assessor <- parseOfficePages(
columnNames=c('John R. Ames', 'James Birchfield', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('John R. Ames'='DEM', 'James Birchfield'='LIB'),
officeName='County Tax Assessor-Collector',
pages=355:369
)
dfs$Commissioner1 <- parseOfficePages(
columnNames=c('Steven Rayshell', 'Theresa Daniel', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Steven Rayshell'='REP', 'Theresa Daniel'='DEM'),
officeName='County Commissioner, Pct No. 1',
pages=370:373,
precinctCountChecksum=186
)
dfs$Commissioner3 <- parseOfficePages(
columnNames=c('S.T. Russell', 'John Wiley Price', 'Ona Marie Hendricks', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('S.T. Russell'='REP', 'John Wiley Price'='DEM', 'Ona Marie Hendricks'='GRN'),
officeName='County Commissioner, Pct No. 3',
pages=374:377,
precinctCountChecksum=200
)
dfs$JP2Pl1 <- parseOfficePages(
columnNames=c('Brian Hutcheson', 'Latonya D. Shavers', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Brian Hutcheson'='REP', 'Latonya D. Shavers'='DEM'),
officeName='Justice Peace, Pct No. 2, Pl 1 Unexpired',
pages=378:380,
precinctCountChecksum=131
)
dfs$Constable1 <- parseOfficePages(
columnNames=c('Tracey Gulley', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Tracey Gulley'='DEM'),
officeName='Constable, Pct No. 1 Unexpired Term',
pages=381:383,
precinctCountChecksum=155
)
balchList <- map(1:8, function(propNumber) {
parseOfficePages(
columnNames=c('For (A Favor)', 'Against (En Contra)', 'OVER VOTES', 'UNDER VOTES'),
officeName=paste0('Balch Springs Proposition ', propNumber),
pages=383 + propNumber,
precinctCountChecksum=13
)
})
names(balchList) <- paste0('Balch', 1:8)
dfs <- c(dfs, balchList)
rm(balchList)
if (INTERACTIVE) p392 <- extract_areas(pdfFile, 392) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Leon Payton Tate', 'WRITE-IN', 'OVER VOTES', 'UNDER VOTES'),
officeName='Glenn Heights-Mayor'
)
dfs$GlennHeightsMayor <- p392
if (INTERACTIVE) p393 <- extract_areas(pdfFile, 393) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Tony L. Bradley', 'OVER VOTES', 'UNDER VOTES'),
officeName='Glenn Heights- Council Member Pl 2'
)
dfs$GlennHeightsCouncil2 <- p393
if (INTERACTIVE) p394 <- extract_areas(pdfFile, 394) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Ron Adams', 'OVER VOTES', 'UNDER VOTES'),
officeName='Glenn Heights- Pl 4'
)
dfs$GlennHeightsCouncil4 <- p394
if (INTERACTIVE) p395 <- extract_areas(pdfFile, 395) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Glenn George', 'OVER VOTES', 'UNDER VOTES'),
officeName='Glenn Heights- Council Member Pl 6'
)
dfs$GlennHeightsCouncil6 <- p395
dfs$DallasProposition <- parseOfficePages(
columnNames=c('For (A Favor)', 'Against (En Contra)', 'OVER VOTES', 'UNDER VOTES'),
officeName='City of Dallas Proposition',
pages=396:403,
precinctCountChecksum=419
)
dfs$GPProposition <- parseOfficePages(
columnNames=c('Yes (Si)', 'No (No)', 'OVER VOTES', 'UNDER VOTES'),
officeName='Grand Prairie Proposition 1',
pages=404,
precinctCountChecksum=38
)
dfs$CFBISD <- parseOfficePages(
columnNames=c('For (A Favor)', 'Against (En Contra)', 'OVER VOTES', 'UNDER VOTES'),
officeName='CFBISD Proposition 1',
pages=405,
precinctCountChecksum=38
)
dallas <- bind_rows(dfs) %>%
mutate(county='Dallas') %>%
select(county,precinct,office,district,party,candidate,vote)
write_csv(dallas, '../20161108__tx__general__dallas__precinct.csv', na='')
| /src/openelections-tx-r/Parse_Dallas.R | no_license | openelections/openelections-data-tx | R | false | false | 18,136 | r | library(tidyverse)
library(tabulizer)
pdfFile <- tempfile()
download.file('https://github.com/openelections/openelections-sources-tx/raw/master/2016/2016%20DALLAS%201108G%20General%20Final%20PctbyPct%20Totals.pdf',
pdfFile, mode='wb')
INTERACTIVE <- FALSE
dfs <- list()
dfs$RegisteredVoters <- extract_tables(pdfFile, 1:15) %>%
map_df(function(pageMatrix) {
pageMatrix %>%
as_data_frame() %>%
mutate(precinct=gsub(x=V1, pattern='[0-9]+ (.+)', replacement='\\1'),
V2=gsub(x=V2, pattern=' \\.', replacement=' ')) %>%
mutate(V2=gsub(x=V2, pattern=' [ ]*', replacement=' ')) %>%
separate(V2, c('rv', 'bc', 'p'), sep=' ') %>%
select(-V1, -p) %>%
gather(key='office', value='vote', -precinct) %>%
mutate(office=case_when(
office=='rv' ~ 'Registered Voters',
office=='bc' ~ 'Ballots Cast'
)) %>%
mutate(vote=as.integer(vote))
}) %>% bind_rows(
# had to do this by hand...tabulizer extract_tables by area wouldn't work...
tibble(
precinct=rep(c('4662-6550','4664-6554','4664-6555'), 2),
office=c(rep('Registered Voters', 3), rep('Ballots Cast', 3)),
vote=c(249,984,723,127,608,540)
)
) %>% mutate(candidate=office, district=NA_integer_, party=NA_character_)
parseOfficePages <- function(columnNames, partyLookup=character(), officeName, pages, district=NA_integer_, precinctCountChecksum=800) {
ret <- extract_tables(pdfFile, pages) %>%
map_df(parseOfficeMatrix, columnNames=columnNames, partyLookup=partyLookup, officeName=officeName, district=district)
if (!is.null(precinctCountChecksum)) {
if (nrow(ret)/length(columnNames) != precinctCountChecksum) {
warning(paste0('Missing precincts detected for office ', officeName, '. Expecting ', precinctCountChecksum, ' but found ', nrow(ret), ' records and ',
length(columnNames), ' ballot options, or ', (nrow(ret)/length(columnNames)), ' precincts.'))
}
}
ret
}
parseOfficeMatrix <- function(pageMatrix, columnNames, partyLookup=character(), officeName, district=NA_integer_) {
lookup <- columnNames
names(lookup) <- paste0('V', 1 + seq_len(length(columnNames)))
pageMatrix %>%
as_data_frame() %>%
mutate(precinct=gsub(x=V1, pattern='[0-9]+ (.+)', replacement='\\1')) %>%
select(-V1) %>%
gather(key='candidate', value='vote', -precinct) %>%
mutate(candidate=lookup[candidate]) %>%
mutate(office=officeName, district=district, party=partyLookup[candidate], vote=as.integer(vote))
}
dfs$StraightParty <- parseOfficePages(
columnNames=c('Republican Party', 'Democratic Party', 'Libertarian Party', 'Green Party', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Republican Party'='REP', 'Democratic Party'='DEM', 'Libertarian Party'='LIB', 'Green Party'='GRN'),
officeName='Straight Party',
pages=16:30
)
dfs$President <- parseOfficePages(
columnNames=c('Donald J. Trump', 'Hillary Clinton', 'Gary Johnson', 'Jill Stein', 'WRITE-IN', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Donald J. Trump'='REP', 'Hillary Clinton'='DEM', 'Gary Johnson'='LIB', 'Jill Stein'='GRN'),
officeName='President and Vice President',
pages=31:46
)
dfs$House5 <- parseOfficePages(
columnNames=c('Jeb Hensarling', 'Ken Ashby', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Jeb Hensarling'='REP', 'Ken Ashby'='DEM'),
officeName='U.S. House',
district=5,
pages=47:48,
precinctCountChecksum=103
)
dfs$House24 <- parseOfficePages(
columnNames=c('Kenny E. Marchant', 'Jan McDowell', 'Mike Kolls', 'Kevin McCormick', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Kenny E. Marchant'='REP', 'Jan McDowell'='DEM', 'Mike Kolls'='LIB', 'Kevin McCormick'='GRN'),
officeName='U.S. House',
district=24,
pages=49:51,
precinctCountChecksum=132
)
# tabulizer wouldn't parse
dfs$House26 <- tibble(
precinct=c(rep('2910-5709', 5), rep('2911-5710', 5)),
candidate=rep(c('Michael C. Burgess', 'Eric Mauck', 'Mark Boler', 'OVER VOTES', 'UNDER VOTES'), 2),
vote=c(13,9,0,0,1,89,61,6,0,3),
office='U.S. House',
district=26,
party=rep(c('REP','DEM','LIB', NA_character_, NA_character_), 2)
)
dfs$House30 <- parseOfficePages(
columnNames=c('Charles Lingerfelt', 'Eddie Bernice Johnson', 'Jarrett R. Woods', 'Thom Prentice', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Charles Lingerfelt'='REP', 'Eddie Bernice Johnson'='DEM', 'Jarrett R. Woods'='LIB', 'Thom Prentice'='GRN'),
officeName='U.S. House',
district=30,
pages=53:57,
precinctCountChecksum=254
)
dfs$House32 <- parseOfficePages(
columnNames=c('Pete Sessions', 'Ed Rankin', 'Gary Stuard', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Pete Sessions'='REP', 'Ed Rankin'='DEM', 'Gary Stuard'='GRN'),
officeName='U.S. House',
district=32,
pages=58:61,
precinctCountChecksum=200
)
dfs$House33 <- parseOfficePages(
columnNames=c('M.Mark Mitchell', 'Marc Veasey', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('M.Mark Mitchell'='REP', 'Marc Veasey'='DEM'),
officeName='U.S. House',
district=33,
pages=62:63,
precinctCountChecksum=109
)
dfs$RailroadCommissioner <- parseOfficePages(
columnNames=c('Wayne Christian', 'Grady Yarbrough', 'Mark Miller', 'Martina Salinas', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Wayne Christian'='REP', 'Grady Yarbrough'='DEM', 'Mark Miller'='LIB', 'Martina Salinas'='GRN'),
officeName='U.S. House',
pages=64:78
)
dfs$Justice3 <- parseOfficePages(
columnNames=c('Debra Lehrmann', 'Mike Westergren', 'Kathie Glass', 'Rodolfo Rivera Munoz', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Debra Lehrmann'='REP', 'Mike Westergren'='DEM', 'Kathie Glass'='LIB', 'Rodolfo Rivera Munoz'='GRN'),
officeName='Justice, Supreme Court, Pl 3',
pages=79:93
)
dfs$Justice5 <- parseOfficePages(
columnNames=c('Paul Green', 'Dori Contreras Garza', 'Tom Oxford', 'Charles E. Waterbury', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Paul Green'='REP', 'Dori Contreras Garza'='DEM', 'Tom Oxford'='LIB', 'Charles E. Waterbury'='GRN'),
officeName='Justice, Supreme Court, Pl 5',
pages=94:108
)
dfs$Justice9 <- parseOfficePages(
columnNames=c('Eva Guzman', 'Savannah Robinson', 'Don Fulton', 'Jim Chisholm', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Eva Guzman'='REP', 'Savannah Robinson'='DEM', 'Don Fulton'='LIB', 'Jim Chisholm'='GRN'),
officeName='Justice, Supreme Court, Pl 9 DAL COUNTY WIDE',
pages=109:123
)
dfs$Appeals2 <- parseOfficePages(
columnNames=c('Mary Lou Keel', 'Lawrence "Larry" Meyers', 'Mark Ash', 'Adam King Blackwell Reposa', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Mary Lou Keel'='REP', 'Lawrence "Larry" Meyers'='DEM', 'Mark Ash'='LIB', 'Adam King Blackwell Reposa'='GRN'),
officeName='Judge, Ct of Criminal Appeals, Pl 2',
pages=124:138
)
dfs$Appeals5 <- parseOfficePages(
columnNames=c('Scott Walker', 'Betsy Johnson', 'William Bryan Strange, III', 'Judith Sanders-Castro', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Scott Walker'='REP', 'Betsy Johnson'='DEM', 'William Bryan Strange, III'='LIB', 'Judith Sanders-Castro'='GRN'),
officeName='Judge, Ct of Criminal Appeals, Pl 5',
pages=139:153
)
dfs$Appeals6 <- parseOfficePages(
columnNames=c('Michael E. Keasler', 'Robert Burns', 'Mark W. Bennett', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Michael E. Keasler'='REP', 'Robert Burns'='DEM', 'Mark W. Bennett'='LIB'),
officeName='Judge, Ct of Criminal Appeals, Pl 6',
pages=154:168
)
# have to manually find the table on page 170
if (INTERACTIVE) p170 <- extract_areas(pdfFile, 170) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Eric Johnson', 'Heather Marcus', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Eric Johnson'='DEM', 'Heather Marcus'='LIB'),
officeName='State Representative',
district=100
)
dfs$StateRep100 <- parseOfficePages(
columnNames=c('Eric Johnson', 'Heather Marcus', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Eric Johnson'='DEM', 'Heather Marcus'='LIB'),
officeName='State Representative',
district=100,
pages=169,
precinctCountChecksum=NULL
) %>% bind_rows(p170)
dfs$StateRep102 <- parseOfficePages(
columnNames=c('Linda Koop', 'Laura Irvin', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Linda Koop'='REP', 'Laura Irvin'='DEM'),
officeName='State Representative',
district=102,
pages=171,
precinctCountChecksum=47
)
dfs$StateRep103 <- parseOfficePages(
columnNames=c('Rafael M. Anchia', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Rafael M. Anchia'='DEM'),
officeName='State Representative',
district=103,
pages=172:173,
precinctCountChecksum=69
)
dfs$StateRep104 <- parseOfficePages(
columnNames=c('Roberto R. Alonzo', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Roberto R. Alonzo'='DEM'),
officeName='State Representative',
district=104,
pages=174,
precinctCountChecksum=51
)
dfs$StateRep105 <- parseOfficePages(
columnNames=c('Rodney Anderson', 'Terry Meza', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Rodney Anderson'='REP', 'Terry Meza'='DEM'),
officeName='State Representative',
district=105,
pages=175,
precinctCountChecksum=54
)
dfs$StateRep107 <- parseOfficePages(
columnNames=c('Kenneth Sheets', 'Victoria Neave', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Kenneth Sheets'='REP', 'Victoria Neave'='DEM'),
officeName='State Representative',
district=107,
pages=176,
precinctCountChecksum=52
)
dfs$StateRep108 <- parseOfficePages(
columnNames=c('Morgan Meyer', 'Scott Smith', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Morgan Meyer'='REP', 'Scott Smith'='LIB'),
officeName='State Representative',
district=108,
pages=177:178,
precinctCountChecksum=65
)
dfs$StateRep109 <- parseOfficePages(
columnNames=c('A. Denise Russell', 'Helen Giddings', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('A. Denise Russell'='REP', 'Helen Giddings'='DEM'),
officeName='State Representative',
district=109,
pages=179:180,
precinctCountChecksum=66
)
dfs$StateRep110 <- parseOfficePages(
columnNames=c('Toni Rose', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Toni Rose'='DEM'),
officeName='State Representative',
district=110,
pages=181,
precinctCountChecksum=52
)
if (INTERACTIVE) p183 <- extract_areas(pdfFile, 183) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Chad O. Jackson', 'Yvonne Davis', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Chad O. Jackson'='REP', 'Yvonne Davis'='DEM'),
officeName='State Representative',
district=111
)
dfs$StateRep111 <- parseOfficePages(
columnNames=c('Chad O. Jackson', 'Yvonne Davis', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Chad O. Jackson'='REP', 'Yvonne Davis'='DEM'),
officeName='State Representative',
district=111,
pages=182,
precinctCountChecksum=NULL
) %>% bind_rows(p183)
dfs$StateRep112 <- parseOfficePages(
columnNames=c('Angie Chen Button', 'Jack Blackshear', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Angie Chen Button'='REP', 'Jack Blackshear'='DEM'),
officeName='State Representative',
district=112,
pages=184,
precinctCountChecksum=37
)
dfs$StateRep113 <- parseOfficePages(
columnNames=c('Cindy Burkett', 'Rhetta Andrews Bowers', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Cindy Burkett'='REP', 'Rhetta Andrews Bowers'='DEM'),
officeName='State Representative',
district=113,
pages=185,
precinctCountChecksum=43
)
dfs$StateRep114 <- parseOfficePages(
columnNames=c('Jason Villalba', 'Jim Burke', 'Anthony Holan', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Jason Villalba'='REP', 'Jim Burke'='DEM', 'Anthony Holan'='LIB'),
officeName='State Representative',
district=114,
pages=186:187,
precinctCountChecksum=68
)
dfs$StateRep115 <- parseOfficePages(
columnNames=c('Matt Rinaldi', 'Dorotha M. Ocker', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Matt Rinaldi'='REP', 'Dorotha M. Ocker'='DEM'),
officeName='State Representative',
district=115,
pages=188:189,
precinctCountChecksum=66
)
dfs$CoA5Pl4 <- parseOfficePages(
columnNames=c('Lana Myers', 'Gena Slaughter', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Lana Myers'='REP', 'Gena Slaughter'='DEM'),
officeName='Justice, 5th Ct of App Dist, Pl 4',
pages=190:204
)
dfs$CoA5Pl7 <- parseOfficePages(
columnNames=c('David John Schenck', 'Dennise Garcia', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('David John Schenck'='REP', 'Dennise Garcia'='DEM'),
officeName='Justice, 5th Ct of App Dist, Pl 7',
pages=205:219
)
dfs$Judge14 <- parseOfficePages(
columnNames=c('Barry Johnson', 'Eric Moye', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Barry Johnson'='REP', 'Eric Moye'='DEM'),
officeName='Judge, 14th Judicial District',
pages=220:234
)
dfs$Judge95 <- parseOfficePages(
columnNames=c('Ken Molberg', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Ken Molberg'='DEM'),
officeName='Judge, 95th Judicial District',
pages=235:249
)
dfs$Judge162 <- parseOfficePages(
columnNames=c('Gregory Gorman', 'Maricela Moore', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Gregory Gorman'='REP', 'Maricela Moore'='DEM'),
officeName='Judge, 162nd Judicial District',
pages=250:264
)
dfs$Judge195 <- parseOfficePages(
columnNames=c('Mike Lee', 'Hector Garza', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Mike Lee'='REP', 'Hector Garza'='DEM'),
officeName='Judge, 195th Judicial Dist Unexpired',
pages=265:279
)
dfs$Judge254 <- parseOfficePages(
columnNames=c('Susan Rankin', 'Darlene Ewing', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Susan Rankin'='REP', 'Darlene Ewing'='DEM'),
officeName='Judge, 254th Judicial Dist Unexpired',
pages=280:294
)
dfs$CrimJudge2 <- parseOfficePages(
columnNames=c('Tom Spackman', 'Nancy Kennedy', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Tom Spackman'='REP', 'Nancy Kennedy'='DEM'),
officeName='Criminal Dist Judge, Ct No. 2',
pages=295:309
)
dfs$CrimJudge3 <- parseOfficePages(
columnNames=c('Gracie Lewis', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Gracie Lewis'='DEM'),
officeName='Criminal Dist Judge, Ct No. 3',
pages=310:324
)
dfs$CrimJudge4 <- parseOfficePages(
columnNames=c('Dominique Collins', 'William R. Barr', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Dominique Collins'='DEM', 'William R. Barr'='GRN'),
officeName='Criminal Dist Judge, Ct No. 4',
pages=325:339
)
dfs$Sheriff <- parseOfficePages(
columnNames=c('Kirk Launius', 'Lupe Valdez', 'David Geoffrey Morris', 'J. C. Osborne', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Kirk Launius'='REP', 'Lupe Valdez'='DEM', 'David Geoffrey Morris'='LIB', 'J. C. Osborne'='GRN'),
officeName='Sheriff',
pages=340:354
)
dfs$Assessor <- parseOfficePages(
columnNames=c('John R. Ames', 'James Birchfield', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('John R. Ames'='DEM', 'James Birchfield'='LIB'),
officeName='County Tax Assessor-Collector',
pages=355:369
)
dfs$Commissioner1 <- parseOfficePages(
columnNames=c('Steven Rayshell', 'Theresa Daniel', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Steven Rayshell'='REP', 'Theresa Daniel'='DEM'),
officeName='County Commissioner, Pct No. 1',
pages=370:373,
precinctCountChecksum=186
)
dfs$Commissioner3 <- parseOfficePages(
columnNames=c('S.T. Russell', 'John Wiley Price', 'Ona Marie Hendricks', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('S.T. Russell'='REP', 'John Wiley Price'='DEM', 'Ona Marie Hendricks'='GRN'),
officeName='County Commissioner, Pct No. 3',
pages=374:377,
precinctCountChecksum=200
)
dfs$JP2Pl1 <- parseOfficePages(
columnNames=c('Brian Hutcheson', 'Latonya D. Shavers', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Brian Hutcheson'='REP', 'Latonya D. Shavers'='DEM'),
officeName='Justice Peace, Pct No. 2, Pl 1 Unexpired',
pages=378:380,
precinctCountChecksum=131
)
dfs$Constable1 <- parseOfficePages(
columnNames=c('Tracey Gulley', 'OVER VOTES', 'UNDER VOTES'),
partyLookup=c('Tracey Gulley'='DEM'),
officeName='Constable, Pct No. 1 Unexpired Term',
pages=381:383,
precinctCountChecksum=155
)
balchList <- map(1:8, function(propNumber) {
parseOfficePages(
columnNames=c('For (A Favor)', 'Against (En Contra)', 'OVER VOTES', 'UNDER VOTES'),
officeName=paste0('Balch Springs Proposition ', propNumber),
pages=383 + propNumber,
precinctCountChecksum=13
)
})
names(balchList) <- paste0('Balch', 1:8)
dfs <- c(dfs, balchList)
rm(balchList)
if (INTERACTIVE) p392 <- extract_areas(pdfFile, 392) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Leon Payton Tate', 'WRITE-IN', 'OVER VOTES', 'UNDER VOTES'),
officeName='Glenn Heights-Mayor'
)
dfs$GlennHeightsMayor <- p392
if (INTERACTIVE) p393 <- extract_areas(pdfFile, 393) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Tony L. Bradley', 'OVER VOTES', 'UNDER VOTES'),
officeName='Glenn Heights- Council Member Pl 2'
)
dfs$GlennHeightsCouncil2 <- p393
if (INTERACTIVE) p394 <- extract_areas(pdfFile, 394) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Ron Adams', 'OVER VOTES', 'UNDER VOTES'),
officeName='Glenn Heights- Pl 4'
)
dfs$GlennHeightsCouncil4 <- p394
if (INTERACTIVE) p395 <- extract_areas(pdfFile, 395) %>%
.[[1]] %>%
parseOfficeMatrix(
columnNames=c('Glenn George', 'OVER VOTES', 'UNDER VOTES'),
officeName='Glenn Heights- Council Member Pl 6'
)
dfs$GlennHeightsCouncil6 <- p395
dfs$DallasProposition <- parseOfficePages(
columnNames=c('For (A Favor)', 'Against (En Contra)', 'OVER VOTES', 'UNDER VOTES'),
officeName='City of Dallas Proposition',
pages=396:403,
precinctCountChecksum=419
)
dfs$GPProposition <- parseOfficePages(
columnNames=c('Yes (Si)', 'No (No)', 'OVER VOTES', 'UNDER VOTES'),
officeName='Grand Prairie Proposition 1',
pages=404,
precinctCountChecksum=38
)
dfs$CFBISD <- parseOfficePages(
columnNames=c('For (A Favor)', 'Against (En Contra)', 'OVER VOTES', 'UNDER VOTES'),
officeName='CFBISD Proposition 1',
pages=405,
precinctCountChecksum=38
)
dallas <- bind_rows(dfs) %>%
mutate(county='Dallas') %>%
select(county,precinct,office,district,party,candidate,vote)
write_csv(dallas, '../20161108__tx__general__dallas__precinct.csv', na='')
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/stream_data.R
\name{stream_read_orc}
\alias{stream_read_orc}
\title{Read ORC Stream}
\usage{
stream_read_orc(sc, path, name = NULL, columns = NULL,
options = list(), ...)
}
\arguments{
\item{sc}{A \code{spark_connection}.}
\item{path}{The path to the file. Needs to be accessible from the cluster.
Supports the \samp{"hdfs://"}, \samp{"s3a://"} and \samp{"file://"} protocols.}
\item{name}{The name to assign to the newly generated stream.}
\item{columns}{A vector of column names or a named vector of column types.
If specified, the elements can be \code{"binary"} for \code{BinaryType},
\code{"boolean"} for \code{BooleanType}, \code{"byte"} for \code{ByteType},
\code{"integer"} for \code{IntegerType}, \code{"integer64"} for \code{LongType},
\code{"double"} for \code{DoubleType}, \code{"character"} for \code{StringType},
\code{"timestamp"} for \code{TimestampType} and \code{"date"} for \code{DateType}.}
\item{options}{A list of strings with additional options.}
\item{...}{Optional arguments; currently unused.}
}
\description{
Reads an \href{https://orc.apache.org/}{ORC} stream as a Spark dataframe stream.
}
\examples{
\dontrun{
sc <- spark_connect(master = "local")
sdf_len(sc, 10) \%>\% spark_write_orc("orc-in")
stream <- stream_read_orc(sc, "orc-in") \%>\% stream_write_orc("orc-out")
stream_stop(stream)
}
}
\seealso{
Other Spark stream serialization: \code{\link{stream_read_csv}},
\code{\link{stream_read_delta}},
\code{\link{stream_read_json}},
\code{\link{stream_read_kafka}},
\code{\link{stream_read_parquet}},
\code{\link{stream_read_socket}},
\code{\link{stream_read_text}},
\code{\link{stream_write_console}},
\code{\link{stream_write_csv}},
\code{\link{stream_write_delta}},
\code{\link{stream_write_json}},
\code{\link{stream_write_kafka}},
\code{\link{stream_write_memory}},
\code{\link{stream_write_orc}},
\code{\link{stream_write_parquet}},
\code{\link{stream_write_text}}
}
\concept{Spark stream serialization}
| /man/stream_read_orc.Rd | permissive | lu-wang-dl/sparklyr | R | false | true | 2,062 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/stream_data.R
\name{stream_read_orc}
\alias{stream_read_orc}
\title{Read ORC Stream}
\usage{
stream_read_orc(sc, path, name = NULL, columns = NULL,
options = list(), ...)
}
\arguments{
\item{sc}{A \code{spark_connection}.}
\item{path}{The path to the file. Needs to be accessible from the cluster.
Supports the \samp{"hdfs://"}, \samp{"s3a://"} and \samp{"file://"} protocols.}
\item{name}{The name to assign to the newly generated stream.}
\item{columns}{A vector of column names or a named vector of column types.
If specified, the elements can be \code{"binary"} for \code{BinaryType},
\code{"boolean"} for \code{BooleanType}, \code{"byte"} for \code{ByteType},
\code{"integer"} for \code{IntegerType}, \code{"integer64"} for \code{LongType},
\code{"double"} for \code{DoubleType}, \code{"character"} for \code{StringType},
\code{"timestamp"} for \code{TimestampType} and \code{"date"} for \code{DateType}.}
\item{options}{A list of strings with additional options.}
\item{...}{Optional arguments; currently unused.}
}
\description{
Reads an \href{https://orc.apache.org/}{ORC} stream as a Spark dataframe stream.
}
\examples{
\dontrun{
sc <- spark_connect(master = "local")
sdf_len(sc, 10) \%>\% spark_write_orc("orc-in")
stream <- stream_read_orc(sc, "orc-in") \%>\% stream_write_orc("orc-out")
stream_stop(stream)
}
}
\seealso{
Other Spark stream serialization: \code{\link{stream_read_csv}},
\code{\link{stream_read_delta}},
\code{\link{stream_read_json}},
\code{\link{stream_read_kafka}},
\code{\link{stream_read_parquet}},
\code{\link{stream_read_socket}},
\code{\link{stream_read_text}},
\code{\link{stream_write_console}},
\code{\link{stream_write_csv}},
\code{\link{stream_write_delta}},
\code{\link{stream_write_json}},
\code{\link{stream_write_kafka}},
\code{\link{stream_write_memory}},
\code{\link{stream_write_orc}},
\code{\link{stream_write_parquet}},
\code{\link{stream_write_text}}
}
\concept{Spark stream serialization}
|
#Author - Yatish B. Patil
# This script is used for the RNASeq QC report for read counts, phred quality score, mapping percentage and RNA species.
rm(list=ls())
source("http://bioconductor.org/biocLite.R")
# library
require(ggplot2)
require(reshape)
require(scales)
###### Creating folder structure as main, scripts and output
mainDir = "/Users/ypatil/Dropbox (SPM)/Yatish/Analysis/SPRECMED/Internal/COLON/Human/RNASeq/Mayo/neil_ihrke/data/set_1/89_samples/QC/"
scrDir = "/Users/ypatil/Dropbox (SPM)/Yatish/Analysis/SPRECMED/Internal/COLON/Human/RNASeq/Mayo/neil_ihrke/data/set_1/89_samples/QC/scripts/"
dataDir = "/Users/ypatil/Dropbox (SPM)/Yatish/Analysis/SPRECMED/Internal/COLON/Human/RNASeq/Mayo/neil_ihrke/data/set_1/89_samples/QC/data/"
oDir = "/Users/ypatil/Dropbox (SPM)/Yatish/Analysis/SPRECMED/Internal/COLON/Human/RNASeq/Mayo/neil_ihrke/data/set_1/89_samples/QC/output/"
outDir <- paste0(oDir,Sys.Date(),"_QC_RNASeq_Mayo_Neil_Ihrke_Human_BC_89_samples/")
dir.create(outDir, showWarnings = FALSE)
#######################
#fastqc_avg_BC_samples.txt
#rna_species_BC_samples.txt
#rnaseq_genome_mapping_percentage_BC.txt
#rnaseq_transcriptome_mapping_percentage_BC.txt
#sorted_fastq_read_counts_BC_samples.txt
fastqReadFile = paste0(dataDir,"sorted_fastq_read_counts_BC_samples.txt")
rd = read.delim(fastqReadFile,header = FALSE,sep = " ");dim(rd)
#rd$V1 = NULL
colnames(rd) = c("Samples","Counts")
rownames(rd) = rd$Samples
r1pos = grep("R1",rownames(rd))
r1 = rd[r1pos,]
#samples = as.data.frame(sapply(strsplit(rownames(r1), split= "\\_"), function(x) x[2]))
samples = as.data.frame(rownames(r1))
r2pos = grep("R2",rownames(rd))
r2 = rd[r2pos,]
fq_read_count = cbind(samples,r1$Counts,r2$Counts)
colnames(fq_read_count) = c("Samples","R1","R2")
fq_read_count$Samples = gsub("_R1","",fq_read_count$Samples)
# Grouped Bar plot
fq_read_count$Samples = reorder(fq_read_count$Samples, fq_read_count$R1)
fq_read_count$Samples = factor(fq_read_count$Samples, levels=rev(levels(fq_read_count$Samples)))
fq_read_count[order(fq_read_count$R1),]
read_count_dat = melt(fq_read_count)
colnames(read_count_dat) = c("Samples","Paired_Reads","Read_Counts")
g1 = ggplot(read_count_dat, aes(x=Samples,y=Read_Counts,fill=Paired_Reads)) +
geom_bar(position = "dodge",stat="identity") +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
ggtitle("Statistics of Quality Reads") +
theme(plot.title = element_text(color = "orange",lineheight=.8, face="bold",hjust = 0.5))
#dev.off()
### 2. fastqc quality Q30 - fastqc value
q30File = paste0(dataDir,"fastqc_avg_BC_samples.txt")
q30 = read.delim(q30File,header = FALSE,sep = " ",row.names = 1);dim(q30)
#samples = as.data.frame(sapply(strsplit(rownames(q30), split= "-"), function(x) x[1]))
q30Dat = cbind(rownames(q30),q30)
colnames(q30Dat) = c("Samples","Q30_Value")
rownames(q30Dat) = NULL
q30Dat$Samples = reorder(q30Dat$Samples, q30Dat$Q30_Value)
q30Dat$Samples = factor(q30Dat$Samples, levels=rev(levels(q30Dat$Samples)))
g2 = ggplot(q30Dat, aes(x=Samples,y=Q30_Value,group = 1)) +
geom_line(color = "red",size = 0.5) +
theme(axis.text.x = element_text(angle = 0, hjust = 1, size = 20, vjust=1, margin=margin(2,0,0,0)),
#axis.text.y = element_text(hjust = 1.5, size = 20, vjust=1, margin=margin(2,0,0,0)),
axis.text.y = element_blank(),
axis.title.x = element_text(size = 30),
axis.title.y = element_text(size = 30),legend.key.size = unit(2,"cm"),
legend.title = element_text(size = 30),legend.text = element_text(size = 15))+
labs(title="Read Quality-Q30 using FastQC")+
theme(plot.title = element_text(color = "orange",lineheight=.8, face="bold",hjust = 0.5,size = 30))+
coord_flip()
#dev.off()
### 3. Mapping Quality - to transcriptome and genome
trFile = paste0(dataDir,"rnaseq_transcriptome_mapping_percentage_BC.txt")
tr = read.delim(trFile,header=FALSE,sep=" ",row.names = 1);dim(tr)
gmFile = paste0(dataDir,"rnaseq_genome_mapping_percentage_BC.txt")
gm = read.delim(gmFile,header=FALSE,sep="\t",row.names = 1);dim(gm)
samples = as.data.frame(sapply(strsplit(rownames(tr), split= "\\/"), function(x) x[1]))
tr_gm = as.data.frame(cbind(samples,tr$V2,gm$V2));dim(tr_gm)
colnames(tr_gm) =c ("Samples","Transcriptome","Genome")
mapping_count <- tr_gm
mapping_count_datFile = paste0(outDir,Sys.Date(),"_mapping_perc_transcriptome_genome_human_89_BC_Mayo.txt",sep="")
write.table(mapping_count,mapping_count_datFile,sep = "\t",row.names = FALSE)
# Grouped Bar plot
mapping_count$Samples = reorder(mapping_count$Samples, mapping_count$Transcriptome)
mapping_count$Samples = factor(mapping_count$Samples, levels=rev(levels(mapping_count$Samples)))
mapping_count[order(mapping_count[,2],mapping_count[,3],decreasing=TRUE),]
mapping_count_dat = melt(mapping_count)
colnames(mapping_count_dat) = c("Samples","Transcriptome_Genome","Mapping_Percentage")
#ggsave(mapping_count_datFile, device = "pdf", width = 10, height = 10)
g3 = ggplot(mapping_count_dat, aes(x=Samples,y=Mapping_Percentage,fill=Transcriptome_Genome)) +
geom_bar(position = "dodge",stat="identity") +
theme(axis.text.x = element_text(angle = 90, hjust = 1,size = 20)) +
theme(axis.text.y = element_text(size = 20)) +
ggtitle("Mapping Percentage from SAMTools - Flagstat") +
theme(plot.title = element_text(color = "orange",lineheight=.8, face="bold",hjust = 0.5))
#dev.off()
# 4. RNA Species quality
rnaFile = paste0(dataDir,"rna_species_BC_samples.txt")
rnaCount = read.delim(rnaFile,header=FALSE,sep="\t",row.names = 1)
samples = as.data.frame(sapply(strsplit(rownames(rnaCount), split= "\\/"), function(x) x[1]))
rnaCount1 = cbind(samples,rnaCount$V2,rnaCount$V3,rnaCount$V4,rnaCount$V5,rnaCount$V6)
colnames(rnaCount1) = c("Samples","Ribosomal","Coding","UTR","Intronic","Intergenic")
rnaCount_dat = melt(rnaCount1)
colnames(rnaCount_dat) = c("Samples","RNA_Species","Percentage")
g4 = ggplot(rnaCount_dat, aes(x=Samples,y=Percentage,fill=RNA_Species)) +
geom_bar(position = "fill",stat="identity") +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
ggtitle("RNA Quality and Species Information from Picard") +
scale_y_continuous(labels = percent_format())+
theme(axis.text.x = element_text(size = 20)) +
theme(axis.text.y = element_text(size = 20)) +
theme(plot.title = element_text(color = "orange",lineheight=.8, face="bold",hjust = 0.5))
plots = list(g1,g2,g3,g4)
pdf(paste0(outDir,Sys.Date(),"QC_report_RNASeq_Neil_Ihrke_Mayo_Human_PanNet_89_BC_samples",".pdf"),width=30,height=10)
lapply(plots, eval)
dev.off()
| /rnaseq_results_doc.R | no_license | syspremed/rnaseqAnalysis | R | false | false | 6,839 | r | #Author - Yatish B. Patil
# This script is used for the RNASeq QC report for read counts, phred quality score, mapping percentage and RNA species.
rm(list=ls())
source("http://bioconductor.org/biocLite.R")
# library
require(ggplot2)
require(reshape)
require(scales)
###### Creating folder structure as main, scripts and output
mainDir = "/Users/ypatil/Dropbox (SPM)/Yatish/Analysis/SPRECMED/Internal/COLON/Human/RNASeq/Mayo/neil_ihrke/data/set_1/89_samples/QC/"
scrDir = "/Users/ypatil/Dropbox (SPM)/Yatish/Analysis/SPRECMED/Internal/COLON/Human/RNASeq/Mayo/neil_ihrke/data/set_1/89_samples/QC/scripts/"
dataDir = "/Users/ypatil/Dropbox (SPM)/Yatish/Analysis/SPRECMED/Internal/COLON/Human/RNASeq/Mayo/neil_ihrke/data/set_1/89_samples/QC/data/"
oDir = "/Users/ypatil/Dropbox (SPM)/Yatish/Analysis/SPRECMED/Internal/COLON/Human/RNASeq/Mayo/neil_ihrke/data/set_1/89_samples/QC/output/"
outDir <- paste0(oDir,Sys.Date(),"_QC_RNASeq_Mayo_Neil_Ihrke_Human_BC_89_samples/")
dir.create(outDir, showWarnings = FALSE)
#######################
#fastqc_avg_BC_samples.txt
#rna_species_BC_samples.txt
#rnaseq_genome_mapping_percentage_BC.txt
#rnaseq_transcriptome_mapping_percentage_BC.txt
#sorted_fastq_read_counts_BC_samples.txt
fastqReadFile = paste0(dataDir,"sorted_fastq_read_counts_BC_samples.txt")
rd = read.delim(fastqReadFile,header = FALSE,sep = " ");dim(rd)
#rd$V1 = NULL
colnames(rd) = c("Samples","Counts")
rownames(rd) = rd$Samples
r1pos = grep("R1",rownames(rd))
r1 = rd[r1pos,]
#samples = as.data.frame(sapply(strsplit(rownames(r1), split= "\\_"), function(x) x[2]))
samples = as.data.frame(rownames(r1))
r2pos = grep("R2",rownames(rd))
r2 = rd[r2pos,]
fq_read_count = cbind(samples,r1$Counts,r2$Counts)
colnames(fq_read_count) = c("Samples","R1","R2")
fq_read_count$Samples = gsub("_R1","",fq_read_count$Samples)
# Grouped Bar plot
fq_read_count$Samples = reorder(fq_read_count$Samples, fq_read_count$R1)
fq_read_count$Samples = factor(fq_read_count$Samples, levels=rev(levels(fq_read_count$Samples)))
fq_read_count[order(fq_read_count$R1),]
read_count_dat = melt(fq_read_count)
colnames(read_count_dat) = c("Samples","Paired_Reads","Read_Counts")
g1 = ggplot(read_count_dat, aes(x=Samples,y=Read_Counts,fill=Paired_Reads)) +
geom_bar(position = "dodge",stat="identity") +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
ggtitle("Statistics of Quality Reads") +
theme(plot.title = element_text(color = "orange",lineheight=.8, face="bold",hjust = 0.5))
#dev.off()
### 2. fastqc quality Q30 - fastqc value
q30File = paste0(dataDir,"fastqc_avg_BC_samples.txt")
q30 = read.delim(q30File,header = FALSE,sep = " ",row.names = 1);dim(q30)
#samples = as.data.frame(sapply(strsplit(rownames(q30), split= "-"), function(x) x[1]))
q30Dat = cbind(rownames(q30),q30)
colnames(q30Dat) = c("Samples","Q30_Value")
rownames(q30Dat) = NULL
q30Dat$Samples = reorder(q30Dat$Samples, q30Dat$Q30_Value)
q30Dat$Samples = factor(q30Dat$Samples, levels=rev(levels(q30Dat$Samples)))
g2 = ggplot(q30Dat, aes(x=Samples,y=Q30_Value,group = 1)) +
geom_line(color = "red",size = 0.5) +
theme(axis.text.x = element_text(angle = 0, hjust = 1, size = 20, vjust=1, margin=margin(2,0,0,0)),
#axis.text.y = element_text(hjust = 1.5, size = 20, vjust=1, margin=margin(2,0,0,0)),
axis.text.y = element_blank(),
axis.title.x = element_text(size = 30),
axis.title.y = element_text(size = 30),legend.key.size = unit(2,"cm"),
legend.title = element_text(size = 30),legend.text = element_text(size = 15))+
labs(title="Read Quality-Q30 using FastQC")+
theme(plot.title = element_text(color = "orange",lineheight=.8, face="bold",hjust = 0.5,size = 30))+
coord_flip()
#dev.off()
### 3. Mapping Quality - to transcriptome and genome
trFile = paste0(dataDir,"rnaseq_transcriptome_mapping_percentage_BC.txt")
tr = read.delim(trFile,header=FALSE,sep=" ",row.names = 1);dim(tr)
gmFile = paste0(dataDir,"rnaseq_genome_mapping_percentage_BC.txt")
gm = read.delim(gmFile,header=FALSE,sep="\t",row.names = 1);dim(gm)
samples = as.data.frame(sapply(strsplit(rownames(tr), split= "\\/"), function(x) x[1]))
tr_gm = as.data.frame(cbind(samples,tr$V2,gm$V2));dim(tr_gm)
colnames(tr_gm) =c ("Samples","Transcriptome","Genome")
mapping_count <- tr_gm
mapping_count_datFile = paste0(outDir,Sys.Date(),"_mapping_perc_transcriptome_genome_human_89_BC_Mayo.txt",sep="")
write.table(mapping_count,mapping_count_datFile,sep = "\t",row.names = FALSE)
# Grouped Bar plot
mapping_count$Samples = reorder(mapping_count$Samples, mapping_count$Transcriptome)
mapping_count$Samples = factor(mapping_count$Samples, levels=rev(levels(mapping_count$Samples)))
mapping_count[order(mapping_count[,2],mapping_count[,3],decreasing=TRUE),]
mapping_count_dat = melt(mapping_count)
colnames(mapping_count_dat) = c("Samples","Transcriptome_Genome","Mapping_Percentage")
#ggsave(mapping_count_datFile, device = "pdf", width = 10, height = 10)
g3 = ggplot(mapping_count_dat, aes(x=Samples,y=Mapping_Percentage,fill=Transcriptome_Genome)) +
geom_bar(position = "dodge",stat="identity") +
theme(axis.text.x = element_text(angle = 90, hjust = 1,size = 20)) +
theme(axis.text.y = element_text(size = 20)) +
ggtitle("Mapping Percentage from SAMTools - Flagstat") +
theme(plot.title = element_text(color = "orange",lineheight=.8, face="bold",hjust = 0.5))
#dev.off()
# 4. RNA Species quality
rnaFile = paste0(dataDir,"rna_species_BC_samples.txt")
rnaCount = read.delim(rnaFile,header=FALSE,sep="\t",row.names = 1)
samples = as.data.frame(sapply(strsplit(rownames(rnaCount), split= "\\/"), function(x) x[1]))
rnaCount1 = cbind(samples,rnaCount$V2,rnaCount$V3,rnaCount$V4,rnaCount$V5,rnaCount$V6)
colnames(rnaCount1) = c("Samples","Ribosomal","Coding","UTR","Intronic","Intergenic")
rnaCount_dat = melt(rnaCount1)
colnames(rnaCount_dat) = c("Samples","RNA_Species","Percentage")
g4 = ggplot(rnaCount_dat, aes(x=Samples,y=Percentage,fill=RNA_Species)) +
geom_bar(position = "fill",stat="identity") +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
ggtitle("RNA Quality and Species Information from Picard") +
scale_y_continuous(labels = percent_format())+
theme(axis.text.x = element_text(size = 20)) +
theme(axis.text.y = element_text(size = 20)) +
theme(plot.title = element_text(color = "orange",lineheight=.8, face="bold",hjust = 0.5))
plots = list(g1,g2,g3,g4)
pdf(paste0(outDir,Sys.Date(),"QC_report_RNASeq_Neil_Ihrke_Mayo_Human_PanNet_89_BC_samples",".pdf"),width=30,height=10)
lapply(plots, eval)
dev.off()
|
library(mcomp)
library(forecast)
library(pbapply)
data(M3)
res <- pbsapply(M3, function(x){
mod <- ets(x$x)
f <- forecast(mod, length(x$xx))
return(accuracy(f, x$xx)['Test set','MAPE'])
})
res <- sort(res)
pick <- c(head(res, 5), tail(res, 5))
round(pick, 2)
dev.off()
par(mfrow=c(5,2))
n <- names(pick)
for(i in 1:(length(n)/2)){
a <- n[[1]]
b <- n[[length(n)]]
plot(M3[[a]])
plot(M3[[b]])
n <- setdiff(n, c(a,b))
}
n <- 'N2602'
mod <- ets(M3[[n]]$x, restrict=FALSE)
#mod <- auto.arima(M3[[n]]$x, stepwise=FALSE, trace=TRUE)
#mod <- thetaf(M3[[n]]$x)
f <- forecast(mod, length(M3[[n]]$xx))
dev.off()
plot(f)
lines(M3[[n]]$xx, col='red')
| /data-science-scripts/zach/M3_comp_top_and_bottom.R | no_license | mcohenmcohen/DataRobot | R | false | false | 660 | r | library(mcomp)
library(forecast)
library(pbapply)
data(M3)
res <- pbsapply(M3, function(x){
mod <- ets(x$x)
f <- forecast(mod, length(x$xx))
return(accuracy(f, x$xx)['Test set','MAPE'])
})
res <- sort(res)
pick <- c(head(res, 5), tail(res, 5))
round(pick, 2)
dev.off()
par(mfrow=c(5,2))
n <- names(pick)
for(i in 1:(length(n)/2)){
a <- n[[1]]
b <- n[[length(n)]]
plot(M3[[a]])
plot(M3[[b]])
n <- setdiff(n, c(a,b))
}
n <- 'N2602'
mod <- ets(M3[[n]]$x, restrict=FALSE)
#mod <- auto.arima(M3[[n]]$x, stepwise=FALSE, trace=TRUE)
#mod <- thetaf(M3[[n]]$x)
f <- forecast(mod, length(M3[[n]]$xx))
dev.off()
plot(f)
lines(M3[[n]]$xx, col='red')
|
test = c("abc", "abcvasdf", "abc_rrrr")
gregexpr(pattern = "||abc&||rrrr", text = test)
# [[1]]
# [1] 1 2 3
# attr(,"match.length")
# [1] 0 0 0
# attr(,"useBytes")
# [1] TRUE
#
# [[2]]
# [1] 1 2 3 4 5 6 7 8
# attr(,"match.length")
# [1] 0 0 0 0 0 0 0 0
# attr(,"useBytes")
# [1] TRUE
#
# [[3]]
# [1] 1 2 3 4 5
# attr(,"match.length")
# [1] 0 0 0 0 4
# attr(,"useBytes")
# [1] TRUE
gregexpr(pattern = "abc.*rrrr", text = test)
# [[1]]
# [1] -1
# attr(,"match.length")
# [1] -1
# attr(,"useBytes")
# [1] TRUE
#
# [[2]]
# [1] -1
# attr(,"match.length")
# [1] -1
# attr(,"useBytes")
# [1] TRUE
#
# [[3]]
# [1] 1
# attr(,"match.length")
# [1] 8
# attr(,"useBytes")
# [1] TRUE
| /01_R/grammers/text_handling/Regular_Expression_06.R | no_license | heejour/encaion | R | false | false | 676 | r | test = c("abc", "abcvasdf", "abc_rrrr")
gregexpr(pattern = "||abc&||rrrr", text = test)
# [[1]]
# [1] 1 2 3
# attr(,"match.length")
# [1] 0 0 0
# attr(,"useBytes")
# [1] TRUE
#
# [[2]]
# [1] 1 2 3 4 5 6 7 8
# attr(,"match.length")
# [1] 0 0 0 0 0 0 0 0
# attr(,"useBytes")
# [1] TRUE
#
# [[3]]
# [1] 1 2 3 4 5
# attr(,"match.length")
# [1] 0 0 0 0 4
# attr(,"useBytes")
# [1] TRUE
gregexpr(pattern = "abc.*rrrr", text = test)
# [[1]]
# [1] -1
# attr(,"match.length")
# [1] -1
# attr(,"useBytes")
# [1] TRUE
#
# [[2]]
# [1] -1
# attr(,"match.length")
# [1] -1
# attr(,"useBytes")
# [1] TRUE
#
# [[3]]
# [1] 1
# attr(,"match.length")
# [1] 8
# attr(,"useBytes")
# [1] TRUE
|
## Code to prepare `WHO_SR` dataset goes here.
## Package users ignore this code.
# SOURCE https://www.who.int/emergencies/diseases/novel-coronavirus-2019/situation-reports
devtools::load_all()
WHO_SR <- read.csv("data-raw/WHO_SR.csv")
WHO_SR$Date <- as.Date(WHO_SR$Date)
usethis::use_data(WHO_SR, overwrite = TRUE)
# Once the data in the CSV is updated, run the above code, update the package
# version, followed by:
devtools::document()
devtools::build_vignettes()
devtools::check()
## Below creates alternately labelled object, for use by downstream outbreaks
library(tidyverse)
sarscov2_who_2019 <- WHO_SR
sarscov2_who_2019 <- rename(sarscov2_who_2019,
situation_report = SituationReport,
date = Date,
cases_chn = China,
cases_jpn = Japan,
cases_kor = RepublicofKorea,
cases_vnm = VietNam,
cases_sgp = Singapore,
cases_aus = Australia,
cases_mys = Malaysia,
cases_khm = Cambodia,
cases_nzl = NewZealand,
cases_phl = Philippines,
cases_tha = Thailand,
cases_npl = Nepal,
cases_lka = SriLanka,
cases_ind = India,
cases_idn = Indonesia,
cases_btn = Bhutan,
cases_usa = UnitedStatesofAmerica,
cases_can = Canada,
cases_bra = Brazil,
cases_mex = Mexico,
cases_ecu = Ecuador,
cases_dom = DominicanRepublic,
cases_maf = SaintMartin,
cases_blm = SaintBarthelemy,
cases_arg = Argentina,
cases_chl = Chile,
cases_col = Colombia,
cases_per = Peru,
cases_fin = Finland,
cases_hrv = Croatia,
cases_aut = Austria,
cases_dnk = Denmark,
cases_est = Estonia,
cases_geo = Georgia,
cases_grc = Greece,
cases_mkd = NorthMacedonia,
cases_nor = Norway,
cases_rou = Romania,
cases_che = Switzerland,
cases_blr = Belarus,
cases_ltu = Lithuania,
cases_nld = Netherlands,
cases_smr = SanMarino,
cases_aze = Azerbaijan,
cases_irl = Ireland,
cases_mco = Monaco,
cases_cze = Czechia,
cases_isl = Iceland,
cases_arm = Armenia,
cases_lux = Luxembourg,
cases_prt = Portugal,
cases_and = Andorra,
cases_lva = Latvia,
cases_pol = Poland,
cases_ukr = Ukraine,
cases_lie = Liechtenstein,
cases_bih = BosniaHerzegovina,
cases_hun = Hungary,
cases_svn = Slovenia,
cases_gib = Gibraltar,
cases_isr = Israel,
cases_fra = France,
cases_deu = Germany,
cases_ita = Italy,
cases_rus = RussianFederation,
cases_esp = Spain,
cases_swe = Sweden,
cases_gbr = UnitedKingdom,
cases_bel = Belgium,
cases_srb = Serbia,
cases_svk = Slovakia,
cases_vat = HolySee,
cases_are = UnitedArabEmirates,
cases_egy = Egypt,
cases_irn = Iran,
cases_lbn = Lebanon,
cases_kwt = Kuwait,
cases_afg = Afghanistan,
cases_bhr = Bahrain,
cases_irq = Iraq,
cases_omn = Oman,
cases_pak = Pakistan,
cases_qat = Qatar,
cases_jor = Jordan,
cases_mar = Morocco,
cases_sau = SaudiArabia,
cases_tun = Tunisia,
cases_pse = OccupiedPalestinianTerritory,
cases_dza = Algeria,
cases_nga = Nigeria,
cases_sen = Senegal,
cases_cmr = Cameroon,
cases_zaf = SouthAfrica,
cases_tgo = Togo,
cases_internationconveyance = InternationalConveyance,
cases_global = Global.confirmed,
suspected_chn = China.suspected,
severe_chn = China.severe,
deaths_chn = China.deaths,
deaths_phl = Philippines.deaths,
deaths_jpn = Japan.deaths,
deaths_fra = France.deaths,
deaths_kor = RepublicofKorea.deaths,
deaths_irn = Iran.deaths,
deaths_ita = Italy.deaths,
deaths_aus = Australia.deaths,
deaths_tha = Thailand.deaths,
deaths_usa = UnitedStatesofAmerica.deaths,
deaths_irq = Iraq.deaths,
deaths_esp = Spain.deaths,
deaths_che = Switzerland.deaths,
deaths_gbr = UnitedKingdom.deaths,
deaths_nld = Netherlands.deaths,
deaths_internationalconveyance = InternationalConveyance.deaths,
critical_chn = China.critical,
clinical_chn_hubei = Hubei.clinicaldx,
cases_outside_chn = Cases.nonChina,
countries_outside_chn = Countries.nonChina,
deaths_outside_chn = Deaths.nonChina,
cases_outside_chn_wuhan_travel_history = Cases.nonChina.WuhanTravel,
cases_outside_chn_chn_travel_history = Cases.nonChina.ChinaTravel,
risk_chn = RA.China,
risk_regional = RA.Regional,
risk_global = RA.Global,
cases_health_care_workers = HealthCareWorkers,
cases_chn_wuhan = China.WuhanCity,
cases_chn_hubei = China.Hubei,
cases_chn_guangdong = China.Guangdong,
cases_chn_beijing = China.Beijing,
cases_chn_shanghai = China.Shanghai,
cases_chn_chongqing = China.Chongqing,
cases_chn_zhejiang = China.Zhejiang,
cases_chn_jiangxi = China.Jiangxi,
cases_chn_sichuan = China.Sichuan,
cases_chn_tianjin = China.Tianjin,
cases_chn_henan = China.Henan,
cases_chn_hunan = China.Hunan,
cases_chn_shandong = China.Shandong,
cases_chn_yunnan = China.Yunnan,
cases_chn_taiwan = China.Taiwan,
cases_chn_taipei = China.Taipei,
cases_chn_hkg = China.HongKongSAR,
cases_chn_mac = China.Macao,
cases_chn_unspecified = China.Unspecified,
cases_chn_anhui = China.Anhui,
cases_chn_jiangsu = China.Jiangsu,
cases_chn_fujian = China.Fujian,
cases_chn_shaanxi = China.Shaanxi,
cases_chn_guangxi = China.Guangxi,
cases_chn_hebei = China.Hebei,
cases_chn_heilongjiang = China.Heilongjiang,
cases_chn_liaoning = China.Liaoning,
cases_chn_hainan = China.Hainan,
cases_chn_shanxi = China.Shanxi,
cases_chn_gansu = China.Gansu,
cases_chn_guizhou = China.Guizhou,
cases_chn_ningxia = China.Ningxia,
cases_chn_mng = China.InnerMongolia,
cases_chn_xinjiang = China.Xinjiang,
cases_chn_jilin = China.Jilin,
cases_chn_qinghai = China.Qinghai,
cases_chn_xizang = China.Xizang,
deaths_chn_hubei = China.Hubei.deaths,
deaths_chn_guangdong = China.Guangdong.deaths,
deaths_chn_beijing = China.Beijing.deaths,
deaths_chn_shanghai = China.Shanghai.deaths,
deaths_chn_chongqing = China.Chongqing.deaths,
deaths_chn_zhejiang = China.Zhejiang.deaths,
deaths_chn_jiangxi = China.Jiangxi.deaths,
deaths_chn_sichuan = China.Sichuan.deaths,
deaths_chn_tianjin = China.Tianjin.deaths,
deaths_chn_henan = China.Henan.deaths,
deaths_chn_hunan = China.Hunan.deaths,
deaths_chn_shandong = China.Shandong.deaths,
deaths_chn_yunnan = China.Yunnan.deaths,
deaths_chn_taipei = China.Taipei.deaths,
deaths_chn_hkg = China.HongKongSAR.deaths,
deaths_chn_mac = China.Macao.deaths,
deaths_chn_anhui = China.Anhui.deaths,
deaths_chn_jiangsu = China.Jiangsu.deaths,
deaths_chn_fujian = China.Fujian.deaths,
deaths_chn_shaanxi = China.Shaanxi.deaths,
deaths_chn_guangxi = China.Guangxi.deaths,
deaths_chn_hebei = China.Hebei.deaths,
deaths_chn_heilongjiang = China.Heilongjiang.deaths,
deaths_chn_liaoning = China.Liaoning.deaths,
deaths_chn_hainan = China.Hainan.deaths,
deaths_chn_shanxi = China.Shanxi.deaths,
deaths_chn_gansu = China.Gansu.deaths,
deaths_chn_guizhou = China.Guizhou.deaths,
deaths_chn_ningxia = China.Ningxia.deaths,
deaths_chn_mng = China.InnerMongolia.deaths,
deaths_chn_xinjiang = China.Xinjiang.deaths,
deaths_chn_jilin = China.Jilin.deaths,
deaths_chn_qinghai = China.Qinghai.deaths,
deaths_chn_xizang = China.Xizang.deaths
)
save(sarscov2_who_2019, file = "sarscov2_who_2019.RData", version = 2)
usethis::use_data(sarscov2_who_2019, overwrite = TRUE)
devtools::document()
devtools::check()
| /data-raw/WHO_SR.R | no_license | achalpashine/data2019nCoV | R | false | false | 7,650 | r | ## Code to prepare `WHO_SR` dataset goes here.
## Package users ignore this code.
# SOURCE https://www.who.int/emergencies/diseases/novel-coronavirus-2019/situation-reports
devtools::load_all()
WHO_SR <- read.csv("data-raw/WHO_SR.csv")
WHO_SR$Date <- as.Date(WHO_SR$Date)
usethis::use_data(WHO_SR, overwrite = TRUE)
# Once the data in the CSV is updated, run the above code, update the package
# version, followed by:
devtools::document()
devtools::build_vignettes()
devtools::check()
## Below creates alternately labelled object, for use by downstream outbreaks
library(tidyverse)
sarscov2_who_2019 <- WHO_SR
sarscov2_who_2019 <- rename(sarscov2_who_2019,
situation_report = SituationReport,
date = Date,
cases_chn = China,
cases_jpn = Japan,
cases_kor = RepublicofKorea,
cases_vnm = VietNam,
cases_sgp = Singapore,
cases_aus = Australia,
cases_mys = Malaysia,
cases_khm = Cambodia,
cases_nzl = NewZealand,
cases_phl = Philippines,
cases_tha = Thailand,
cases_npl = Nepal,
cases_lka = SriLanka,
cases_ind = India,
cases_idn = Indonesia,
cases_btn = Bhutan,
cases_usa = UnitedStatesofAmerica,
cases_can = Canada,
cases_bra = Brazil,
cases_mex = Mexico,
cases_ecu = Ecuador,
cases_dom = DominicanRepublic,
cases_maf = SaintMartin,
cases_blm = SaintBarthelemy,
cases_arg = Argentina,
cases_chl = Chile,
cases_col = Colombia,
cases_per = Peru,
cases_fin = Finland,
cases_hrv = Croatia,
cases_aut = Austria,
cases_dnk = Denmark,
cases_est = Estonia,
cases_geo = Georgia,
cases_grc = Greece,
cases_mkd = NorthMacedonia,
cases_nor = Norway,
cases_rou = Romania,
cases_che = Switzerland,
cases_blr = Belarus,
cases_ltu = Lithuania,
cases_nld = Netherlands,
cases_smr = SanMarino,
cases_aze = Azerbaijan,
cases_irl = Ireland,
cases_mco = Monaco,
cases_cze = Czechia,
cases_isl = Iceland,
cases_arm = Armenia,
cases_lux = Luxembourg,
cases_prt = Portugal,
cases_and = Andorra,
cases_lva = Latvia,
cases_pol = Poland,
cases_ukr = Ukraine,
cases_lie = Liechtenstein,
cases_bih = BosniaHerzegovina,
cases_hun = Hungary,
cases_svn = Slovenia,
cases_gib = Gibraltar,
cases_isr = Israel,
cases_fra = France,
cases_deu = Germany,
cases_ita = Italy,
cases_rus = RussianFederation,
cases_esp = Spain,
cases_swe = Sweden,
cases_gbr = UnitedKingdom,
cases_bel = Belgium,
cases_srb = Serbia,
cases_svk = Slovakia,
cases_vat = HolySee,
cases_are = UnitedArabEmirates,
cases_egy = Egypt,
cases_irn = Iran,
cases_lbn = Lebanon,
cases_kwt = Kuwait,
cases_afg = Afghanistan,
cases_bhr = Bahrain,
cases_irq = Iraq,
cases_omn = Oman,
cases_pak = Pakistan,
cases_qat = Qatar,
cases_jor = Jordan,
cases_mar = Morocco,
cases_sau = SaudiArabia,
cases_tun = Tunisia,
cases_pse = OccupiedPalestinianTerritory,
cases_dza = Algeria,
cases_nga = Nigeria,
cases_sen = Senegal,
cases_cmr = Cameroon,
cases_zaf = SouthAfrica,
cases_tgo = Togo,
cases_internationconveyance = InternationalConveyance,
cases_global = Global.confirmed,
suspected_chn = China.suspected,
severe_chn = China.severe,
deaths_chn = China.deaths,
deaths_phl = Philippines.deaths,
deaths_jpn = Japan.deaths,
deaths_fra = France.deaths,
deaths_kor = RepublicofKorea.deaths,
deaths_irn = Iran.deaths,
deaths_ita = Italy.deaths,
deaths_aus = Australia.deaths,
deaths_tha = Thailand.deaths,
deaths_usa = UnitedStatesofAmerica.deaths,
deaths_irq = Iraq.deaths,
deaths_esp = Spain.deaths,
deaths_che = Switzerland.deaths,
deaths_gbr = UnitedKingdom.deaths,
deaths_nld = Netherlands.deaths,
deaths_internationalconveyance = InternationalConveyance.deaths,
critical_chn = China.critical,
clinical_chn_hubei = Hubei.clinicaldx,
cases_outside_chn = Cases.nonChina,
countries_outside_chn = Countries.nonChina,
deaths_outside_chn = Deaths.nonChina,
cases_outside_chn_wuhan_travel_history = Cases.nonChina.WuhanTravel,
cases_outside_chn_chn_travel_history = Cases.nonChina.ChinaTravel,
risk_chn = RA.China,
risk_regional = RA.Regional,
risk_global = RA.Global,
cases_health_care_workers = HealthCareWorkers,
cases_chn_wuhan = China.WuhanCity,
cases_chn_hubei = China.Hubei,
cases_chn_guangdong = China.Guangdong,
cases_chn_beijing = China.Beijing,
cases_chn_shanghai = China.Shanghai,
cases_chn_chongqing = China.Chongqing,
cases_chn_zhejiang = China.Zhejiang,
cases_chn_jiangxi = China.Jiangxi,
cases_chn_sichuan = China.Sichuan,
cases_chn_tianjin = China.Tianjin,
cases_chn_henan = China.Henan,
cases_chn_hunan = China.Hunan,
cases_chn_shandong = China.Shandong,
cases_chn_yunnan = China.Yunnan,
cases_chn_taiwan = China.Taiwan,
cases_chn_taipei = China.Taipei,
cases_chn_hkg = China.HongKongSAR,
cases_chn_mac = China.Macao,
cases_chn_unspecified = China.Unspecified,
cases_chn_anhui = China.Anhui,
cases_chn_jiangsu = China.Jiangsu,
cases_chn_fujian = China.Fujian,
cases_chn_shaanxi = China.Shaanxi,
cases_chn_guangxi = China.Guangxi,
cases_chn_hebei = China.Hebei,
cases_chn_heilongjiang = China.Heilongjiang,
cases_chn_liaoning = China.Liaoning,
cases_chn_hainan = China.Hainan,
cases_chn_shanxi = China.Shanxi,
cases_chn_gansu = China.Gansu,
cases_chn_guizhou = China.Guizhou,
cases_chn_ningxia = China.Ningxia,
cases_chn_mng = China.InnerMongolia,
cases_chn_xinjiang = China.Xinjiang,
cases_chn_jilin = China.Jilin,
cases_chn_qinghai = China.Qinghai,
cases_chn_xizang = China.Xizang,
deaths_chn_hubei = China.Hubei.deaths,
deaths_chn_guangdong = China.Guangdong.deaths,
deaths_chn_beijing = China.Beijing.deaths,
deaths_chn_shanghai = China.Shanghai.deaths,
deaths_chn_chongqing = China.Chongqing.deaths,
deaths_chn_zhejiang = China.Zhejiang.deaths,
deaths_chn_jiangxi = China.Jiangxi.deaths,
deaths_chn_sichuan = China.Sichuan.deaths,
deaths_chn_tianjin = China.Tianjin.deaths,
deaths_chn_henan = China.Henan.deaths,
deaths_chn_hunan = China.Hunan.deaths,
deaths_chn_shandong = China.Shandong.deaths,
deaths_chn_yunnan = China.Yunnan.deaths,
deaths_chn_taipei = China.Taipei.deaths,
deaths_chn_hkg = China.HongKongSAR.deaths,
deaths_chn_mac = China.Macao.deaths,
deaths_chn_anhui = China.Anhui.deaths,
deaths_chn_jiangsu = China.Jiangsu.deaths,
deaths_chn_fujian = China.Fujian.deaths,
deaths_chn_shaanxi = China.Shaanxi.deaths,
deaths_chn_guangxi = China.Guangxi.deaths,
deaths_chn_hebei = China.Hebei.deaths,
deaths_chn_heilongjiang = China.Heilongjiang.deaths,
deaths_chn_liaoning = China.Liaoning.deaths,
deaths_chn_hainan = China.Hainan.deaths,
deaths_chn_shanxi = China.Shanxi.deaths,
deaths_chn_gansu = China.Gansu.deaths,
deaths_chn_guizhou = China.Guizhou.deaths,
deaths_chn_ningxia = China.Ningxia.deaths,
deaths_chn_mng = China.InnerMongolia.deaths,
deaths_chn_xinjiang = China.Xinjiang.deaths,
deaths_chn_jilin = China.Jilin.deaths,
deaths_chn_qinghai = China.Qinghai.deaths,
deaths_chn_xizang = China.Xizang.deaths
)
save(sarscov2_who_2019, file = "sarscov2_who_2019.RData", version = 2)
usethis::use_data(sarscov2_who_2019, overwrite = TRUE)
devtools::document()
devtools::check()
|
#' Group continuous data values (x-axis)
#'
#' The "bin" property is for grouping quantitative, continuous data values of a
#' particular field into smaller number of “bins” (e.g., for a histogram).
#'
#' @param vl Vega-Lite object
#' @param min the minimum bin value to consider.
#' @param max the maximum bin value to consider.
#' @param base the number base to use for automatic bin determination.
#' @param step an exact step size to use between bins.
#' @param steps an array of allowable step sizes to choose from.
#' @param minstep minimum allowable step size (particularly useful for integer values).
#' @param div Scale factors indicating allowable subdivisions. The default value is
#' [5, 2], which indicates that for base 10 numbers (the default base),
#' the method may consider dividing bin sizes by 5 and/or 2. For example,
#' for an initial step size of 10, the method can check if bin sizes of 2
#' (= 10/5), 5 (= 10/2), or 1 (= 10/(5*2)) might also satisfy the given
#' constraints.
#' @param maxbins the maximum number of allowable bins.
#' @encoding UTF-8
#' @references \href{http://vega.github.io/vega-lite/docs/bin.html}{Vega-Lite Binning}
#' @export
#' @examples
#' vegalite() %>%
#' add_data("https://vega.github.io/vega-editor/app/data/movies.json") %>%
#' encode_x("IMDB_Rating", "quantitative") %>%
#' encode_y("Rotten_Tomatoes_Rating", "quantitative") %>%
#' encode_size("*", "quantitative", aggregate="count") %>%
#' bin_x(maxbins=10) %>%
#' bin_y(maxbins=10) %>%
#' mark_point()
bin_x <- function(vl, min=NULL, max=NULL, base=NULL, step=NULL,
steps=NULL, minstep=NULL, div=NULL, maxbins=NULL) {
chnl <- "x"
if (!is.null(min)) vl$x$encoding[[chnl]]$bin$min <- min
if (!is.null(max)) vl$x$encoding[[chnl]]$bin$max <- max
if (!is.null(base)) vl$x$encoding[[chnl]]$bin$base <- base
if (!is.null(step)) vl$x$encoding[[chnl]]$bin$grid <- step
if (!is.null(steps)) vl$x$encoding[[chnl]]$bin$labels <- steps
if (!is.null(minstep)) vl$x$encoding[[chnl]]$bin$minstep <- minstep
if (!is.null(div)) vl$x$encoding[[chnl]]$bin$div <- div
if (!is.null(maxbins)) vl$x$encoding[[chnl]]$bin$maxbins <- maxbins
if (length( vl$x$encoding[[chnl]]$bin) == 0) vl$x$encoding$x$bin <- TRUE
vl
}
#' Group continuous data values (y-axis)
#'
#' The "bin" property is for grouping quantitative, continuous data values of a
#' particular field into smaller number of “bins” (e.g., for a histogram).
#'
#' @param vl Vega-Lite object
#' @param min the minimum bin value to consider.
#' @param max the maximum bin value to consider.
#' @param base the number base to use for automatic bin determination.
#' @param step an exact step size to use between bins.
#' @param steps an array of allowable step sizes to choose from.
#' @param minstep minimum allowable step size (particularly useful for integer values).
#' @param div Scale factors indicating allowable subdivisions. The default value is
#' [5, 2], which indicates that for base 10 numbers (the default base),
#' the method may consider dividing bin sizes by 5 and/or 2. For example,
#' for an initial step size of 10, the method can check if bin sizes of 2
#' (= 10/5), 5 (= 10/2), or 1 (= 10/(5*2)) might also satisfy the given
#' constraints.
#' @param maxbins the maximum number of allowable bins.
#' @encoding UTF-8
#' @references \href{http://vega.github.io/vega-lite/docs/bin.html}{Vega-Lite Binning}
#' @export
#' @examples
#' vegalite() %>%
#' add_data("https://vega.github.io/vega-editor/app/data/movies.json") %>%
#' encode_x("IMDB_Rating", "quantitative") %>%
#' encode_y("Rotten_Tomatoes_Rating", "quantitative") %>%
#' encode_size("*", "quantitative", aggregate="count") %>%
#' bin_x(maxbins=10) %>%
#' bin_y(maxbins=10) %>%
#' mark_point()
bin_y <- function(vl, min=NULL, max=NULL, base=NULL, step=NULL,
steps=NULL, minstep=NULL, div=NULL, maxbins=NULL) {
chnl <- "y"
if (!is.null(min)) vl$x$encoding[[chnl]]$bin$min <- min
if (!is.null(max)) vl$x$encoding[[chnl]]$bin$max <- max
if (!is.null(base)) vl$x$encoding[[chnl]]$bin$base <- base
if (!is.null(step)) vl$x$encoding[[chnl]]$bin$grid <- step
if (!is.null(steps)) vl$x$encoding[[chnl]]$bin$labels <- steps
if (!is.null(minstep)) vl$x$encoding[[chnl]]$bin$minstep <- minstep
if (!is.null(div)) vl$x$encoding[[chnl]]$bin$div <- div
if (!is.null(maxbins)) vl$x$encoding[[chnl]]$bin$maxbins <- maxbins
if (length( vl$x$encoding[[chnl]]$bin) == 0) vl$x$encoding$y$bin <- TRUE
vl
}
| /R/bin.r | no_license | cran/vegalite | R | false | false | 4,641 | r | #' Group continuous data values (x-axis)
#'
#' The "bin" property is for grouping quantitative, continuous data values of a
#' particular field into smaller number of “bins” (e.g., for a histogram).
#'
#' @param vl Vega-Lite object
#' @param min the minimum bin value to consider.
#' @param max the maximum bin value to consider.
#' @param base the number base to use for automatic bin determination.
#' @param step an exact step size to use between bins.
#' @param steps an array of allowable step sizes to choose from.
#' @param minstep minimum allowable step size (particularly useful for integer values).
#' @param div Scale factors indicating allowable subdivisions. The default value is
#' [5, 2], which indicates that for base 10 numbers (the default base),
#' the method may consider dividing bin sizes by 5 and/or 2. For example,
#' for an initial step size of 10, the method can check if bin sizes of 2
#' (= 10/5), 5 (= 10/2), or 1 (= 10/(5*2)) might also satisfy the given
#' constraints.
#' @param maxbins the maximum number of allowable bins.
#' @encoding UTF-8
#' @references \href{http://vega.github.io/vega-lite/docs/bin.html}{Vega-Lite Binning}
#' @export
#' @examples
#' vegalite() %>%
#' add_data("https://vega.github.io/vega-editor/app/data/movies.json") %>%
#' encode_x("IMDB_Rating", "quantitative") %>%
#' encode_y("Rotten_Tomatoes_Rating", "quantitative") %>%
#' encode_size("*", "quantitative", aggregate="count") %>%
#' bin_x(maxbins=10) %>%
#' bin_y(maxbins=10) %>%
#' mark_point()
bin_x <- function(vl, min=NULL, max=NULL, base=NULL, step=NULL,
steps=NULL, minstep=NULL, div=NULL, maxbins=NULL) {
chnl <- "x"
if (!is.null(min)) vl$x$encoding[[chnl]]$bin$min <- min
if (!is.null(max)) vl$x$encoding[[chnl]]$bin$max <- max
if (!is.null(base)) vl$x$encoding[[chnl]]$bin$base <- base
if (!is.null(step)) vl$x$encoding[[chnl]]$bin$grid <- step
if (!is.null(steps)) vl$x$encoding[[chnl]]$bin$labels <- steps
if (!is.null(minstep)) vl$x$encoding[[chnl]]$bin$minstep <- minstep
if (!is.null(div)) vl$x$encoding[[chnl]]$bin$div <- div
if (!is.null(maxbins)) vl$x$encoding[[chnl]]$bin$maxbins <- maxbins
if (length( vl$x$encoding[[chnl]]$bin) == 0) vl$x$encoding$x$bin <- TRUE
vl
}
#' Group continuous data values (y-axis)
#'
#' The "bin" property is for grouping quantitative, continuous data values of a
#' particular field into smaller number of “bins” (e.g., for a histogram).
#'
#' @param vl Vega-Lite object
#' @param min the minimum bin value to consider.
#' @param max the maximum bin value to consider.
#' @param base the number base to use for automatic bin determination.
#' @param step an exact step size to use between bins.
#' @param steps an array of allowable step sizes to choose from.
#' @param minstep minimum allowable step size (particularly useful for integer values).
#' @param div Scale factors indicating allowable subdivisions. The default value is
#' [5, 2], which indicates that for base 10 numbers (the default base),
#' the method may consider dividing bin sizes by 5 and/or 2. For example,
#' for an initial step size of 10, the method can check if bin sizes of 2
#' (= 10/5), 5 (= 10/2), or 1 (= 10/(5*2)) might also satisfy the given
#' constraints.
#' @param maxbins the maximum number of allowable bins.
#' @encoding UTF-8
#' @references \href{http://vega.github.io/vega-lite/docs/bin.html}{Vega-Lite Binning}
#' @export
#' @examples
#' vegalite() %>%
#' add_data("https://vega.github.io/vega-editor/app/data/movies.json") %>%
#' encode_x("IMDB_Rating", "quantitative") %>%
#' encode_y("Rotten_Tomatoes_Rating", "quantitative") %>%
#' encode_size("*", "quantitative", aggregate="count") %>%
#' bin_x(maxbins=10) %>%
#' bin_y(maxbins=10) %>%
#' mark_point()
bin_y <- function(vl, min=NULL, max=NULL, base=NULL, step=NULL,
steps=NULL, minstep=NULL, div=NULL, maxbins=NULL) {
chnl <- "y"
if (!is.null(min)) vl$x$encoding[[chnl]]$bin$min <- min
if (!is.null(max)) vl$x$encoding[[chnl]]$bin$max <- max
if (!is.null(base)) vl$x$encoding[[chnl]]$bin$base <- base
if (!is.null(step)) vl$x$encoding[[chnl]]$bin$grid <- step
if (!is.null(steps)) vl$x$encoding[[chnl]]$bin$labels <- steps
if (!is.null(minstep)) vl$x$encoding[[chnl]]$bin$minstep <- minstep
if (!is.null(div)) vl$x$encoding[[chnl]]$bin$div <- div
if (!is.null(maxbins)) vl$x$encoding[[chnl]]$bin$maxbins <- maxbins
if (length( vl$x$encoding[[chnl]]$bin) == 0) vl$x$encoding$y$bin <- TRUE
vl
}
|
library(lavaan)
setwd("/Volumes/SP PHD U3/missing-data-project-2")
source("functions.R")
source("Models_WM.R") #done
### FOR TWO MISSING VARIABLES
#purpose: create missing data on x11, x12.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMinPattern_2Var <- function(model, sample.nobs, missing.percentage=0.5){
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,7:8] <- NA
simuData
}
#Usage: only for this research. Two variables has missing data; maximum number of missing patterns for two variables: x11 and x12
# Each variable with missing data has the given percentage of missing data.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMaxPattern_2Var <- function(model, sample.nobs, missing.percentage=.5){
missing.percentage <- missing.percentage
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
for(i in 7:8){
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,i] <- NA
}
simuData
}
#Usage: only for this research. Two variables has missing data; maximum number of missing patterns for two variables: x11 and x12
# Each variable with missing data has the given percentage of missing data.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMaxPattern_2Var <- function(model, sample.nobs, missing.percentage=.5){
missing.percentage <- missing.percentage
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
for(i in 7:8){
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,i] <- NA
}
simuData
}
##FOR FOUR MISSING VARIABLES
#purpose: create missing data on x9 to x12.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMinPattern_4Var <- function(model, sample.nobs, missing.percentage){
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,7:10] <- NA
simuData
}
#Usage: only for this research. Four variables has missing data; max number of missing patterns for four variables: x9, x10, x11 and x12
# Each variable with missing data has the given percentage of missing data.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMaxPattern_4Var <- function(model, sample.nobs, missing.percentage=.5){
missing.percentage <- missing.percentage
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
for(i in 7:10){
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,i] <- NA
}
simuData
}
##FOR SIX MISSING VARIABLES
#purpose: create missing data on x7 to x12.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMinPattern_6Var <- function(model, sample.nobs, missing.percentage){
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,7:12] <- NA
simuData
}
#Usage: only for this research. Six variables has missing data; max number of missing patterns for six variables: x9, x10, x11 and x12
# Each variable with missing data has the given percentage of missing data.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMaxPattern_6Var <- function(model, sample.nobs, missing.percentage=.5){
missing.percentage <- missing.percentage
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
for(i in 7:12){
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,i] <- NA
}
simuData
}
#Arguments:
#pop.model.list: a list of lavaan models for the population
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
##var.with.missing: the number of variables with missing data; it can be 2, 4 OR 6
##simu.num: number of simulation rounds
############
fit.components.simu <- function(pop.model.list, fitted.mod, sample.nobs ,
missing.percentage, missing.type, var.with.missing,
simu.num = 1){
fit.components.list <- vector(mode="list", length=simu.num)
for(j in 1:simu.num){
fit.components <-matrix( nrow = 30, ncol = 0)
for(i in 1:length(pop.model.list)){
if (var.with.missing == 2){
if(missing.type =="min"){
simuData <- MCARMinPattern_2Var(pop.model.list[[i]], sample.nobs, missing.percentage)
} else {
simuData <- MCARMaxPattern_2Var(pop.model.list[[i]], sample.nobs, missing.percentage)
}
} else if(var.with.missing == 4) {
if(missing.type =="min"){
simuData <- MCARMinPattern_4Var(pop.model.list[[i]], sample.nobs, missing.percentage)
} else {
simuData <- MCARMaxPattern_4Var(pop.model.list[[i]], sample.nobs, missing.percentage)
}
} else {
if(missing.type =="min"){
simuData <- MCARMinPattern_6Var(pop.model.list[[i]], sample.nobs, missing.percentage)
} else {
simuData <- MCARMaxPattern_6Var(pop.model.list[[i]], sample.nobs, missing.percentage)
}
}
fit.ind.vector <- ts.components(fitted.mod, dataset=simuData)
fit.components<- cbind(fit.components,fit.ind.vector)
}
colnames(fit.components) <-paste("FC =",c("1","0.9", "0.8" , "0.7", "0.6", "0.5", "0.4", "0.3","0.2"))
fit.components <- round(fit.components, 8)
fit.components.list[[j]] <- fit.components
print(j)
}
fit.components.list
}
set.seed(111)
setwd("/Volumes/SP PHD U3/missing-data-project-2/Simu results TS")
##### zero percent missing
fitMCAR_0PerMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0, missing.type = "min",
var.with.missing = 2)
fitMCAR_0PerMiss_WM_ts_n1000000<-ts.fit(fitMCAR_0PerMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_0PerMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_0PerMiss_WM_ts_n1000000.RData")
fitMCAR_0PerMiss_WM_ts_checks_n1000000<-ts.checks(fitMCAR_0PerMiss_WM_ts_compo_n1000000,
fitMCAR_0PerMiss_WM_ts_n1000000)
save(fitMCAR_0PerMiss_WM_ts_compo_n1000000, file="fitMCAR_0PerMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_0PerMiss_WM_ts_n1000000, file="fitMCAR_0PerMiss_WM_ts_n1000000.RData")
save(fitMCAR_0PerMiss_WM_ts_checks_n1000000, file="fitMCAR_0PerMiss_WM_ts_checks_n1000000.RData")
#### min pattern##
##### 2 variables with missing data #######################
fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "min",
var.with.missing = 2)
fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000)
#load(file="fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
#load(file="fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_n1000000.RData")
fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000.RData")
fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "min",
var.with.missing = 2)
fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_n1000000.RData")
fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000.RData")
##### 4 variables with missing data #######################
fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "min",
var.with.missing = 4)
fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_n1000000.RData")
#load( file="fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000.RData")
fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "min",
var.with.missing = 4)
fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
#load(file="fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_n1000000.RData")
fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000.RData")
##### 6 variables with missing data #######################
fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "min",
var.with.missing = 6)
fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_n1000000.RData")
fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000.RData")
fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "min",
var.with.missing = 6)
fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000)
#load(file="fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
#load(file="fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_n1000000.RData")
fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000.RData")
####Max PATTERNS!!! #####
##### 2 variables with missing data #######################
fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "max",
var.with.missing = 2)
fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000)
#load(file="fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
#load(file="fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000,
fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_n1000000)
save(fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000.RData")
fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "max",
var.with.missing = 2)
fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000,fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_n1000000 )
save(fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000.RData")
##### 4 variables with missing data #######################
fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "max",
var.with.missing = 4)
fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000,
fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_n1000000)
save(fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000.RData")
set.seed(100)
fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "max",
var.with.missing = 4)
fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000)
#load(file="fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000,
fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_n1000000)
save(fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000.RData")
##### 6 variables with missing data #######################
fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "max",
var.with.missing = 6)
fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000,
fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_n1000000)
save(fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000.RData")
fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000 <-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "max",
var.with.missing = 6)
fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000)
#load(file="fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
#load(file="fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000,
fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000)
save(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000.RData")
list.mean(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000)
fitNoMissing_WM_new
| /generateMCAR_study2_p2_ts.R | no_license | cathyxijuan/missing-data-project-2 | R | false | false | 23,328 | r | library(lavaan)
setwd("/Volumes/SP PHD U3/missing-data-project-2")
source("functions.R")
source("Models_WM.R") #done
### FOR TWO MISSING VARIABLES
#purpose: create missing data on x11, x12.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMinPattern_2Var <- function(model, sample.nobs, missing.percentage=0.5){
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,7:8] <- NA
simuData
}
#Usage: only for this research. Two variables has missing data; maximum number of missing patterns for two variables: x11 and x12
# Each variable with missing data has the given percentage of missing data.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMaxPattern_2Var <- function(model, sample.nobs, missing.percentage=.5){
missing.percentage <- missing.percentage
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
for(i in 7:8){
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,i] <- NA
}
simuData
}
#Usage: only for this research. Two variables has missing data; maximum number of missing patterns for two variables: x11 and x12
# Each variable with missing data has the given percentage of missing data.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMaxPattern_2Var <- function(model, sample.nobs, missing.percentage=.5){
missing.percentage <- missing.percentage
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
for(i in 7:8){
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,i] <- NA
}
simuData
}
##FOR FOUR MISSING VARIABLES
#purpose: create missing data on x9 to x12.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMinPattern_4Var <- function(model, sample.nobs, missing.percentage){
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,7:10] <- NA
simuData
}
#Usage: only for this research. Four variables has missing data; max number of missing patterns for four variables: x9, x10, x11 and x12
# Each variable with missing data has the given percentage of missing data.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMaxPattern_4Var <- function(model, sample.nobs, missing.percentage=.5){
missing.percentage <- missing.percentage
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
for(i in 7:10){
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,i] <- NA
}
simuData
}
##FOR SIX MISSING VARIABLES
#purpose: create missing data on x7 to x12.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMinPattern_6Var <- function(model, sample.nobs, missing.percentage){
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,7:12] <- NA
simuData
}
#Usage: only for this research. Six variables has missing data; max number of missing patterns for six variables: x9, x10, x11 and x12
# Each variable with missing data has the given percentage of missing data.
#Argument:
#model: lavaan defined population model
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
#missing.percentage: vector specifying which columns are missing
MCARMaxPattern_6Var <- function(model, sample.nobs, missing.percentage=.5){
missing.percentage <- missing.percentage
data <- simulateData(model, sample.nobs=sample.nobs,seed=111)
simuData <- data.frame(x1=data[,"x1"], x2=data[,"x2"], x3=data[,"x3"], x4=data[,"x4"],
x5=data[,"x5"], x6=data[,"x6"], x7=data[,"x7"], x8=data[,"x8"],
x9=data[,"x9"], x10=data[,"x10"], x11=data[,"x11"], x12=data[,"x12"])
for(i in 7:12){
ind <- as.logical(rbinom(sample.nobs, 1, missing.percentage))
simuData[ind,i] <- NA
}
simuData
}
#Arguments:
#pop.model.list: a list of lavaan models for the population
#sample.nobs: numeric; sample size without missing data
#missing.percentage: numeric; a proportion of missing data
##var.with.missing: the number of variables with missing data; it can be 2, 4 OR 6
##simu.num: number of simulation rounds
############
fit.components.simu <- function(pop.model.list, fitted.mod, sample.nobs ,
missing.percentage, missing.type, var.with.missing,
simu.num = 1){
fit.components.list <- vector(mode="list", length=simu.num)
for(j in 1:simu.num){
fit.components <-matrix( nrow = 30, ncol = 0)
for(i in 1:length(pop.model.list)){
if (var.with.missing == 2){
if(missing.type =="min"){
simuData <- MCARMinPattern_2Var(pop.model.list[[i]], sample.nobs, missing.percentage)
} else {
simuData <- MCARMaxPattern_2Var(pop.model.list[[i]], sample.nobs, missing.percentage)
}
} else if(var.with.missing == 4) {
if(missing.type =="min"){
simuData <- MCARMinPattern_4Var(pop.model.list[[i]], sample.nobs, missing.percentage)
} else {
simuData <- MCARMaxPattern_4Var(pop.model.list[[i]], sample.nobs, missing.percentage)
}
} else {
if(missing.type =="min"){
simuData <- MCARMinPattern_6Var(pop.model.list[[i]], sample.nobs, missing.percentage)
} else {
simuData <- MCARMaxPattern_6Var(pop.model.list[[i]], sample.nobs, missing.percentage)
}
}
fit.ind.vector <- ts.components(fitted.mod, dataset=simuData)
fit.components<- cbind(fit.components,fit.ind.vector)
}
colnames(fit.components) <-paste("FC =",c("1","0.9", "0.8" , "0.7", "0.6", "0.5", "0.4", "0.3","0.2"))
fit.components <- round(fit.components, 8)
fit.components.list[[j]] <- fit.components
print(j)
}
fit.components.list
}
set.seed(111)
setwd("/Volumes/SP PHD U3/missing-data-project-2/Simu results TS")
##### zero percent missing
fitMCAR_0PerMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0, missing.type = "min",
var.with.missing = 2)
fitMCAR_0PerMiss_WM_ts_n1000000<-ts.fit(fitMCAR_0PerMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_0PerMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_0PerMiss_WM_ts_n1000000.RData")
fitMCAR_0PerMiss_WM_ts_checks_n1000000<-ts.checks(fitMCAR_0PerMiss_WM_ts_compo_n1000000,
fitMCAR_0PerMiss_WM_ts_n1000000)
save(fitMCAR_0PerMiss_WM_ts_compo_n1000000, file="fitMCAR_0PerMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_0PerMiss_WM_ts_n1000000, file="fitMCAR_0PerMiss_WM_ts_n1000000.RData")
save(fitMCAR_0PerMiss_WM_ts_checks_n1000000, file="fitMCAR_0PerMiss_WM_ts_checks_n1000000.RData")
#### min pattern##
##### 2 variables with missing data #######################
fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "min",
var.with.missing = 2)
fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000)
#load(file="fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
#load(file="fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_n1000000.RData")
fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000.RData")
fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "min",
var.with.missing = 2)
fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_n1000000.RData")
fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000.RData")
##### 4 variables with missing data #######################
fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "min",
var.with.missing = 4)
fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_n1000000.RData")
#load( file="fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000.RData")
fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "min",
var.with.missing = 4)
fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
#load(file="fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_n1000000.RData")
fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000.RData")
##### 6 variables with missing data #######################
fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "min",
var.with.missing = 6)
fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_n1000000.RData")
fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000.RData")
fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "min",
var.with.missing = 6)
fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000)
#load(file="fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
#load(file="fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_n1000000.RData")
fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000,
fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_n1000000)
save(fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_n1000000, file="fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MinPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000.RData")
####Max PATTERNS!!! #####
##### 2 variables with missing data #######################
fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "max",
var.with.missing = 2)
fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000)
#load(file="fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
#load(file="fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000,
fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_n1000000)
save(fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_20PerMiss_2VarMiss_WM_ts_checks_n1000000.RData")
fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "max",
var.with.missing = 2)
fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000,fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_n1000000 )
save(fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_50PerMiss_2VarMiss_WM_ts_checks_n1000000.RData")
##### 4 variables with missing data #######################
fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "max",
var.with.missing = 4)
fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000,
fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_n1000000)
save(fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_20PerMiss_4VarMiss_WM_ts_checks_n1000000.RData")
set.seed(100)
fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "max",
var.with.missing = 4)
fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000)
#load(file="fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000,
fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_n1000000)
save(fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_50PerMiss_4VarMiss_WM_ts_checks_n1000000.RData")
##### 6 variables with missing data #######################
fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000<-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.20, missing.type = "max",
var.with.missing = 6)
fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000)
#load( file="fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
#load( file="fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000,
fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_n1000000)
save(fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_20PerMiss_6VarMiss_WM_ts_checks_n1000000.RData")
fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000 <-
fit.components.simu(pop.model.list=pop.mod,fitted.mod=fitted.mod,sample.nobs =1000000,
missing.percentage = 0.50, missing.type = "max",
var.with.missing = 6)
fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000<- ts.fit(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000)
#load(file="fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
#load(file="fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000.RData")
fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000<-
ts.checks(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000,
fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000)
save(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000, file="fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_compo_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000, file="fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000.RData")
save(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000, file="fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_checks_n1000000.RData")
list.mean(fitMCAR_MaxPat_50PerMiss_6VarMiss_WM_ts_n1000000)
fitNoMissing_WM_new
|
testlist <- list(type = 0L, z = 1.7838734208744e-319)
result <- do.call(esreg::G1_fun,testlist)
str(result) | /esreg/inst/testfiles/G1_fun/libFuzzer_G1_fun/G1_fun_valgrind_files/1609893243-test.R | no_license | akhikolla/updated-only-Issues | R | false | false | 107 | r | testlist <- list(type = 0L, z = 1.7838734208744e-319)
result <- do.call(esreg::G1_fun,testlist)
str(result) |
#' @param x A simList or a directory containing a valid archivist repository
#' @param after A time (POSIX, character understandable by data.table).
#' Objects cached after this time will be shown or deleted.
#' @param before A time (POSIX, character understandable by data.table).
#' Objects cached before this time will be shown or deleted.
#' @param ... Other arguments. Currently unused.
#'
#' If neither \code{after} or \code{before} are provided, nor \code{userTags},
#' then all objects will be removed.
#' If both \code{after} and \code{before} are specified, then all objects between \code{after} and
#' \code{before} will be deleted.
#' If \code{userTags} is used, this will override \code{after} or \code{before}.
#'
#' @return Will clear all (or that match \code{userTags}, or between \code{after} or \code{before})
#' objects from the repository located at \code{cachePath} of the sim object,
#' if \code{sim} is provided, or located in \code{cacheRepo}. Also returns a data.table invisibly
#' of the removed items.
#'
#' @export
#' @importFrom archivist rmFromLocalRepo searchInLocalRepo
#' @importFrom methods setGeneric setMethod
#' @param userTags Character vector. If used, this will be used in place of the \code{after} and
#' \code{before}. Specifying one or more \code{userTag} here will
#' clear all objects that
#' match those tags. Matching is via regular expresssion, meaning
#' partial matches
#' will work unless strict beginning (^) and end ($) of string
#' characters are used. Matching
#' will be against any of the 3 columns returned by \code{showCache()},
#' i.e., artifact, tagValue or tagName. Also, length \code{userTags} > 1,
#' then matching is by `and`. For `or` matching, use | in a single character
#' string. See examples.
#'
#' @rdname viewCache
#'
#' @example inst/examples/example_Cache.R
#'
setGeneric("clearCache", function(x, userTags = character(), after, before, ...) {
standardGeneric("clearCache")
})
#' @export
#' @rdname viewCache
setMethod(
"clearCache",
definition = function(x, userTags, after, before, ...) {
if (missing(x)) {
message("x not specified; using ", getOption("spades.cachePath"))
x <- getOption("spades.cachePath")
}
if (missing(after)) after <- "1970-01-01"
if (missing(before)) before <- Sys.time() + 1e5
if (is(x, "simList")) x <- x@paths$cachePath
args <- append(list(x = x, after = after, before = before, userTags = userTags),
list(...))
objsDT <- do.call(showCache, args = args)
if (NROW(objsDT)) {
rastersInRepo <- objsDT[grep(tagValue, pattern = "Raster")]
if (all(!is.na(rastersInRepo$artifact))) {
suppressWarnings(rasters <- lapply(rastersInRepo$artifact, function(ras) {
loadFromLocalRepo(ras, repoDir = x, value = TRUE)
}))
filesToRemove <- unlist(lapply(rasters, function(x) filename(x)))
filesToRemove <- gsub(filesToRemove, pattern = ".{1}$", replacement = "*")
unlink(filesToRemove)
}
suppressWarnings(rmFromLocalRepo(unique(objsDT$artifact), x, many = TRUE))
}
return(invisible(objsDT))
})
#' Examining and modifying the cache
#'
#' These are convenience wrappers around \code{archivist} package functions.
#' They allow the user a bit of control over what is being cached.
#'
#' \describe{
#' \item{\code{clearCache}}{remove items from the cache based on their
#' \code{userTag} or \code{times} values.}
#' \item{\code{keepCache}}{remove all cached items \emph{except} those based on
#' certain \code{userTags} or \code{times} values.}
#' \item{\code{showCache}}{display the contents of the cache.}
#' }
#'
#' @inheritParams clearCache
#'
#' @export
#' @importFrom archivist splitTagsLocal
#' @importFrom data.table data.table set setkeyv
#' @rdname viewCache
#' @seealso \code{\link[archivist]{splitTagsLocal}}.
#'
#' @example inst/examples/example_Cache.R
#'
setGeneric("showCache", function(x, userTags = character(), after, before, ...) {
standardGeneric("showCache")
})
#' @export
#' @rdname viewCache
setMethod(
"showCache",
definition = function(x, userTags, after, before, ...) {
if (missing(x)) {
message("x not specified; using ", getOption("spades.cachePath"))
x <- getOption("spades.cachePath")
}
if (missing(after)) after <- "1970-01-01"
if (missing(before)) before <- Sys.time() + 1e5
if (is(x, "simList")) x <- x@paths$cachePath
objsDT <- showLocalRepo(x) %>% data.table()
setkeyv(objsDT, "md5hash")
if (NROW(objsDT) > 0) {
objsDT <- data.table(splitTagsLocal(x), key = "artifact")
objsDT3 <- objsDT[tagKey == "accessed"][(tagValue <= before) &
(tagValue >= after)][!duplicated(artifact)]
objsDT <- objsDT[artifact %in% objsDT3$artifact]
if (length(userTags) > 0) {
for (ut in userTags) {
objsDT2 <- objsDT[
grepl(tagValue, pattern = ut) |
grepl(tagKey, pattern = ut) |
grepl(artifact, pattern = ut)]
setkeyv(objsDT2, "artifact")
objsDT <- objsDT[unique(objsDT2, by = "artifact")[, artifact]] # merge each userTags
}
}
}
objsDT
})
#' @rdname viewCache
setGeneric("keepCache", function(x, userTags = character(), after, before, ...) {
standardGeneric("keepCache")
})
#' @export
#' @rdname viewCache
setMethod(
"keepCache",
definition = function(x, userTags, after, before, ...) {
if (missing(x)) {
message("x not specified; using ", getOption("spades.cachePath"))
x <- getOption("spades.cachePath")
}
if (missing(after)) after <- "1970-01-01"
if (missing(before)) before <- Sys.time() + 1e5
if (is(x, "simList")) x <- x@paths$cachePath
args <- append(list(x = x, after = after, before = before, userTags = userTags),
list(...))
objsDTAll <- showCache(x)
objsDT <- do.call(showCache, args = args)
keep <- unique(objsDT$artifact)
eliminate <- unique(objsDTAll$artifact[!(objsDTAll$artifact %in% keep)])
if (length(eliminate)) {
eliminate <- paste(eliminate, collapse = "|")
clearCache(x, eliminate)
}
return(objsDT)
})
| /R/cache-tools.R | no_license | guhjy/reproducible | R | false | false | 6,465 | r | #' @param x A simList or a directory containing a valid archivist repository
#' @param after A time (POSIX, character understandable by data.table).
#' Objects cached after this time will be shown or deleted.
#' @param before A time (POSIX, character understandable by data.table).
#' Objects cached before this time will be shown or deleted.
#' @param ... Other arguments. Currently unused.
#'
#' If neither \code{after} or \code{before} are provided, nor \code{userTags},
#' then all objects will be removed.
#' If both \code{after} and \code{before} are specified, then all objects between \code{after} and
#' \code{before} will be deleted.
#' If \code{userTags} is used, this will override \code{after} or \code{before}.
#'
#' @return Will clear all (or that match \code{userTags}, or between \code{after} or \code{before})
#' objects from the repository located at \code{cachePath} of the sim object,
#' if \code{sim} is provided, or located in \code{cacheRepo}. Also returns a data.table invisibly
#' of the removed items.
#'
#' @export
#' @importFrom archivist rmFromLocalRepo searchInLocalRepo
#' @importFrom methods setGeneric setMethod
#' @param userTags Character vector. If used, this will be used in place of the \code{after} and
#' \code{before}. Specifying one or more \code{userTag} here will
#' clear all objects that
#' match those tags. Matching is via regular expresssion, meaning
#' partial matches
#' will work unless strict beginning (^) and end ($) of string
#' characters are used. Matching
#' will be against any of the 3 columns returned by \code{showCache()},
#' i.e., artifact, tagValue or tagName. Also, length \code{userTags} > 1,
#' then matching is by `and`. For `or` matching, use | in a single character
#' string. See examples.
#'
#' @rdname viewCache
#'
#' @example inst/examples/example_Cache.R
#'
setGeneric("clearCache", function(x, userTags = character(), after, before, ...) {
standardGeneric("clearCache")
})
#' @export
#' @rdname viewCache
setMethod(
"clearCache",
definition = function(x, userTags, after, before, ...) {
if (missing(x)) {
message("x not specified; using ", getOption("spades.cachePath"))
x <- getOption("spades.cachePath")
}
if (missing(after)) after <- "1970-01-01"
if (missing(before)) before <- Sys.time() + 1e5
if (is(x, "simList")) x <- x@paths$cachePath
args <- append(list(x = x, after = after, before = before, userTags = userTags),
list(...))
objsDT <- do.call(showCache, args = args)
if (NROW(objsDT)) {
rastersInRepo <- objsDT[grep(tagValue, pattern = "Raster")]
if (all(!is.na(rastersInRepo$artifact))) {
suppressWarnings(rasters <- lapply(rastersInRepo$artifact, function(ras) {
loadFromLocalRepo(ras, repoDir = x, value = TRUE)
}))
filesToRemove <- unlist(lapply(rasters, function(x) filename(x)))
filesToRemove <- gsub(filesToRemove, pattern = ".{1}$", replacement = "*")
unlink(filesToRemove)
}
suppressWarnings(rmFromLocalRepo(unique(objsDT$artifact), x, many = TRUE))
}
return(invisible(objsDT))
})
#' Examining and modifying the cache
#'
#' These are convenience wrappers around \code{archivist} package functions.
#' They allow the user a bit of control over what is being cached.
#'
#' \describe{
#' \item{\code{clearCache}}{remove items from the cache based on their
#' \code{userTag} or \code{times} values.}
#' \item{\code{keepCache}}{remove all cached items \emph{except} those based on
#' certain \code{userTags} or \code{times} values.}
#' \item{\code{showCache}}{display the contents of the cache.}
#' }
#'
#' @inheritParams clearCache
#'
#' @export
#' @importFrom archivist splitTagsLocal
#' @importFrom data.table data.table set setkeyv
#' @rdname viewCache
#' @seealso \code{\link[archivist]{splitTagsLocal}}.
#'
#' @example inst/examples/example_Cache.R
#'
setGeneric("showCache", function(x, userTags = character(), after, before, ...) {
standardGeneric("showCache")
})
#' @export
#' @rdname viewCache
setMethod(
"showCache",
definition = function(x, userTags, after, before, ...) {
if (missing(x)) {
message("x not specified; using ", getOption("spades.cachePath"))
x <- getOption("spades.cachePath")
}
if (missing(after)) after <- "1970-01-01"
if (missing(before)) before <- Sys.time() + 1e5
if (is(x, "simList")) x <- x@paths$cachePath
objsDT <- showLocalRepo(x) %>% data.table()
setkeyv(objsDT, "md5hash")
if (NROW(objsDT) > 0) {
objsDT <- data.table(splitTagsLocal(x), key = "artifact")
objsDT3 <- objsDT[tagKey == "accessed"][(tagValue <= before) &
(tagValue >= after)][!duplicated(artifact)]
objsDT <- objsDT[artifact %in% objsDT3$artifact]
if (length(userTags) > 0) {
for (ut in userTags) {
objsDT2 <- objsDT[
grepl(tagValue, pattern = ut) |
grepl(tagKey, pattern = ut) |
grepl(artifact, pattern = ut)]
setkeyv(objsDT2, "artifact")
objsDT <- objsDT[unique(objsDT2, by = "artifact")[, artifact]] # merge each userTags
}
}
}
objsDT
})
#' @rdname viewCache
setGeneric("keepCache", function(x, userTags = character(), after, before, ...) {
standardGeneric("keepCache")
})
#' @export
#' @rdname viewCache
setMethod(
"keepCache",
definition = function(x, userTags, after, before, ...) {
if (missing(x)) {
message("x not specified; using ", getOption("spades.cachePath"))
x <- getOption("spades.cachePath")
}
if (missing(after)) after <- "1970-01-01"
if (missing(before)) before <- Sys.time() + 1e5
if (is(x, "simList")) x <- x@paths$cachePath
args <- append(list(x = x, after = after, before = before, userTags = userTags),
list(...))
objsDTAll <- showCache(x)
objsDT <- do.call(showCache, args = args)
keep <- unique(objsDT$artifact)
eliminate <- unique(objsDTAll$artifact[!(objsDTAll$artifact %in% keep)])
if (length(eliminate)) {
eliminate <- paste(eliminate, collapse = "|")
clearCache(x, eliminate)
}
return(objsDT)
})
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/AllMethods.R
\docType{methods}
\name{tnsPreprocess,TNI-method}
\alias{tnsPreprocess,TNI-method}
\alias{tnsPreprocess}
\title{Preprocessing of TNS class objects.}
\usage{
\S4method{tnsPreprocess}{TNI}(tni, survivalData, keycovar, time = 1,
event = 2, samples = NULL)
}
\arguments{
\item{tni}{A \linkS4class{TNI} class, already processed with the same samples
listed in the survival data.frame.}
\item{survivalData}{A named data.frame with samples in rows and survival data
in the columns.}
\item{keycovar}{A character vector of the 'keycovars' listed in the
data.frame columns.}
\item{time}{A numeric or character value corresponding to the column of the
data.frame where the time of last observation is given.}
\item{event}{A numeric or character value, corresponding to the columm of
the data.frame where the 'event' information is given.}
\item{samples}{An optional character vector listing samples to be analyzed.}
}
\value{
A preprocessed \linkS4class{TNS} class
}
\description{
Creates TNS class onbjects for regulons an survival data.
}
\examples{
data(dt4rtn, package="RTN")
data(survival.data)
# compute regulons for 3 TFs using the RTN package
rtni <- new("TNI", gexp=dt4rtn$gexp,
transcriptionFactors=dt4rtn$tfs[c("FOXM1","E2F2","PTTG1")])
rtni <- tni.preprocess(rtni,gexpIDs=dt4rtn$gexpIDs, verbose=FALSE)
rtni<-tni.permutation(rtni, nPermutations=100, verbose=FALSE) #sets 'nPermutations'>=1000
rtni<-tni.dpi.filter(rtni, verbose=FALSE)
# create a new TNS object
rtns <- tnsPreprocess(rtni, survival.data, keycovar = c("Grade","Age"),
time = 1, event = 2)
}
\seealso{
\code{\link[RTN:tni.preprocess]{tni.preprocess}} for similar
preprocessing.
}
| /man/tnsPreprocess-methods.Rd | no_license | xtsvm/RTNsurvival | R | false | true | 1,753 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/AllMethods.R
\docType{methods}
\name{tnsPreprocess,TNI-method}
\alias{tnsPreprocess,TNI-method}
\alias{tnsPreprocess}
\title{Preprocessing of TNS class objects.}
\usage{
\S4method{tnsPreprocess}{TNI}(tni, survivalData, keycovar, time = 1,
event = 2, samples = NULL)
}
\arguments{
\item{tni}{A \linkS4class{TNI} class, already processed with the same samples
listed in the survival data.frame.}
\item{survivalData}{A named data.frame with samples in rows and survival data
in the columns.}
\item{keycovar}{A character vector of the 'keycovars' listed in the
data.frame columns.}
\item{time}{A numeric or character value corresponding to the column of the
data.frame where the time of last observation is given.}
\item{event}{A numeric or character value, corresponding to the columm of
the data.frame where the 'event' information is given.}
\item{samples}{An optional character vector listing samples to be analyzed.}
}
\value{
A preprocessed \linkS4class{TNS} class
}
\description{
Creates TNS class onbjects for regulons an survival data.
}
\examples{
data(dt4rtn, package="RTN")
data(survival.data)
# compute regulons for 3 TFs using the RTN package
rtni <- new("TNI", gexp=dt4rtn$gexp,
transcriptionFactors=dt4rtn$tfs[c("FOXM1","E2F2","PTTG1")])
rtni <- tni.preprocess(rtni,gexpIDs=dt4rtn$gexpIDs, verbose=FALSE)
rtni<-tni.permutation(rtni, nPermutations=100, verbose=FALSE) #sets 'nPermutations'>=1000
rtni<-tni.dpi.filter(rtni, verbose=FALSE)
# create a new TNS object
rtns <- tnsPreprocess(rtni, survival.data, keycovar = c("Grade","Age"),
time = 1, event = 2)
}
\seealso{
\code{\link[RTN:tni.preprocess]{tni.preprocess}} for similar
preprocessing.
}
|
# Source reactive expressions and other code
source("external/appSourceFiles/reactives.R",local=T) # source reactive expressions
source("external/appSourceFiles/iosidebarwp1.R",local=T) # source input/output objects associated with sidebar wellPanel 1
source("external/appSourceFiles/iosidebarwp2.R",local=T) # source input/output objects associated with sidebar wellPanel 2
#### The is doesn't really do anything but issue system calls to another server,
#### Hence the lack of central code typically found here.
# Reactive expression (see reactives.R) for code tab in main panel
# Ideal, but cannot do this on the server side due to a bug in the shinyAce package.
#output$codeTab <- renderUI({ codeTab() })
output$HLTheme <- renderUI({ selectInput("hltheme", "Code highlighting theme:", getAceThemes(), selected="clouds_midnight") })
output$HLFontSize <- renderUI({ selectInput("hlfontsize", "Font size:", seq(8,24,by=2), selected=12) })
observe({
input$tsp
input$nlp
input$hltheme
for(i in 1:length(R_files)) eval(parse(text=sprintf("input$%s", gsub("\\.", "", basename(R_files[i])))))
for(i in 1:length(R_files)) updateAceEditor(session, gsub("\\.", "", basename(R_files[i])), theme=input$hltheme, fontSize=input$hlfontsize)
})
output$CodeDescription <- renderUI({
h6(HTML(
'<p style="text-align:justify;">I use code externalization for more complex apps to keep the
<strong><span style="color:#3366ff;">R</span></strong> code organized.
The <em>Header</em>, <em>Sidebar</em>, <em>Main</em>, and <em>About</em>
<strong><span style="color:#3366ff;">R</span></strong> scripts are sourced at the top level on the <em>UI</em> side
while <em>app.R</em> is sourced in <em>server.R</em>.
In turn, the <em>app.R</em> sources all of the reactive inputs/outputs/expressions
in the remaining <strong><span style="color:#3366ff;">R</span></strong> scripts.</p>'
))
})
output$pageviews <- renderText({
if (!file.exists("pageviews.Rdata")) pageviews <- 0 else load(file="pageviews.Rdata")
pageviews <- pageviews + 1
save(pageviews,file="pageviews.Rdata")
paste("Visits:",pageviews)
})
| /system_call_test-devel/external/app.R | no_license | man-bear-pig/shiny-apps | R | false | false | 2,147 | r | # Source reactive expressions and other code
source("external/appSourceFiles/reactives.R",local=T) # source reactive expressions
source("external/appSourceFiles/iosidebarwp1.R",local=T) # source input/output objects associated with sidebar wellPanel 1
source("external/appSourceFiles/iosidebarwp2.R",local=T) # source input/output objects associated with sidebar wellPanel 2
#### The is doesn't really do anything but issue system calls to another server,
#### Hence the lack of central code typically found here.
# Reactive expression (see reactives.R) for code tab in main panel
# Ideal, but cannot do this on the server side due to a bug in the shinyAce package.
#output$codeTab <- renderUI({ codeTab() })
output$HLTheme <- renderUI({ selectInput("hltheme", "Code highlighting theme:", getAceThemes(), selected="clouds_midnight") })
output$HLFontSize <- renderUI({ selectInput("hlfontsize", "Font size:", seq(8,24,by=2), selected=12) })
observe({
input$tsp
input$nlp
input$hltheme
for(i in 1:length(R_files)) eval(parse(text=sprintf("input$%s", gsub("\\.", "", basename(R_files[i])))))
for(i in 1:length(R_files)) updateAceEditor(session, gsub("\\.", "", basename(R_files[i])), theme=input$hltheme, fontSize=input$hlfontsize)
})
output$CodeDescription <- renderUI({
h6(HTML(
'<p style="text-align:justify;">I use code externalization for more complex apps to keep the
<strong><span style="color:#3366ff;">R</span></strong> code organized.
The <em>Header</em>, <em>Sidebar</em>, <em>Main</em>, and <em>About</em>
<strong><span style="color:#3366ff;">R</span></strong> scripts are sourced at the top level on the <em>UI</em> side
while <em>app.R</em> is sourced in <em>server.R</em>.
In turn, the <em>app.R</em> sources all of the reactive inputs/outputs/expressions
in the remaining <strong><span style="color:#3366ff;">R</span></strong> scripts.</p>'
))
})
output$pageviews <- renderText({
if (!file.exists("pageviews.Rdata")) pageviews <- 0 else load(file="pageviews.Rdata")
pageviews <- pageviews + 1
save(pageviews,file="pageviews.Rdata")
paste("Visits:",pageviews)
})
|
#!/bin/Rscript -l
##########################################################################################################
############### DADA2 PIPELINE 8 : Ad Phylogeny to Phyloseq ##############################################
##########################################################################################################
#### ####
#### Andreas Novotny, 2018-02 ####
#### https://github.com/andreasnovotny/DadaSlurm ####
#### ####
##########################################################################################################
##########################################################################################################
##########################################################################################################
library(phyloseq)
print('R will now ad the tree to the phyloseq object... ...')
args <- commandArgs(TRUE)
CURRENT_DIR <- args[1]
phylogeny <- readRDS(file.path(CURRENT_DIR,'phangorn_tree.rds'))
ps <- readRDS(file.path(CURRENT_DIR,'phyloseq.rds'))
ps@phy_tree <- phylogeny$tree
saveRDS(ps, paste(CURRENT_DIR,'/phyloseq.rds', sep=""))
##########################################################################################################
##########################################################################################################
| /Pipeline/dada2_pipeline8.R | no_license | andreasnovotny/DadaSlurm | R | false | false | 1,643 | r | #!/bin/Rscript -l
##########################################################################################################
############### DADA2 PIPELINE 8 : Ad Phylogeny to Phyloseq ##############################################
##########################################################################################################
#### ####
#### Andreas Novotny, 2018-02 ####
#### https://github.com/andreasnovotny/DadaSlurm ####
#### ####
##########################################################################################################
##########################################################################################################
##########################################################################################################
library(phyloseq)
print('R will now ad the tree to the phyloseq object... ...')
args <- commandArgs(TRUE)
CURRENT_DIR <- args[1]
phylogeny <- readRDS(file.path(CURRENT_DIR,'phangorn_tree.rds'))
ps <- readRDS(file.path(CURRENT_DIR,'phyloseq.rds'))
ps@phy_tree <- phylogeny$tree
saveRDS(ps, paste(CURRENT_DIR,'/phyloseq.rds', sep=""))
##########################################################################################################
##########################################################################################################
|
best<- function(state,outcome){
# read data # data is still with NAs
data<- read.csv("outcome-of-care-measures.csv",colClasses = "character")
sdata<-data[,c(2,7,11,17,23)]
names(sdata)<- c("h.name","State","heart attack","heart failure","pneumonia")
# validating Argument outcome
if (outcome== "heart attack")
sdata$"heart attack"<-as.numeric(sdata$"heart attack")
else
if (outcome== "heart failure")
sdata$"heart failure"<-as.numeric(sdata$"heart failure")
else
if (outcome== "pneumonia")
sdata$"pneumonia"<-as.numeric(sdata$"pneumonia")
else
stop("invalid Outcome")
# validating Argument State
y<- (sdata$State == state)
if (sum(y) == 0)
stop("invalid State")
## Take only those rows with have the required state value
sdata <- sdata[sdata$State==state & sdata[outcome] != 'Not Available', ]
vals <- sdata[, outcome]
rowNum <- which.min(vals)
## Return hospital name in that state with lowest 30-day death rate
sdata[rowNum,1]
} | /Best Hospital _ Final.R | no_license | anurag-code/JhonHopkins_R_Prog | R | false | false | 1,042 | r | best<- function(state,outcome){
# read data # data is still with NAs
data<- read.csv("outcome-of-care-measures.csv",colClasses = "character")
sdata<-data[,c(2,7,11,17,23)]
names(sdata)<- c("h.name","State","heart attack","heart failure","pneumonia")
# validating Argument outcome
if (outcome== "heart attack")
sdata$"heart attack"<-as.numeric(sdata$"heart attack")
else
if (outcome== "heart failure")
sdata$"heart failure"<-as.numeric(sdata$"heart failure")
else
if (outcome== "pneumonia")
sdata$"pneumonia"<-as.numeric(sdata$"pneumonia")
else
stop("invalid Outcome")
# validating Argument State
y<- (sdata$State == state)
if (sum(y) == 0)
stop("invalid State")
## Take only those rows with have the required state value
sdata <- sdata[sdata$State==state & sdata[outcome] != 'Not Available', ]
vals <- sdata[, outcome]
rowNum <- which.min(vals)
## Return hospital name in that state with lowest 30-day death rate
sdata[rowNum,1]
} |
build_recode_39<-function() {
require(dplyr,quietly = T,warn.conflicts = FALSE)
require(stringr,quietly = T,warn.conflicts = FALSE)
recode39<-read.delim("./misc/recode39.tab",stringsAsFactors = F)
recode39$ICD.10<-gsub("[()]","",recode39$ICD.10)
colnames(recode39)<-tolower(colnames(recode39))
recode39_codes<-data.frame()
invisible(
mapply(function(index,codes) {
ranges<-strsplit(codes,split = ",")[[1]]
starts<-gsub("-.*","",ranges)
ends<-gsub(".*-","",ranges)
df<-data.frame(recode=index,start=starts,end=ends)
recode39_codes<<-rbind(recode39_codes,df)
}, recode39$recode, recode39$icd.10)
)
recode39_codes<-inner_join(recode39_codes,recode39)
recode39_codes$icd.10<-NULL
recode39_codes$start<-str_trim(gsub("[*]","",recode39_codes$start))
recode39_codes$end<-str_trim(gsub("[*]","",recode39_codes$end))
recode39<-recode39_codes[,c("recode","t","parent","sex","age","cause")]
recode39<-unique(recode39)
recode39_codes<-recode39_codes[,c("recode","start","end")]
save(recode39,file="./data/recode39.RData")
save(recode39_codes,file="./data/recode39_codes.RData")
}
build_code39_categories<-function() {
# category39<-data.frame(name=character(),regexp=character())
# category39<-rbind(category39,data.frame(title="Cancer", name="cancer",regexp="eoplasm|lymphoma|Leuk"))
# category39<-rbind(category39,data.frame(title="Human immunodeficiency virus (HIV) disease", name="hiv",regexp="HIV"))
# category39<-rbind(category39,data.frame(title="Diabetes", name="diabetes",regexp="Diabetes"))
# category39<-rbind(category39,data.frame(title="Alzheimer's Disease", name="alzheimers",regexp="Alzheim"))
# category39<-rbind(category39,data.frame(title="Diseases of heart", name="heart_disease",regexp="[Hh]eart"))
# category39<-rbind(category39,data.frame(title="Essential (primary) hypertension and hypertensive renal disease", name="hypertension",regexp="Essent.*[Hh]ypertens"))
# category39<-rbind(category39,data.frame(title="Cerebrovascular diseases", name="cerebrovascular",regexp="Cerebrovasc"))
# category39<-rbind(category39,data.frame(title="Influenza and pneumonia", name="influenza",regexp="Influenz"))
# category39<-rbind(category39,data.frame(title="Chronic lower respiratory diseases", name="respiratory",regexp="respiratory"))
# category39<-rbind(category39,data.frame(title="Chronic liver disease and cirrhosis", name="liver",regexp="liver.*cirrho"))
# category39<-rbind(category39,data.frame(title="Nephritis, nephrotic syndrome, and nephrosis", name="nephritis",regexp="[Nn]ephrit"))
# category39<-rbind(category39,data.frame(title="Intentional self-harm (suicide)", name="suicide",regexp="[Ss]uicide"))
# category39<-rbind(category39,data.frame(title="Assault (homicide)", name="assault",regexp="[Aa]ssault"))
category39<-read.csv("./misc/category39.csv")
save(category39,file = "./data/category39.RData")
}
#' Cause of Death Codes - NVSS
#'
#' The National Vital Statistics System publishes annual reports on Mortality. Statistics are provided for categories based on the
#' 39 Selected Causes of Death. This function maps the categories to the 39 Selected Causes of Death.
#'
#' @param name character giving the name of the category. If omitted, returns a vector of valid names.This function uses 'fuzzy' matching, so using any of "cerebro","cerevasc","cvasc", for example, will match "cerebrovascular".
#'
#' @return
#' returns an integer vector of recode values used to identify cases for inclusion in this category or a character vector of valid names.
#'
#' @export
#'
#'
#' @examples
#' nvss_cause_of_death_39()
#'
#' recodes<-nvss_cause_of_death_39("cancer")
#' recodes<-nvss_cause_of_death_39("resp")
#'
#'
nvss_cause_of_death_39<-function(name) {
data(category39,envir = environment())
if (missing("name")) {
return (as.character(category39$name))
}
fuzzy<-as.vector(adist(name,category39$name,partial=T))
index<-which.min(fuzzy)
data(recode39,envir = environment())
parent<-category39[index,"recode_id"]
res<-recode39[recode39$parent==parent,"recode"]
return(res)
}
#' ICD-10 Index Of 39 Selected Causes of Death
#'
#' @param icd10 character ICD-10 code
#'
#' @return Recode value for 39 Selected Causes of Death
#' @export
#'
#' @examples
#' recode.cause.39("C45")
#'
recode.cause.39<-function(icd10) {
data("recode39_codes",envir = environment())
data("recode39",envir = environment())
res<-recode39_codes[icd10>=recode39_codes$start&icd10<=recode39_codes$end,"recode"]
recode39[recode39$recode%in%res & recode39$recode!=recode39$parent,"recode"]
}
| /code/build_recodes_39.R | no_license | JahNorr/mortRecode | R | false | false | 4,630 | r |
build_recode_39<-function() {
require(dplyr,quietly = T,warn.conflicts = FALSE)
require(stringr,quietly = T,warn.conflicts = FALSE)
recode39<-read.delim("./misc/recode39.tab",stringsAsFactors = F)
recode39$ICD.10<-gsub("[()]","",recode39$ICD.10)
colnames(recode39)<-tolower(colnames(recode39))
recode39_codes<-data.frame()
invisible(
mapply(function(index,codes) {
ranges<-strsplit(codes,split = ",")[[1]]
starts<-gsub("-.*","",ranges)
ends<-gsub(".*-","",ranges)
df<-data.frame(recode=index,start=starts,end=ends)
recode39_codes<<-rbind(recode39_codes,df)
}, recode39$recode, recode39$icd.10)
)
recode39_codes<-inner_join(recode39_codes,recode39)
recode39_codes$icd.10<-NULL
recode39_codes$start<-str_trim(gsub("[*]","",recode39_codes$start))
recode39_codes$end<-str_trim(gsub("[*]","",recode39_codes$end))
recode39<-recode39_codes[,c("recode","t","parent","sex","age","cause")]
recode39<-unique(recode39)
recode39_codes<-recode39_codes[,c("recode","start","end")]
save(recode39,file="./data/recode39.RData")
save(recode39_codes,file="./data/recode39_codes.RData")
}
build_code39_categories<-function() {
# category39<-data.frame(name=character(),regexp=character())
# category39<-rbind(category39,data.frame(title="Cancer", name="cancer",regexp="eoplasm|lymphoma|Leuk"))
# category39<-rbind(category39,data.frame(title="Human immunodeficiency virus (HIV) disease", name="hiv",regexp="HIV"))
# category39<-rbind(category39,data.frame(title="Diabetes", name="diabetes",regexp="Diabetes"))
# category39<-rbind(category39,data.frame(title="Alzheimer's Disease", name="alzheimers",regexp="Alzheim"))
# category39<-rbind(category39,data.frame(title="Diseases of heart", name="heart_disease",regexp="[Hh]eart"))
# category39<-rbind(category39,data.frame(title="Essential (primary) hypertension and hypertensive renal disease", name="hypertension",regexp="Essent.*[Hh]ypertens"))
# category39<-rbind(category39,data.frame(title="Cerebrovascular diseases", name="cerebrovascular",regexp="Cerebrovasc"))
# category39<-rbind(category39,data.frame(title="Influenza and pneumonia", name="influenza",regexp="Influenz"))
# category39<-rbind(category39,data.frame(title="Chronic lower respiratory diseases", name="respiratory",regexp="respiratory"))
# category39<-rbind(category39,data.frame(title="Chronic liver disease and cirrhosis", name="liver",regexp="liver.*cirrho"))
# category39<-rbind(category39,data.frame(title="Nephritis, nephrotic syndrome, and nephrosis", name="nephritis",regexp="[Nn]ephrit"))
# category39<-rbind(category39,data.frame(title="Intentional self-harm (suicide)", name="suicide",regexp="[Ss]uicide"))
# category39<-rbind(category39,data.frame(title="Assault (homicide)", name="assault",regexp="[Aa]ssault"))
category39<-read.csv("./misc/category39.csv")
save(category39,file = "./data/category39.RData")
}
#' Cause of Death Codes - NVSS
#'
#' The National Vital Statistics System publishes annual reports on Mortality. Statistics are provided for categories based on the
#' 39 Selected Causes of Death. This function maps the categories to the 39 Selected Causes of Death.
#'
#' @param name character giving the name of the category. If omitted, returns a vector of valid names.This function uses 'fuzzy' matching, so using any of "cerebro","cerevasc","cvasc", for example, will match "cerebrovascular".
#'
#' @return
#' returns an integer vector of recode values used to identify cases for inclusion in this category or a character vector of valid names.
#'
#' @export
#'
#'
#' @examples
#' nvss_cause_of_death_39()
#'
#' recodes<-nvss_cause_of_death_39("cancer")
#' recodes<-nvss_cause_of_death_39("resp")
#'
#'
nvss_cause_of_death_39<-function(name) {
data(category39,envir = environment())
if (missing("name")) {
return (as.character(category39$name))
}
fuzzy<-as.vector(adist(name,category39$name,partial=T))
index<-which.min(fuzzy)
data(recode39,envir = environment())
parent<-category39[index,"recode_id"]
res<-recode39[recode39$parent==parent,"recode"]
return(res)
}
#' ICD-10 Index Of 39 Selected Causes of Death
#'
#' @param icd10 character ICD-10 code
#'
#' @return Recode value for 39 Selected Causes of Death
#' @export
#'
#' @examples
#' recode.cause.39("C45")
#'
recode.cause.39<-function(icd10) {
data("recode39_codes",envir = environment())
data("recode39",envir = environment())
res<-recode39_codes[icd10>=recode39_codes$start&icd10<=recode39_codes$end,"recode"]
recode39[recode39$recode%in%res & recode39$recode!=recode39$parent,"recode"]
}
|
# coursera Specialization: "Data Science" by Johns Hopkins University
# Course: 4. Exploratory Data Analysis
# Assignment: Course Project 1
# Author: Niek Alexander Peters, MD
# PhD Candidate Surgical Oncology
# UMC Utrecht, The Netherlands
# Download file, unzip and load data
dataSet <- "dataset.zip"
fileUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
if(!file.exists(dataSet)) {
download.file(fileUrl, dataSet, method = "auto")
unzip(dataSet)
}
# Load dependencies
if (!("data.table" %in% rownames(installed.packages()))) {install.packages("data.table")}
suppressMessages(library(data.table))
if (!("sqldf" %in% rownames(installed.packages()))) {install.packages("sqldf")}
suppressMessages(library(sqldf))
# Read in data
hpc <- rbind(
read.csv.sql("household_power_consumption.txt", sql = "select * from file where Date == '1/2/2007' ", header = TRUE, sep = ";"),
read.csv.sql("household_power_consumption.txt", sql = "select * from file where Date == '2/2/2007' ", header = TRUE, sep = ";")
)
# Converse Date and Time string vectors to date and time objects
DateTime <- strptime(paste(hpc$Date, hpc$Time), format = '%d/%m/%Y %H:%M:%S')
hpc$DateTime <- DateTime
# Start PNG device
png(filename = "./plot3.png", width = 480, height = 480, bg = "transparent")
# Draw the plot (Sub_metering per time)
plot(hpc$DateTime, hpc$Sub_metering_1, type = "n", ylab = "Energy sub metering", xlab = "")
lines(hpc$DateTime, hpc$Sub_metering_1, col = "black")
lines(hpc$DateTime, hpc$Sub_metering_2, col = "red")
lines(hpc$DateTime, hpc$Sub_metering_3, col = "blue")
legend("topright", lty = 1, col=c("black", "red", "blue"), legend= c("Sub_metering 1", "Sub_metering 2", "Sub_metergin 3"))
# Stop the device
dev.off() | /plot3.R | no_license | npeters91/ExData_Plotting1 | R | false | false | 1,922 | r | # coursera Specialization: "Data Science" by Johns Hopkins University
# Course: 4. Exploratory Data Analysis
# Assignment: Course Project 1
# Author: Niek Alexander Peters, MD
# PhD Candidate Surgical Oncology
# UMC Utrecht, The Netherlands
# Download file, unzip and load data
dataSet <- "dataset.zip"
fileUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
if(!file.exists(dataSet)) {
download.file(fileUrl, dataSet, method = "auto")
unzip(dataSet)
}
# Load dependencies
if (!("data.table" %in% rownames(installed.packages()))) {install.packages("data.table")}
suppressMessages(library(data.table))
if (!("sqldf" %in% rownames(installed.packages()))) {install.packages("sqldf")}
suppressMessages(library(sqldf))
# Read in data
hpc <- rbind(
read.csv.sql("household_power_consumption.txt", sql = "select * from file where Date == '1/2/2007' ", header = TRUE, sep = ";"),
read.csv.sql("household_power_consumption.txt", sql = "select * from file where Date == '2/2/2007' ", header = TRUE, sep = ";")
)
# Converse Date and Time string vectors to date and time objects
DateTime <- strptime(paste(hpc$Date, hpc$Time), format = '%d/%m/%Y %H:%M:%S')
hpc$DateTime <- DateTime
# Start PNG device
png(filename = "./plot3.png", width = 480, height = 480, bg = "transparent")
# Draw the plot (Sub_metering per time)
plot(hpc$DateTime, hpc$Sub_metering_1, type = "n", ylab = "Energy sub metering", xlab = "")
lines(hpc$DateTime, hpc$Sub_metering_1, col = "black")
lines(hpc$DateTime, hpc$Sub_metering_2, col = "red")
lines(hpc$DateTime, hpc$Sub_metering_3, col = "blue")
legend("topright", lty = 1, col=c("black", "red", "blue"), legend= c("Sub_metering 1", "Sub_metering 2", "Sub_metergin 3"))
# Stop the device
dev.off() |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/cc_social_historical.R
\name{cc_social_historical}
\alias{cc_social_historical}
\title{cc_social_historical}
\usage{
cc_social_historical(
symbol = NULL,
start = NULL,
end = NULL,
interval = c("daily", "hourly"),
api_key = NULL
)
}
\arguments{
\item{symbol}{character, the symbol of interest.}
\item{start}{character or Date, the start date for importation.}
\item{end}{character or Date, the end date for importation.}
\item{interval}{character, the frequency of the data, it can be "daily" or "hourly".}
\item{api_key}{character}
}
\value{
a tibble
}
\description{
cc_social_historical
}
| /man/cc_social_historical.Rd | no_license | beniamino98/cryptocompareR | R | false | true | 682 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/cc_social_historical.R
\name{cc_social_historical}
\alias{cc_social_historical}
\title{cc_social_historical}
\usage{
cc_social_historical(
symbol = NULL,
start = NULL,
end = NULL,
interval = c("daily", "hourly"),
api_key = NULL
)
}
\arguments{
\item{symbol}{character, the symbol of interest.}
\item{start}{character or Date, the start date for importation.}
\item{end}{character or Date, the end date for importation.}
\item{interval}{character, the frequency of the data, it can be "daily" or "hourly".}
\item{api_key}{character}
}
\value{
a tibble
}
\description{
cc_social_historical
}
|
# Server code for safetyGraphics App
# - calls dataUpload module (data tab)
# - calls renderSettings module (settings tab)
# - calls chart modules (chart tab)
# - uses render UI to append a red X or green check on tab title,
# indicating whether user has satisfied requirements of that tab
function(input, output, session){
##############################################################
# initialize dataUpload module
#
# returns selected dataset, settings, and validation status
##############################################################
dataUpload_out <- callModule(dataUpload, "datatab")
##############################################################
# Initialize Settings Module
#
# generate settings page based on selected data set & generated/selected settings obj
#
# NOTE: module is being triggered when selected dataset changes OR when settings list changes
# this could cause the module to trigger twice unecessarily in some cases because the settings are generated
# AFTER the data is changed.
#
# returns updated settings and validation status
##############################################################
settings_new <- callModule(
renderSettings,
"settingsUI",
data = reactive(dataUpload_out$data_selected()),
settings = reactive(dataUpload_out$settings()),
status = reactive(dataUpload_out$status())
)
#toggle css class of chart tabs
observeEvent(settings_new$status(),{
for (chart in settings_new$charts()){
valid <- settings_new$status()$charts[[chart]]
## code to toggle css for chart-specific tab here
toggleClass(selector= paste0("#nav_id li.dropdown ul.dropdown-menu li a[data-value='", chart, "']"), class="valid", condition=valid==TRUE)
toggleClass(selector= paste0("#nav_id li.dropdown ul.dropdown-menu li a[data-value='", chart, "']"), class="invalid", condition=valid==FALSE)
}
})
# hide charts tab if no chart selected
observeEvent(settings_new$charts(),{
if (is.null(settings_new$charts())){
hideTab(inputId = "nav_id", target = "Charts")
hideTab(inputId = "nav_id", target = "Reports")
}
},
ignoreNULL = FALSE,
ignoreInit = TRUE) # so there's no hiding when the app first loads
##############################################################
# Initialize Charts Modules
##############################################################
labeledCharts <- list()
for (row in 1:nrow(filter(chartsMetadata, chart %in% all_charts))){
labeledCharts[row]<-filter(chartsMetadata, chart %in% all_charts)[row,"chart"]
names(labeledCharts)[row]<-filter(chartsMetadata, chart %in% all_charts)[row,"label"]
}
# set up all chart tabs from the start (all_charts defined in global.R)
for (chartnum in 1:length(labeledCharts)){
chart<-labeledCharts[[chartnum]]
chartLabel<-names(labeledCharts)[[chartnum]]
tabid <- paste0(chart, "_tab_title")
appendTab(
inputId = "nav_id",
tab = tabPanel(
title = chartLabel,
value = chart,
renderChartUI(paste0("chart", chart))
),
menuName = "Charts"
)
}
# hide/show chart tabs in response to user selections
observe({
# show charts and reports tabs if any charts are selected
showTab(inputId = "nav_id", target = "Charts")
showTab(inputId = "nav_id", target = "Reports")
selected_charts <- settings_new$charts()
unselected_charts <- all_charts[!all_charts %in% selected_charts]
for(chart in unselected_charts){
hideTab(inputId = "nav_id",
target = chart)
}
for(chart in selected_charts){
showTab(inputId = "nav_id",
target = chart)
}
})
for(chart in all_charts){
chartType <- chartsMetadata %>% filter(chart==!!chart) %>% pull(type)
width <- chartsMetadata %>% filter(chart==!!chart) %>% pull(maxWidth)
callModule(
module = renderChart,
id = paste0("chart", chart),
data = reactive(dataUpload_out$data_selected()),
settings = reactive(settings_new$settings()),
valid = reactive(settings_new$status()$charts[[chart]]),
chart = chart,
type = chartType,
width = width
# type = "htmlwidget"
)
}
callModule(
module = renderReports,
id = "reportsUI",
data = reactive(dataUpload_out$data_selected()),
settings = reactive(settings_new$settings()),
charts = reactive(labeledCharts[labeledCharts %in% settings_new$charts()])
)
output$about <- renderUI({
HTML('<h1> <b> Welcome to the Safety Graphics Shiny App </b> </h1>
<p> The Safety Graphics Shiny app is an interactive tool for evaluating clinical trial safety using
a flexible data pipeline. This application and corresponding
<a href="https://cran.r-project.org/web/packages/safetyGraphics/index.html">safetyGraphics</a>
R package have been developed as part of the <a href="https://safetygraphics.github.io/">Interactive Safety Graphics (ISG) workstream</a>
of the ASA Biopharm-DIA Safety Working Group. </p>
<h3><i> Using the app</i></h3>
<p>Detailed instructions about using the app can be found in our
<a href="https://cran.r-project.org/web/packages/safetyGraphics/vignettes/shinyUserGuide.html">vignette</a>. In short,
the user will begin by loading a data file, adjust settings as needed and view the interactive charts.
Finally, the user may export a self-contained, fully reproducible snapshot of the charts that can be easily shared with others.</p>
<h3><i> Clinical Workflow </i></h3>
This shiny app has been developed in parallel with a well-documented <a href="https://github.com/SafetyGraphics/SafetyGraphics.github.io/raw/master/guide/HepExplorerWorkflow_v1_1.pdf">clinical workflow</a>
for monitoring hepatotoxicity. The workflow, written by expert physicians, provides a detailed description of how the interactive graphics can be used as part of a safety clinician’s monitoring practice.
<h3><i> Interactive Charts </i></h3>
<p> The included interactive charts are built using the <code>htmlwidgets</code> framework in R. The code libraries
and configuration details for the underlying JavaScript charts are located below.
<ul>
<li>Hepatic Safety Explorer -
<a href="https://github.com/SafetyGraphics/hep-explorer">Library</a>,
<a href="https://github.com/SafetyGraphics/hep-explorer/wiki/Configuration">Configuration</a>
</li>
<li>Histogram -
<a href="https://github.com/RhoInc/safety-histogram">Library</a>,
<a href="https://github.com/RhoInc/safety-histogram/wiki/Configuration">Configuration</a></li>
<li>Outlier Explorer -
<a href="https://github.com/RhoInc/safety-outlier-explorer">Library</a>,
<a href="https://github.com/RhoInc/safety-outlier-explorer/wiki/Configuration">Configuration</a></li>
<li>Shift Plot -
<a href="https://github.com/RhoInc/safety-shift-plot">Library</a>,
<a href="https://github.com/RhoInc/safety-shift-plot/wiki/Configuration">Configuration</a></li>
<li>Results Over Time -
<a href="https://github.com/RhoInc/safety-results-over-time">Library</a>,
<a href="https://github.com/RhoInc/safety-results-over-time/wiki/Configuration">Configuration</a></li>
<li>Paneled Outlier Explorer -
<a href="https://github.com/RhoInc/paneled-outlier-explorer">Library</a>,
<a href="https://github.com/RhoInc/paneled-outlier-explorer/wiki/Configuration">Configuration</a></li></ul>
</p>
<br>
<p>For more information about <code>safetyGraphics</code>, please visit our
<a href="https://github.com/SafetyGraphics/safetyGraphics">GitHub repository</a>. We also welcome your suggestions in our
<a href="https://github.com/SafetyGraphics/safetyGraphics/issues">issue tracker</a>.
</p>')
})
output$hex <- renderImage({
list(src = system.file("safetyGraphicsHex/safetyGraphicsHex.png", package = "safetyGraphics"), width="60%")
}, deleteFile = FALSE)
session$onSessionEnded(stopApp)
}
| /inst/safetyGraphics_app/server.R | no_license | mli1/safetyGraphics | R | false | false | 8,008 | r | # Server code for safetyGraphics App
# - calls dataUpload module (data tab)
# - calls renderSettings module (settings tab)
# - calls chart modules (chart tab)
# - uses render UI to append a red X or green check on tab title,
# indicating whether user has satisfied requirements of that tab
function(input, output, session){
##############################################################
# initialize dataUpload module
#
# returns selected dataset, settings, and validation status
##############################################################
dataUpload_out <- callModule(dataUpload, "datatab")
##############################################################
# Initialize Settings Module
#
# generate settings page based on selected data set & generated/selected settings obj
#
# NOTE: module is being triggered when selected dataset changes OR when settings list changes
# this could cause the module to trigger twice unecessarily in some cases because the settings are generated
# AFTER the data is changed.
#
# returns updated settings and validation status
##############################################################
settings_new <- callModule(
renderSettings,
"settingsUI",
data = reactive(dataUpload_out$data_selected()),
settings = reactive(dataUpload_out$settings()),
status = reactive(dataUpload_out$status())
)
#toggle css class of chart tabs
observeEvent(settings_new$status(),{
for (chart in settings_new$charts()){
valid <- settings_new$status()$charts[[chart]]
## code to toggle css for chart-specific tab here
toggleClass(selector= paste0("#nav_id li.dropdown ul.dropdown-menu li a[data-value='", chart, "']"), class="valid", condition=valid==TRUE)
toggleClass(selector= paste0("#nav_id li.dropdown ul.dropdown-menu li a[data-value='", chart, "']"), class="invalid", condition=valid==FALSE)
}
})
# hide charts tab if no chart selected
observeEvent(settings_new$charts(),{
if (is.null(settings_new$charts())){
hideTab(inputId = "nav_id", target = "Charts")
hideTab(inputId = "nav_id", target = "Reports")
}
},
ignoreNULL = FALSE,
ignoreInit = TRUE) # so there's no hiding when the app first loads
##############################################################
# Initialize Charts Modules
##############################################################
labeledCharts <- list()
for (row in 1:nrow(filter(chartsMetadata, chart %in% all_charts))){
labeledCharts[row]<-filter(chartsMetadata, chart %in% all_charts)[row,"chart"]
names(labeledCharts)[row]<-filter(chartsMetadata, chart %in% all_charts)[row,"label"]
}
# set up all chart tabs from the start (all_charts defined in global.R)
for (chartnum in 1:length(labeledCharts)){
chart<-labeledCharts[[chartnum]]
chartLabel<-names(labeledCharts)[[chartnum]]
tabid <- paste0(chart, "_tab_title")
appendTab(
inputId = "nav_id",
tab = tabPanel(
title = chartLabel,
value = chart,
renderChartUI(paste0("chart", chart))
),
menuName = "Charts"
)
}
# hide/show chart tabs in response to user selections
observe({
# show charts and reports tabs if any charts are selected
showTab(inputId = "nav_id", target = "Charts")
showTab(inputId = "nav_id", target = "Reports")
selected_charts <- settings_new$charts()
unselected_charts <- all_charts[!all_charts %in% selected_charts]
for(chart in unselected_charts){
hideTab(inputId = "nav_id",
target = chart)
}
for(chart in selected_charts){
showTab(inputId = "nav_id",
target = chart)
}
})
for(chart in all_charts){
chartType <- chartsMetadata %>% filter(chart==!!chart) %>% pull(type)
width <- chartsMetadata %>% filter(chart==!!chart) %>% pull(maxWidth)
callModule(
module = renderChart,
id = paste0("chart", chart),
data = reactive(dataUpload_out$data_selected()),
settings = reactive(settings_new$settings()),
valid = reactive(settings_new$status()$charts[[chart]]),
chart = chart,
type = chartType,
width = width
# type = "htmlwidget"
)
}
callModule(
module = renderReports,
id = "reportsUI",
data = reactive(dataUpload_out$data_selected()),
settings = reactive(settings_new$settings()),
charts = reactive(labeledCharts[labeledCharts %in% settings_new$charts()])
)
output$about <- renderUI({
HTML('<h1> <b> Welcome to the Safety Graphics Shiny App </b> </h1>
<p> The Safety Graphics Shiny app is an interactive tool for evaluating clinical trial safety using
a flexible data pipeline. This application and corresponding
<a href="https://cran.r-project.org/web/packages/safetyGraphics/index.html">safetyGraphics</a>
R package have been developed as part of the <a href="https://safetygraphics.github.io/">Interactive Safety Graphics (ISG) workstream</a>
of the ASA Biopharm-DIA Safety Working Group. </p>
<h3><i> Using the app</i></h3>
<p>Detailed instructions about using the app can be found in our
<a href="https://cran.r-project.org/web/packages/safetyGraphics/vignettes/shinyUserGuide.html">vignette</a>. In short,
the user will begin by loading a data file, adjust settings as needed and view the interactive charts.
Finally, the user may export a self-contained, fully reproducible snapshot of the charts that can be easily shared with others.</p>
<h3><i> Clinical Workflow </i></h3>
This shiny app has been developed in parallel with a well-documented <a href="https://github.com/SafetyGraphics/SafetyGraphics.github.io/raw/master/guide/HepExplorerWorkflow_v1_1.pdf">clinical workflow</a>
for monitoring hepatotoxicity. The workflow, written by expert physicians, provides a detailed description of how the interactive graphics can be used as part of a safety clinician’s monitoring practice.
<h3><i> Interactive Charts </i></h3>
<p> The included interactive charts are built using the <code>htmlwidgets</code> framework in R. The code libraries
and configuration details for the underlying JavaScript charts are located below.
<ul>
<li>Hepatic Safety Explorer -
<a href="https://github.com/SafetyGraphics/hep-explorer">Library</a>,
<a href="https://github.com/SafetyGraphics/hep-explorer/wiki/Configuration">Configuration</a>
</li>
<li>Histogram -
<a href="https://github.com/RhoInc/safety-histogram">Library</a>,
<a href="https://github.com/RhoInc/safety-histogram/wiki/Configuration">Configuration</a></li>
<li>Outlier Explorer -
<a href="https://github.com/RhoInc/safety-outlier-explorer">Library</a>,
<a href="https://github.com/RhoInc/safety-outlier-explorer/wiki/Configuration">Configuration</a></li>
<li>Shift Plot -
<a href="https://github.com/RhoInc/safety-shift-plot">Library</a>,
<a href="https://github.com/RhoInc/safety-shift-plot/wiki/Configuration">Configuration</a></li>
<li>Results Over Time -
<a href="https://github.com/RhoInc/safety-results-over-time">Library</a>,
<a href="https://github.com/RhoInc/safety-results-over-time/wiki/Configuration">Configuration</a></li>
<li>Paneled Outlier Explorer -
<a href="https://github.com/RhoInc/paneled-outlier-explorer">Library</a>,
<a href="https://github.com/RhoInc/paneled-outlier-explorer/wiki/Configuration">Configuration</a></li></ul>
</p>
<br>
<p>For more information about <code>safetyGraphics</code>, please visit our
<a href="https://github.com/SafetyGraphics/safetyGraphics">GitHub repository</a>. We also welcome your suggestions in our
<a href="https://github.com/SafetyGraphics/safetyGraphics/issues">issue tracker</a>.
</p>')
})
output$hex <- renderImage({
list(src = system.file("safetyGraphicsHex/safetyGraphicsHex.png", package = "safetyGraphics"), width="60%")
}, deleteFile = FALSE)
session$onSessionEnded(stopApp)
}
|
#################################### read & merge datas ####################################
handleData <- function(ref, wd, out){
ref_table <- read.csv(ref, header=TRUE)
ref_table <- ref_table[unique(ref_table$Ensembl.ID.supplied.by.Ensembl.),]
TCGA_genes <- as.character(ref_table$Approved.Symbol)
gene_ids <- as.character(ref_table$Ensembl.ID.supplied.by.Ensembl.)
TCGA_table_frame <- data.frame(TCGA_genes)
TCGA_table <- TCGA_table_frame
setwd(wd)
file_list = c(list.files(pattern="*.counts"),list.files(pattern="*.txt"))
file_form <- NULL
for(f in file_list){
file_form <- c(file_form,unlist(strsplit(f, ".", fixed=TRUE))[2])
}
file_table <- data.frame(file_list, file_form)
#forms <- c("FPKM-UQ", "FPKM", "htseq")
forms <- "htseq"
print("*************************** file table done.")
for(form in forms){
print(paste0("*************************** format: @ ", form, " @ starts."))
file_list <- file_table[file_table$file_form==form,1]
file_num <- 0
error_files <- NULL
if(form == "htseq")
{
ref_index <- (ref_table$index)+5
}else
{
ref_index <- ref_table$index
}
# htseq have 5 more elements. Add 5 to index for move back reading frame.
for(i in 1:length(file_list)){
exp_file <- file(as.character(file_list[i]))
table_temp <- read.table(exp_file, header = FALSE)
table_temp <- table_temp[order(table_temp$V1), ]
table_temp <- table_temp[ref_index, ]
id_sets <-
strsplit(as.character(table_temp[, 1]), ".", fixed = TRUE)
ids <- NULL
for (k in 1:length(id_sets)) {
ids <- c(ids, unlist(id_sets[k])[1])
}
table_temp <- data.frame(ids, table_temp$V2)
names(table_temp) <- c("ids", as.character(file_list[i]))
if(isErrorfile(table_temp, gene_ids)){
error_files <- c(error_files, as.character(file_list[i]))
}else{
TCGA_table <- cbind(TCGA_table,table_temp[2])
names(TCGA_table)[length(TCGA_table[1,])] <- as.character(file_list[i])
}
print(paste0(i,"/",length(file_list)," file done."))
if(i%%100==0 || i==length(file_list)){
file_num <- file_num+1
file_name <- names(TCGA_table)[-1]
#log2 scale
maxs <- apply(TCGA_table[,-1],2,max)
not_log2_scale_ids <- names( which(maxs > 100 ) )
for(j in 1:length(not_log2_scale_ids)){
exception = TCGA_table[,not_log2_scale_ids[j]]<1
TCGA_table[exception,not_log2_scale_ids[j]] = 1
temp = log2(TCGA_table[,not_log2_scale_ids[j]])
TCGA_table[,not_log2_scale_ids[j]] = temp
}
print(paste0("*************************** ",as.character(file_num)," file log2 done."))
# Normalize
for(k in 2:dim(TCGA_table)[2]){
TCGA_table[,k] <- (TCGA_table[,k]-mean(TCGA_table[,k]))/sd(TCGA_table[,k])
}
print(paste0("*************************** ",as.character(file_num)," file normalized."))
# Transpose
TCGA_table <- data.frame(t(TCGA_table))
TCGA_table <- TCGA_table[-1,]
names(TCGA_table) <- TCGA_genes
TCGA_table <- cbind(file_name, TCGA_table)
print(paste0("*************************** ",as.character(file_num)," file transposed."))
# Add TCGA barcode
#barcode <- getBarcode(TCGA_table$file_name, "C:\\test\\merge_pro.csv")
barcode <- getBarcode(TCGA_table$file_name, "/home/tjahn/Git2/User/kyulhee/TCGA/merge_pro.csv")
TCGA_table <- cbind(TCGA_table, barcode)
print(paste0("*************************** ",as.character(file_num)," file added barcode."))
# Add Tumor result
result <- tumorDisc(TCGA_table$sample_id)
TCGA_table <- cbind(TCGA_table, result)
print(paste0("*************************** ",as.character(file_num)," file added result."))
# Write file(has 100 samples)
#csv_file_name = paste0(out, "\\TCGA_genes_",form,"_",as.character(file_num),".csv")
csv_file_name = paste0(out, "/TCGA_genes_",form,"_",as.character(file_num),".csv")
write.csv(TCGA_table, csv_file_name, row.names = FALSE)
print(paste0("*************************** ",as.character(file_num)," file written."))
#table initialization
TCGA_table <- TCGA_table_frame
}
}
if(length(error_files)>0){
print(paste0(form, " error file detect: ", length(error_files)))
#error_csv_name <- paste0(out, "\\TCGA_genes_",form,"_error",".csv")
error_csv_name <- paste0(out, "/TCGA_genes_",form,"_error",".csv")
write.csv(error_files, error_csv_name, row.names = FALSE)
}else{
print(paste0(form, " has no error file."))
}
}
}
#################################### check errors ####################################
isErrorfile <- function(table_temp, gene_ids){
error_switch <- 0
for (t in 1:length(table_temp$ids)) {
if (table_temp$ids[t] != gene_ids[t]){
print(paste0(
"@@@@@@@@@@@@@@@@@@@@@@@ Error detect! file: ",
names(table_temp)[2], table_temp$ids[t], "and", gene_ids[t]
))
error_switch <- error_switch+1
}
}
if(error_switch>0)
{
return(1)
}else
{
return(0)
}
}
#################################### getting TCGA barcode ####################################
getBarcode <- function(file_names, barcode_file){
barcode_ref <- read.csv(barcode_file)
barcode <- NULL
for(i in file_names){
barcode <- rbind(barcode, subset(barcode_ref, barcode_ref$file_name %in% i)[2:3] )
}
return(barcode)
}
#################################### discrimination Normal/Tumor ####################################
tumorDisc <- function(sample_id){
result <- as.integer(!(sample_id %in% 10:19))
# 01~09 -> tumor, 10~19 -> normal, 40 -> special tumor case
return(result)
}
#################################### Main ####################################
ref = "/home/tjahn/Git2/User/kyulhee/TCGA/hgnc_symbols_ref_inter.csv"
#ref = "C://test//hgnc_symbols_ref_inter.csv"
# where's "hgnc_symbols_ref_inter.csv" file?
wd = "/home/tjahn/GDC_Data/GeneExpression/Gene_txt_files"
#wd = "C://test//exp//error"
# where're expression files?
out = "/home/tjahn/GDC_Data/GeneExpression/Gene_txt_sum"
#out = "C://test//sam"
# output file space
handleData(ref,wd,out)
| /User/kyulhee/TCGA/Code/02-1.meRgefile_error.R | no_license | Chan-Hee/BioDataLab | R | false | false | 6,505 | r | #################################### read & merge datas ####################################
handleData <- function(ref, wd, out){
ref_table <- read.csv(ref, header=TRUE)
ref_table <- ref_table[unique(ref_table$Ensembl.ID.supplied.by.Ensembl.),]
TCGA_genes <- as.character(ref_table$Approved.Symbol)
gene_ids <- as.character(ref_table$Ensembl.ID.supplied.by.Ensembl.)
TCGA_table_frame <- data.frame(TCGA_genes)
TCGA_table <- TCGA_table_frame
setwd(wd)
file_list = c(list.files(pattern="*.counts"),list.files(pattern="*.txt"))
file_form <- NULL
for(f in file_list){
file_form <- c(file_form,unlist(strsplit(f, ".", fixed=TRUE))[2])
}
file_table <- data.frame(file_list, file_form)
#forms <- c("FPKM-UQ", "FPKM", "htseq")
forms <- "htseq"
print("*************************** file table done.")
for(form in forms){
print(paste0("*************************** format: @ ", form, " @ starts."))
file_list <- file_table[file_table$file_form==form,1]
file_num <- 0
error_files <- NULL
if(form == "htseq")
{
ref_index <- (ref_table$index)+5
}else
{
ref_index <- ref_table$index
}
# htseq have 5 more elements. Add 5 to index for move back reading frame.
for(i in 1:length(file_list)){
exp_file <- file(as.character(file_list[i]))
table_temp <- read.table(exp_file, header = FALSE)
table_temp <- table_temp[order(table_temp$V1), ]
table_temp <- table_temp[ref_index, ]
id_sets <-
strsplit(as.character(table_temp[, 1]), ".", fixed = TRUE)
ids <- NULL
for (k in 1:length(id_sets)) {
ids <- c(ids, unlist(id_sets[k])[1])
}
table_temp <- data.frame(ids, table_temp$V2)
names(table_temp) <- c("ids", as.character(file_list[i]))
if(isErrorfile(table_temp, gene_ids)){
error_files <- c(error_files, as.character(file_list[i]))
}else{
TCGA_table <- cbind(TCGA_table,table_temp[2])
names(TCGA_table)[length(TCGA_table[1,])] <- as.character(file_list[i])
}
print(paste0(i,"/",length(file_list)," file done."))
if(i%%100==0 || i==length(file_list)){
file_num <- file_num+1
file_name <- names(TCGA_table)[-1]
#log2 scale
maxs <- apply(TCGA_table[,-1],2,max)
not_log2_scale_ids <- names( which(maxs > 100 ) )
for(j in 1:length(not_log2_scale_ids)){
exception = TCGA_table[,not_log2_scale_ids[j]]<1
TCGA_table[exception,not_log2_scale_ids[j]] = 1
temp = log2(TCGA_table[,not_log2_scale_ids[j]])
TCGA_table[,not_log2_scale_ids[j]] = temp
}
print(paste0("*************************** ",as.character(file_num)," file log2 done."))
# Normalize
for(k in 2:dim(TCGA_table)[2]){
TCGA_table[,k] <- (TCGA_table[,k]-mean(TCGA_table[,k]))/sd(TCGA_table[,k])
}
print(paste0("*************************** ",as.character(file_num)," file normalized."))
# Transpose
TCGA_table <- data.frame(t(TCGA_table))
TCGA_table <- TCGA_table[-1,]
names(TCGA_table) <- TCGA_genes
TCGA_table <- cbind(file_name, TCGA_table)
print(paste0("*************************** ",as.character(file_num)," file transposed."))
# Add TCGA barcode
#barcode <- getBarcode(TCGA_table$file_name, "C:\\test\\merge_pro.csv")
barcode <- getBarcode(TCGA_table$file_name, "/home/tjahn/Git2/User/kyulhee/TCGA/merge_pro.csv")
TCGA_table <- cbind(TCGA_table, barcode)
print(paste0("*************************** ",as.character(file_num)," file added barcode."))
# Add Tumor result
result <- tumorDisc(TCGA_table$sample_id)
TCGA_table <- cbind(TCGA_table, result)
print(paste0("*************************** ",as.character(file_num)," file added result."))
# Write file(has 100 samples)
#csv_file_name = paste0(out, "\\TCGA_genes_",form,"_",as.character(file_num),".csv")
csv_file_name = paste0(out, "/TCGA_genes_",form,"_",as.character(file_num),".csv")
write.csv(TCGA_table, csv_file_name, row.names = FALSE)
print(paste0("*************************** ",as.character(file_num)," file written."))
#table initialization
TCGA_table <- TCGA_table_frame
}
}
if(length(error_files)>0){
print(paste0(form, " error file detect: ", length(error_files)))
#error_csv_name <- paste0(out, "\\TCGA_genes_",form,"_error",".csv")
error_csv_name <- paste0(out, "/TCGA_genes_",form,"_error",".csv")
write.csv(error_files, error_csv_name, row.names = FALSE)
}else{
print(paste0(form, " has no error file."))
}
}
}
#################################### check errors ####################################
isErrorfile <- function(table_temp, gene_ids){
error_switch <- 0
for (t in 1:length(table_temp$ids)) {
if (table_temp$ids[t] != gene_ids[t]){
print(paste0(
"@@@@@@@@@@@@@@@@@@@@@@@ Error detect! file: ",
names(table_temp)[2], table_temp$ids[t], "and", gene_ids[t]
))
error_switch <- error_switch+1
}
}
if(error_switch>0)
{
return(1)
}else
{
return(0)
}
}
#################################### getting TCGA barcode ####################################
getBarcode <- function(file_names, barcode_file){
barcode_ref <- read.csv(barcode_file)
barcode <- NULL
for(i in file_names){
barcode <- rbind(barcode, subset(barcode_ref, barcode_ref$file_name %in% i)[2:3] )
}
return(barcode)
}
#################################### discrimination Normal/Tumor ####################################
tumorDisc <- function(sample_id){
result <- as.integer(!(sample_id %in% 10:19))
# 01~09 -> tumor, 10~19 -> normal, 40 -> special tumor case
return(result)
}
#################################### Main ####################################
ref = "/home/tjahn/Git2/User/kyulhee/TCGA/hgnc_symbols_ref_inter.csv"
#ref = "C://test//hgnc_symbols_ref_inter.csv"
# where's "hgnc_symbols_ref_inter.csv" file?
wd = "/home/tjahn/GDC_Data/GeneExpression/Gene_txt_files"
#wd = "C://test//exp//error"
# where're expression files?
out = "/home/tjahn/GDC_Data/GeneExpression/Gene_txt_sum"
#out = "C://test//sam"
# output file space
handleData(ref,wd,out)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/parse_snps.R
\name{parse_snps}
\alias{parse_snps}
\title{Parse SNP matrix from Ali's pipeline}
\usage{
parse_snps(
varmat_code,
varmat_allele,
tree = NULL,
og = NULL,
remove_multi_annots = FALSE,
return_binary_matrix = TRUE,
ref_to_anc = TRUE,
keep_conf_only = TRUE,
mat_suffix = "_R1_001.fastq.gz|_R1.fastq.gz|_1.fastq.gz"
)
}
\arguments{
\item{varmat_code}{Loaded data.frame or path to the varmat_code file
generated from internal variant calling pipeline}
\item{varmat_allele}{Loaded data.frame or path to the varmat_allele file
generated from internal variant calling pipeline}
\item{tree}{Optional: path to tree file or loaded in tree (class = phylo)}
\item{og}{Optional: character string of the name of the outgroup (has to
match what it is called in the tree)}
\item{remove_multi_annots}{Logical flag indicating if you want to remove
rows with multiple annotations - alternative is to split rows with mutliple
annotations (default = FALSE)}
\item{return_binary_matrix}{Logical flag indicating if you want to return a
binary matrix (default = TRUE)}
\item{ref_to_anc}{Whether to reference to the ancestral allele to create the binary marix (default = TRUE)}
\item{keep_conf_only}{Logical flag indicating if only confident variants should be kept (1's in Ali's pipeline, otherwise 3's are also kept) (default = TRUE)}
\item{mat_suffix}{Suffix to remove from code and allele matrices so the names match with the tree tip labels.}
}
\value{
list of allele mat, code mat, binary mat and corresponding parsed
annotations. output will depend on arguments to the function.
}
\description{
Input matrices generated from internal (Ali's) variant calling
pipeline. Always returns parsed annotation info. In addition, you have the
option to: 1. split rows with multiple annotations (snps in overlapping
genes, multiallelic snps) 2. Re-reference to the ancestral allele at that
position (instead of to the reference genome) 3. Simplify the code matrix -
which contains numbers from -4 to 3 indicating different information about
the variants - to a binary matrix indicating simple presence/absence of a
SNP at that site.
}
| /man/parse_snps.Rd | permissive | wangdi2014/snitkitr | R | false | true | 2,237 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/parse_snps.R
\name{parse_snps}
\alias{parse_snps}
\title{Parse SNP matrix from Ali's pipeline}
\usage{
parse_snps(
varmat_code,
varmat_allele,
tree = NULL,
og = NULL,
remove_multi_annots = FALSE,
return_binary_matrix = TRUE,
ref_to_anc = TRUE,
keep_conf_only = TRUE,
mat_suffix = "_R1_001.fastq.gz|_R1.fastq.gz|_1.fastq.gz"
)
}
\arguments{
\item{varmat_code}{Loaded data.frame or path to the varmat_code file
generated from internal variant calling pipeline}
\item{varmat_allele}{Loaded data.frame or path to the varmat_allele file
generated from internal variant calling pipeline}
\item{tree}{Optional: path to tree file or loaded in tree (class = phylo)}
\item{og}{Optional: character string of the name of the outgroup (has to
match what it is called in the tree)}
\item{remove_multi_annots}{Logical flag indicating if you want to remove
rows with multiple annotations - alternative is to split rows with mutliple
annotations (default = FALSE)}
\item{return_binary_matrix}{Logical flag indicating if you want to return a
binary matrix (default = TRUE)}
\item{ref_to_anc}{Whether to reference to the ancestral allele to create the binary marix (default = TRUE)}
\item{keep_conf_only}{Logical flag indicating if only confident variants should be kept (1's in Ali's pipeline, otherwise 3's are also kept) (default = TRUE)}
\item{mat_suffix}{Suffix to remove from code and allele matrices so the names match with the tree tip labels.}
}
\value{
list of allele mat, code mat, binary mat and corresponding parsed
annotations. output will depend on arguments to the function.
}
\description{
Input matrices generated from internal (Ali's) variant calling
pipeline. Always returns parsed annotation info. In addition, you have the
option to: 1. split rows with multiple annotations (snps in overlapping
genes, multiallelic snps) 2. Re-reference to the ancestral allele at that
position (instead of to the reference genome) 3. Simplify the code matrix -
which contains numbers from -4 to 3 indicating different information about
the variants - to a binary matrix indicating simple presence/absence of a
SNP at that site.
}
|
##creamos un script
a<- c(1,2,3,4) | /Script.R | no_license | Lolaalvarez/ecoinfo_2014_2015_reto_4_1 | R | false | false | 34 | r | ##creamos un script
a<- c(1,2,3,4) |
#' Download and install dependencies
#'
#' When called in the repo of an R package, its package dependencies are inspected
#' and the obsolete ones are updated. This function is a thin wrapper around
#' \code{stats::update(remotes::dev_package_deps())}. Unlike the 'Update' button in RStudio's 'Packages' panel,
#' this function will (a) update from CRAN and remote sources like GitHub and
#' (b) not attempt to install local packages that are unrelated to the current package.
#'
#' @export
updatePackagesAddin <- function() {
stats::update(remotes::dev_package_deps())
}
| /R/updatePackagesAddin.R | no_license | wibeasley/addinexamples | R | false | false | 577 | r | #' Download and install dependencies
#'
#' When called in the repo of an R package, its package dependencies are inspected
#' and the obsolete ones are updated. This function is a thin wrapper around
#' \code{stats::update(remotes::dev_package_deps())}. Unlike the 'Update' button in RStudio's 'Packages' panel,
#' this function will (a) update from CRAN and remote sources like GitHub and
#' (b) not attempt to install local packages that are unrelated to the current package.
#'
#' @export
updatePackagesAddin <- function() {
stats::update(remotes::dev_package_deps())
}
|
# R-functions used when filtering normalized expression data
# by Boel Brynedal
filtIQR=function(Exp,prob1) {
iqr=apply(Exp,1, function(x) IQR(x, na.rm = TRUE))
mmIQR <- Mclust(iqr, G=2)
filt=vector('logical',length=nrow(Exp))
filt[which(mmIQR$z[,2]>=prob1)]=T
return(filt) }
filtE=function(Exp,prob2) {
mE=apply(Exp,1, mean)
mmE <- Mclust(mE, G=2)
filt=vector('logical',length=nrow(Exp))
filt[which(mmE$z[,2]>=prob2)]=T
return(filt) }
reduceFilt=function(filt1,filt2) {
return(Reduce('|',list(filt1,filt2))) }
| /filtFun.R | no_license | cotsapaslab/CPMAtranseqtl | R | false | false | 521 | r | # R-functions used when filtering normalized expression data
# by Boel Brynedal
filtIQR=function(Exp,prob1) {
iqr=apply(Exp,1, function(x) IQR(x, na.rm = TRUE))
mmIQR <- Mclust(iqr, G=2)
filt=vector('logical',length=nrow(Exp))
filt[which(mmIQR$z[,2]>=prob1)]=T
return(filt) }
filtE=function(Exp,prob2) {
mE=apply(Exp,1, mean)
mmE <- Mclust(mE, G=2)
filt=vector('logical',length=nrow(Exp))
filt[which(mmE$z[,2]>=prob2)]=T
return(filt) }
reduceFilt=function(filt1,filt2) {
return(Reduce('|',list(filt1,filt2))) }
|
### pulls in several ESI geodatabases from
### https://response.restoration.noaa.gov/esi_download
rm(list=ls())
library(sp)
library(sf)
library(rgdal)
### ESI dataset - central California
fgdb = "data/CentralCal_2006_GDB/CentralCaliforniaESI.gdb/"
fc = readOGR(dsn=fgdb,verbose = T,layer = 'esil_arc')
latlon <- c()
ID <- c()
for (i in 1:length(fc@lines))
{
tmp <- data.frame(coordinates(fc@lines[[i]]))
latlon <- rbind(latlon,tmp)
ID <- c(ID,rep(fc@lines[[i]]@ID,dim(tmp)[1]))
}
out <- data.frame(lon=latlon[,1],lat=latlon[,2],ID=as.numeric(ID))
out$Landward_shoretype <- fc@data[match(out$ID,rownames(fc@data)),"Landward_shoretype"]
out$ESI <- fc@data[match(out$ID,rownames(fc@data)),"ESI"]
### remove "LINES" with estuarine codes
#out2 <- out[!(out$Landward_shoretype%in%c(
# "10A: Salt and Brackish Water Marshes",
# "10B: Freshwater Marshes",
# "10D: Scrub and Shrub Wetlands",
# "8A: Sheltered, Impermeable, Rocky Shores",
# "8B: Sheltered, Solid Man-Made Structures",
# "8C: Sheltered Riprap",
# "9A: Sheltered Tidal Flats",
# "9B: Vegetated Low Banks")),]
out2 <- out[!(out$ESI%in%c("7","8A","8B","8C","8F","9A","9B")),]
### write
write.csv(out2,file="output/centralCal.csv",quote = F,row.names = F)
### ESI dataset - Northern California
fgdb = "data/NorthernCal_2008_GDB/NorthernCaliforniaESI.gdb/"
fc = readOGR(dsn=fgdb,verbose = T,layer = 'esil')
latlon <- c()
ID <- c()
for (i in 1:length(fc@lines))
{
tmp <- data.frame(coordinates(fc@lines[[i]]))
latlon <- rbind(latlon,tmp)
ID <- c(ID,rep(fc@lines[[i]]@ID,dim(tmp)[1]))
}
out <- data.frame(lon=latlon[,1],lat=latlon[,2],ID=as.numeric(ID))
out$Landward_shoretype <- fc@data[match(out$ID,rownames(fc@data)),"Landward_shoretype"]
out$ESI <- fc@data[match(out$ID,rownames(fc@data)),"ESI"]
### remove "LINES" with estuarine codes
#out2 <- out[!(out$Landward_shoretype%in%c(
# "10A: Salt and Brackish Water Marshes",
# "10B: Freshwater Marshes",
# "10D: Scrub and Shrub Wetlands",
# "8A: Sheltered, Impermeable, Rocky Shores",
# "8B: Sheltered, Solid Man-Made Structures",
# "8C: Sheltered Riprap",
# "9A: Sheltered Tidal Flats",
# "9B: Vegetated Low Banks")),]
out2 <- out[!(out$ESI%in%c("7","8A","8B","8C","8F","9A","9B")),]
### write
write.csv(out2,file="output/northernCal.csv",quote = F,row.names = F)
### ESI dataset - Southern California
fgdb = "data/SouthernCal_2010_GDB/SouthernCaliforniaESI.gdb/"
fc = readOGR(dsn=fgdb,verbose = T,layer = 'esi_arc')
latlon <- c()
ID <- c()
for (i in 1:length(fc@lines))
{
tmp <- data.frame(coordinates(fc@lines[[i]]))
latlon <- rbind(latlon,tmp)
ID <- c(ID,rep(fc@lines[[i]]@ID,dim(tmp)[1]))
}
out <- data.frame(lon=latlon[,1],lat=latlon[,2],ID=as.numeric(ID))
out$Landward_shoretype <- fc@data[match(out$ID,rownames(fc@data)),"Landward_shoretype"]
out$ESI <- fc@data[match(out$ID,rownames(fc@data)),"ESI"]
### remove "LINES" with estuarine codes
#out2 <- out[!(out$Landward_shoretype%in%c(
# "10A: Salt and Brackish Water Marshes",
# "10B: Freshwater Marshes",
# "10D: Scrub and Shrub Wetlands",
# "8A: Sheltered, Impermeable, Rocky Shores",
# "8B: Sheltered, Solid Man-Made Structures",
# "8C: Sheltered Riprap",
# "9A: Sheltered Tidal Flats",
# "9B: Vegetated Low Banks")),]
out2 <- out[!(out$ESI%in%c("7","8A","8B","8C","8F","9A","9B")),]
### write
write.csv(out2,file="output/southernCal.csv",quote = F,row.names = F)
| /R/read.ESI.data.R | no_license | esotka/BalanusGlandula | R | false | false | 3,382 | r | ### pulls in several ESI geodatabases from
### https://response.restoration.noaa.gov/esi_download
rm(list=ls())
library(sp)
library(sf)
library(rgdal)
### ESI dataset - central California
fgdb = "data/CentralCal_2006_GDB/CentralCaliforniaESI.gdb/"
fc = readOGR(dsn=fgdb,verbose = T,layer = 'esil_arc')
latlon <- c()
ID <- c()
for (i in 1:length(fc@lines))
{
tmp <- data.frame(coordinates(fc@lines[[i]]))
latlon <- rbind(latlon,tmp)
ID <- c(ID,rep(fc@lines[[i]]@ID,dim(tmp)[1]))
}
out <- data.frame(lon=latlon[,1],lat=latlon[,2],ID=as.numeric(ID))
out$Landward_shoretype <- fc@data[match(out$ID,rownames(fc@data)),"Landward_shoretype"]
out$ESI <- fc@data[match(out$ID,rownames(fc@data)),"ESI"]
### remove "LINES" with estuarine codes
#out2 <- out[!(out$Landward_shoretype%in%c(
# "10A: Salt and Brackish Water Marshes",
# "10B: Freshwater Marshes",
# "10D: Scrub and Shrub Wetlands",
# "8A: Sheltered, Impermeable, Rocky Shores",
# "8B: Sheltered, Solid Man-Made Structures",
# "8C: Sheltered Riprap",
# "9A: Sheltered Tidal Flats",
# "9B: Vegetated Low Banks")),]
out2 <- out[!(out$ESI%in%c("7","8A","8B","8C","8F","9A","9B")),]
### write
write.csv(out2,file="output/centralCal.csv",quote = F,row.names = F)
### ESI dataset - Northern California
fgdb = "data/NorthernCal_2008_GDB/NorthernCaliforniaESI.gdb/"
fc = readOGR(dsn=fgdb,verbose = T,layer = 'esil')
latlon <- c()
ID <- c()
for (i in 1:length(fc@lines))
{
tmp <- data.frame(coordinates(fc@lines[[i]]))
latlon <- rbind(latlon,tmp)
ID <- c(ID,rep(fc@lines[[i]]@ID,dim(tmp)[1]))
}
out <- data.frame(lon=latlon[,1],lat=latlon[,2],ID=as.numeric(ID))
out$Landward_shoretype <- fc@data[match(out$ID,rownames(fc@data)),"Landward_shoretype"]
out$ESI <- fc@data[match(out$ID,rownames(fc@data)),"ESI"]
### remove "LINES" with estuarine codes
#out2 <- out[!(out$Landward_shoretype%in%c(
# "10A: Salt and Brackish Water Marshes",
# "10B: Freshwater Marshes",
# "10D: Scrub and Shrub Wetlands",
# "8A: Sheltered, Impermeable, Rocky Shores",
# "8B: Sheltered, Solid Man-Made Structures",
# "8C: Sheltered Riprap",
# "9A: Sheltered Tidal Flats",
# "9B: Vegetated Low Banks")),]
out2 <- out[!(out$ESI%in%c("7","8A","8B","8C","8F","9A","9B")),]
### write
write.csv(out2,file="output/northernCal.csv",quote = F,row.names = F)
### ESI dataset - Southern California
fgdb = "data/SouthernCal_2010_GDB/SouthernCaliforniaESI.gdb/"
fc = readOGR(dsn=fgdb,verbose = T,layer = 'esi_arc')
latlon <- c()
ID <- c()
for (i in 1:length(fc@lines))
{
tmp <- data.frame(coordinates(fc@lines[[i]]))
latlon <- rbind(latlon,tmp)
ID <- c(ID,rep(fc@lines[[i]]@ID,dim(tmp)[1]))
}
out <- data.frame(lon=latlon[,1],lat=latlon[,2],ID=as.numeric(ID))
out$Landward_shoretype <- fc@data[match(out$ID,rownames(fc@data)),"Landward_shoretype"]
out$ESI <- fc@data[match(out$ID,rownames(fc@data)),"ESI"]
### remove "LINES" with estuarine codes
#out2 <- out[!(out$Landward_shoretype%in%c(
# "10A: Salt and Brackish Water Marshes",
# "10B: Freshwater Marshes",
# "10D: Scrub and Shrub Wetlands",
# "8A: Sheltered, Impermeable, Rocky Shores",
# "8B: Sheltered, Solid Man-Made Structures",
# "8C: Sheltered Riprap",
# "9A: Sheltered Tidal Flats",
# "9B: Vegetated Low Banks")),]
out2 <- out[!(out$ESI%in%c("7","8A","8B","8C","8F","9A","9B")),]
### write
write.csv(out2,file="output/southernCal.csv",quote = F,row.names = F)
|
#!/usr/bin/env Rscript
# sbdiexportreannotate.R
#
# A script that collates taxonomy data from Ampliseq to produce an updated
# annotation tsv file as close to ready for submission to the Swedish
# Biodiversity Data Infrastructure (SBDI) as possible.
#
# The script expects the following arguments: dbversion, ASV_tax_species.tsv
#
# Author: daniel.lundin@lnu.se
suppressPackageStartupMessages(library(tidyverse))
# Get dbversion and taxonomy file from the command line
args <- commandArgs(trailingOnly=TRUE)
dbversion <- args[1]
taxfile <- args[2]
taxonomy <- read.delim(taxfile, sep = '\t', stringsAsFactors = FALSE)
taxonomy %>%
mutate(SH = if("SH" %in% colnames(.)) SH else '') %>%
relocate(SH, .after = Species) %>%
rename_with(tolower, Domain:Species) %>%
rename(
asv_id_alias = ASV_ID,
asv_sequence = sequence,
specificEpithet = species,
otu = SH,
annotation_confidence = confidence
) %>%
mutate(
infraspecificEpithet = '',
domain = str_remove(domain, 'Reversed:_'),
scientificName = case_when(
!(is.na(specificEpithet) | specificEpithet == '') ~ sprintf("%s %s", genus, specificEpithet),
!(is.na(genus) | genus == '') ~ sprintf("%s", genus),
!(is.na(family) | family == '') ~ sprintf("%s", family),
!(is.na(order) | order == '') ~ sprintf("%s", order),
!(is.na(class) | class == '') ~ sprintf("%s", class),
!(is.na(phylum) | phylum == '') ~ sprintf("%s", phylum),
!(is.na(kingdom) | kingdom == '') ~ sprintf("%s", kingdom),
TRUE ~ 'Unassigned'
),
taxonRank = case_when(
!(is.na(specificEpithet) | specificEpithet == '') ~ 'species',
!(is.na(genus) | genus == '') ~ 'genus',
!(is.na(family) | family == '') ~ 'family',
!(is.na(order) | order == '') ~ 'order',
!(is.na(class) | class == '') ~ 'class',
!(is.na(phylum) | phylum == '') ~ 'phylum',
!(is.na(kingdom) | kingdom == '') ~ 'kingdom',
TRUE ~ 'kingdom'
),
date_identified = as.character(lubridate::today()),
reference_db = dbversion,
annotation_algorithm = case_when(
(!(is.na(otu) | otu == '')) ~ 'Ampliseq:addsh',
TRUE ~ 'DADA2:assignTaxonomy:addSpecies'
),
identification_references = 'https://docs.biodiversitydata.se/analyse-data/molecular-tools/#taxonomy-annotation',
taxon_remarks = '',
kingdom = ifelse(is.na(kingdom), 'Unassigned', kingdom)
) %>%
relocate(asv_sequence, .after = asv_id_alias) %>%
relocate(infraspecificEpithet:identification_references, .after = specificEpithet) %>%
relocate(otu, .after = infraspecificEpithet) %>%
select(-domain) %>%
write_tsv("annotation.tsv", na = '')
| /bin/sbdiexportreannotate.R | permissive | erikrikarddaniel/ampliseq | R | false | false | 3,236 | r | #!/usr/bin/env Rscript
# sbdiexportreannotate.R
#
# A script that collates taxonomy data from Ampliseq to produce an updated
# annotation tsv file as close to ready for submission to the Swedish
# Biodiversity Data Infrastructure (SBDI) as possible.
#
# The script expects the following arguments: dbversion, ASV_tax_species.tsv
#
# Author: daniel.lundin@lnu.se
suppressPackageStartupMessages(library(tidyverse))
# Get dbversion and taxonomy file from the command line
args <- commandArgs(trailingOnly=TRUE)
dbversion <- args[1]
taxfile <- args[2]
taxonomy <- read.delim(taxfile, sep = '\t', stringsAsFactors = FALSE)
taxonomy %>%
mutate(SH = if("SH" %in% colnames(.)) SH else '') %>%
relocate(SH, .after = Species) %>%
rename_with(tolower, Domain:Species) %>%
rename(
asv_id_alias = ASV_ID,
asv_sequence = sequence,
specificEpithet = species,
otu = SH,
annotation_confidence = confidence
) %>%
mutate(
infraspecificEpithet = '',
domain = str_remove(domain, 'Reversed:_'),
scientificName = case_when(
!(is.na(specificEpithet) | specificEpithet == '') ~ sprintf("%s %s", genus, specificEpithet),
!(is.na(genus) | genus == '') ~ sprintf("%s", genus),
!(is.na(family) | family == '') ~ sprintf("%s", family),
!(is.na(order) | order == '') ~ sprintf("%s", order),
!(is.na(class) | class == '') ~ sprintf("%s", class),
!(is.na(phylum) | phylum == '') ~ sprintf("%s", phylum),
!(is.na(kingdom) | kingdom == '') ~ sprintf("%s", kingdom),
TRUE ~ 'Unassigned'
),
taxonRank = case_when(
!(is.na(specificEpithet) | specificEpithet == '') ~ 'species',
!(is.na(genus) | genus == '') ~ 'genus',
!(is.na(family) | family == '') ~ 'family',
!(is.na(order) | order == '') ~ 'order',
!(is.na(class) | class == '') ~ 'class',
!(is.na(phylum) | phylum == '') ~ 'phylum',
!(is.na(kingdom) | kingdom == '') ~ 'kingdom',
TRUE ~ 'kingdom'
),
date_identified = as.character(lubridate::today()),
reference_db = dbversion,
annotation_algorithm = case_when(
(!(is.na(otu) | otu == '')) ~ 'Ampliseq:addsh',
TRUE ~ 'DADA2:assignTaxonomy:addSpecies'
),
identification_references = 'https://docs.biodiversitydata.se/analyse-data/molecular-tools/#taxonomy-annotation',
taxon_remarks = '',
kingdom = ifelse(is.na(kingdom), 'Unassigned', kingdom)
) %>%
relocate(asv_sequence, .after = asv_id_alias) %>%
relocate(infraspecificEpithet:identification_references, .after = specificEpithet) %>%
relocate(otu, .after = infraspecificEpithet) %>%
select(-domain) %>%
write_tsv("annotation.tsv", na = '')
|
existing_product_attributes <- read.csv(paste("https://github.com/pvpgit/Predicting-Sales-Volume/tree/master/existing_product_attributes.csv", sep=""), header = TRUE)
install.packages("e1071")
library("e1071")
existing_product_attributes$"X.Product.Type." <- NULL
existing_product_attributes$"X.Best.Sellers.Rank." <- NULL
existing_product_attributes$"X.5.Star.Reviews." <- NULL
str(existing_product_attributes)
trainsize<-round(nrow(existing_product_attributes)*0.7)
testsize<-nrow(existing_product_attributes) - trainsize
trainsize
testsize
set.seed((123))
training_indices<-sample(seq_len(nrow(existing_product_attributes)),size=trainsize)
trainset<-existing_product_attributes[training_indices,]
testset<-existing_product_attributes[-training_indices,]
training_indices
##1st model kernel=polynomial
modelsvmpoly<-svm(Volume ~ ., existing_product_attributes, type="C-classification",
ranges=list(cost=10^(-1:2),gamma=c(0.5,1,2)), kernel="polynomial")
modelsvmpoly
tunepoly<-tune(svm,Volume ~ ., data=testset,
ranges =list(cost=10^(-1:2),gamma=c(.5,1,2)))
tunepoly
##2nd model kernel=radial
##modelsvmradial<-svm(Volume ~ ., existing_product_attributes, type="C-classification",
## ranges=list(cost=10^(-1:2),gamma=c(0.5,1,2)), kernel="radial")
##modelsvmradial
##tuneradial<-tune(svm,Volume ~ ., data=testset,
## ranges =list(cost=10^(-1:2),gamma=c(.5,1,2)))
##tuneradial
svm_model_after_tunepoly <- svm(Volume ~ ., existing_product_attributes,
kernel="polynomial", cost=1, gamma=0.5)
summary(svm_model_after_tunepoly)
##svm_model_after_tuneradial <- svm(Volume ~ ., existing_product_attributes,
## kernel="radial", cost=1, gamma=0.5)
##summary(svm_model_after_tuneradial)
##Preprocess the new data
new_product_attributes <- read.csv(paste("https://github.com/pvpgit/Predicting-Sales-Volume/tree/master/new_product_attributes.csv",
sep=""), header = TRUE)
new_product_attributes$"X.Product.Type." <- NULL
new_product_attributes$"X.Best.Sellers.Rank." <- NULL
new_product_attributes$"X.5.Star.Reviews." <- NULL
predpoly<-predict(svm_model_after_tunepoly,new_product_attributes)
system.time(predict(svm_model_after_tunepoly,new_product_attributes))
predpoly
##predradial<-predict(svm_model_after_tuneradial,new_product_attributes)
##system.time(predict(svm_model_after_tuneradial,new_product_attributes))
##predradial
| /SVM.R | no_license | pvpgit/Predicting-Sales-Volume | R | false | false | 2,438 | r | existing_product_attributes <- read.csv(paste("https://github.com/pvpgit/Predicting-Sales-Volume/tree/master/existing_product_attributes.csv", sep=""), header = TRUE)
install.packages("e1071")
library("e1071")
existing_product_attributes$"X.Product.Type." <- NULL
existing_product_attributes$"X.Best.Sellers.Rank." <- NULL
existing_product_attributes$"X.5.Star.Reviews." <- NULL
str(existing_product_attributes)
trainsize<-round(nrow(existing_product_attributes)*0.7)
testsize<-nrow(existing_product_attributes) - trainsize
trainsize
testsize
set.seed((123))
training_indices<-sample(seq_len(nrow(existing_product_attributes)),size=trainsize)
trainset<-existing_product_attributes[training_indices,]
testset<-existing_product_attributes[-training_indices,]
training_indices
##1st model kernel=polynomial
modelsvmpoly<-svm(Volume ~ ., existing_product_attributes, type="C-classification",
ranges=list(cost=10^(-1:2),gamma=c(0.5,1,2)), kernel="polynomial")
modelsvmpoly
tunepoly<-tune(svm,Volume ~ ., data=testset,
ranges =list(cost=10^(-1:2),gamma=c(.5,1,2)))
tunepoly
##2nd model kernel=radial
##modelsvmradial<-svm(Volume ~ ., existing_product_attributes, type="C-classification",
## ranges=list(cost=10^(-1:2),gamma=c(0.5,1,2)), kernel="radial")
##modelsvmradial
##tuneradial<-tune(svm,Volume ~ ., data=testset,
## ranges =list(cost=10^(-1:2),gamma=c(.5,1,2)))
##tuneradial
svm_model_after_tunepoly <- svm(Volume ~ ., existing_product_attributes,
kernel="polynomial", cost=1, gamma=0.5)
summary(svm_model_after_tunepoly)
##svm_model_after_tuneradial <- svm(Volume ~ ., existing_product_attributes,
## kernel="radial", cost=1, gamma=0.5)
##summary(svm_model_after_tuneradial)
##Preprocess the new data
new_product_attributes <- read.csv(paste("https://github.com/pvpgit/Predicting-Sales-Volume/tree/master/new_product_attributes.csv",
sep=""), header = TRUE)
new_product_attributes$"X.Product.Type." <- NULL
new_product_attributes$"X.Best.Sellers.Rank." <- NULL
new_product_attributes$"X.5.Star.Reviews." <- NULL
predpoly<-predict(svm_model_after_tunepoly,new_product_attributes)
system.time(predict(svm_model_after_tunepoly,new_product_attributes))
predpoly
##predradial<-predict(svm_model_after_tuneradial,new_product_attributes)
##system.time(predict(svm_model_after_tuneradial,new_product_attributes))
##predradial
|
# Use the "norm" package downloaded from CRAN to
# carry out proper multiple imputation using a
# multivariate normal model to impute on the
# bivariate normal data
#
# install.packages("norm") and choose a mirror site
#
# Visit the CRAN website for the documentation
# Load the libary for the norm package
library(norm)
library(nlme)
# number of imputed data sets
M <- 10
# Read in the data set -- the missing values are denoted
# by the usual R convention NA
# The norm wants the data in a matrix, so we read it in
# directly to a matrix
datamat <- matrix(scan("bvnormal.R.dat"),ncol=2,byrow=TRUE)
N <- nrow(datamat)
nvar <- ncol(datamat)
# Run prelim.norm() to set up the data for the algorithm
prelim.mi <- prelim.norm(datamat)
# Look at the numbers of missing values and missing data patterns
prelim.mi$nmis
prelim.mi$r
# This produces
# > prelim.mi$nmis
# [1] 214 238
#
#> prelim.mi$r
# [,1] [,2]
# 548 1 1
# 214 0 1
# 238 1 0
# Run the EM algorithm initially with the default settings to
# get the form of the starting values
theta.init <- em.norm(prelim.mi,showits=FALSE)
# Extract the parameters so you can see the format
theta.init <- getparam.norm(prelim.mi,theta.init,corr=TRUE)
theta.init$mu # the mean vector
theta.init$sdv # the standard deviations
theta.init$r # the correlation matrix
# Convert these to the form used by the function em.norm
theta.init <- makeparam.norm(prelim.mi,theta.init)
# Create M imputed data sets using proper imputation
# and carry out the desired analysis on each one; save
# them in a big matrix in case you want to use them
# for something else
imputed.data <- NULL
# the mi.inference function wants the parameters and their
# standard errors saved in lists. We'll also save the full
# asymptotic covariance matrices for use with our own multivariate
# mi inference function below
mu.list <- vector("list",M)
ses.list <- vector("list",M)
covs.list <- vector("list",M)
covparms.list <- vector("list",M)
# Set the seed for the MCMC
rngseed(82)
for (m in 1:M){
# Impute the missing values to create a single data set using MCMC.
# Use the da.norm (for "data augmentation") function in the norm package
# to impute the missing values. Here, steps is apparently the number
# of iterations in the chain between draws - the documentation does not give
# details, and it is not clear if there is a burn-in period
imp.dat <- da.norm(prelim.mi,theta.init,steps=200,return.ymis=TRUE)
# misobs is a vector containing the imputed missing values in the order
# they are missing in the original data set, so insert them into a copy
# of the original data set.
misobs <- imp.dat$ymis
this.imp <- datamat
this.imp[is.na(this.imp)] <- misobs
# Save this imputed data set in case you want to do other stuff with it
imputed.data <- rbind(imputed.data,this.imp)
# Reconfigure the imputed data set to 1 record per observation
# for use with gls()
this.imp.alt <- NULL
for (i in 1:N){
this <-cbind(rep(i,nvar),seq(1,nvar,1),this.imp[i,1:2,drop=TRUE])
this.imp.alt <- rbind(this.imp.alt,this)
}
# Call gls() to fit the multivariate normal model to the reconfigured
# imputed data set
id <- factor(this.imp.alt[,1])
ind <- factor(this.imp.alt[,2])
y <- this.imp.alt[,3]
time <- rep(seq(1,2,1),N)
gls.fit <- gls(y ~ -1 + ind,correlation=corSymm(form = ~time | id),
weights=varIdent(form= ~1 | ind),method="ML")
# Get the estimates of the mean parameters and their standard errors
# and also the full asymptotic covariance matrices
this.mu <- gls.fit$coef
this.ses <- sqrt(diag(gls.fit$varBeta))
this.cov <- gls.fit$varBeta
# Save these in the lists, as the mi.inference function
# requires that the parameter estimates from each imputed data set and
# their standard errors be in lists
mu.list[[m]] <- this.mu
ses.list[[m]] <- this.ses
covs.list[[m]] <- this.cov
# Save the estimates of the variance and covariance parameters
this.covmat <- getVarCov(gls.fit)
this.covparms <- c(this.covmat[1,1],this.covmat[1,2],this.covmat[2,2])
covparms.list[[m]] <- this.covparms
# Unfortunately, getting their standard errors is hard -- they are computed
# but are available in a different (and not clear) parameterization via
# gls.fit$apVar
# We won't bother trying to extract them; usually these aren't of
# interest anyway
}
# Now call the function mi.inference() to obtain the multiple
# imputation estimate for mu and the ses via Rubin's formula. This
# function requires the parameters and their standard errors to be in
# lists, as noted aboe
mi.mu <- mi.inference(mu.list,ses.list,confidence=0.95) # confidence=0.95 is the default
# Display the results in the same format as SAS proc mianalyze
mu.imp <- simplify2array(mu.list)
mi.results <- cbind(mi.mu$est,mi.mu$std.err,mi.mu$lower,mi.mu$upper,mi.mu$df,apply(mu.imp,1,min),apply(mu.imp,1,max))
colnames(mi.results) <- c("Est","StdErr","Lower","Upper","DF","Min","Max")
# Results of running this as above
#> mi.results
# Est StdErr Lower Upper DF Min Max
#ind1 4.986591 0.03711372 4.913196 5.059986 135.8841 4.953036 5.018024
#ind2 7.923550 0.03669786 7.851316 7.995784 283.9978 7.901227 7.950898
# If we are willing to do a little of our own programming, we
# can write a function to do the full multivariate analysis. This
# one takes as input list of the parameters and asymptotic covariance
# matrices from each imputation and returns the imputation estimator,
# the entire covariance matrix of this estimator, the within and among
# components thereof, and the associated standard errors/confidence limits.
mi.mv.inference <- function (est, covmat, confidence = 0.95){
# Get the mean of estimates and mean of (within) covariance matrices
# (presumably these lists are of the same length; don't bother
# checking this)
m <- length(est)
qmat <- simplify2array(est)
qbar <- apply(qmat,1,mean)
wcov <- Reduce('+',covmat)/m
# Get among-imputation covariance matrix
bcov <- sweep(data.matrix(qmat),1,qbar)%*%t(sweep(data.matrix(qmat),1,qbar))/(m-1)
# Rubin covariance matrix and diagonal elements of each component
qcovmat <- wcov + (1+1/m)*bcov
bm <- apply(simplify2array(est),1,var) # should = diag(bcov)
ubar <- diag(wcov)
# This code is from mi.inference - CIs, DFs, etc for each component
tm <- ubar + ((1 + (1/m)) * bm) # should - diag(qcovmat)
rem <- (1 + (1/m)) * bm/ubar
nu <- (m - 1) * (1 + (1/rem))^2
alpha <- 1 - (1 - confidence)/2
low <- qbar - qt(alpha, nu) * sqrt(tm)
up <- qbar + qt(alpha, nu) * sqrt(tm)
pval <- 2 * (1 - pt(abs(qbar/sqrt(tm)), nu))
fminf <- (rem + 2/(nu + 3))/(rem + 1)
# First 3 elements are the mean of estimates, their SEs,
# entire covariance matrix using Rubin's formula; last 2
# are the within and among components
result <- list(est = qbar, std.err = sqrt(tm), cov.mat = qcovmat,
df = nu, signif = pval,lower = low, upper = up, r =
rem, fminf = fminf, within = wcov, between = bcov)
result
}
# Call the multivariate function
mi.mv.mu <- mi.mv.inference(mu.list,covs.list,confidence=0.95)
# Display the results -- should be identical to mi.inference
mi.mv.results <- cbind(mi.mv.mu$est,mi.mv.mu$std.err,mi.mv.mu$lower,mi.mv.mu$upper,
mi.mv.mu$df,apply(mu.imp,1,min),apply(mu.imp,1,max))
colnames(mi.mv.results) <- c("Est","StdErr","Lower","Upper","DF","Min","Max")
#> mi.mv.results
# Est StdErr Lower Upper DF Min Max
# ind1 4.986591 0.03711372 4.913196 5.059986 135.8841 4.953036 5.018024
# ind2 7.923550 0.03669786 7.851316 7.995784 283.9978 7.901227 7.950898
# get the components of the full Rubin covariance matrix
within.cov <- mi.mv.mu$within
between.cov <- mi.mv.mu$between
Rubin.cov <- mi.mv.mu$cov.mat
#> within.cov
# ind1 ind2
# ind1 0.0010229366 0.0005132697
# ind2 0.0005132697 0.0011069902
#> between.cov
# ind1 ind2
# ind1 3.222650e-04 6.834349e-06
# ind2 6.834349e-06 2.179478e-04
#> Rubin.cov
# ind1 ind2
# ind1 0.0013774280 0.0005207875
# ind2 0.0005207875 0.0013467327
| /course/st790_missing/examples/norm_mi.R | no_license | BowenNCSU/BowenNCSU.github.io | R | false | false | 8,426 | r | # Use the "norm" package downloaded from CRAN to
# carry out proper multiple imputation using a
# multivariate normal model to impute on the
# bivariate normal data
#
# install.packages("norm") and choose a mirror site
#
# Visit the CRAN website for the documentation
# Load the libary for the norm package
library(norm)
library(nlme)
# number of imputed data sets
M <- 10
# Read in the data set -- the missing values are denoted
# by the usual R convention NA
# The norm wants the data in a matrix, so we read it in
# directly to a matrix
datamat <- matrix(scan("bvnormal.R.dat"),ncol=2,byrow=TRUE)
N <- nrow(datamat)
nvar <- ncol(datamat)
# Run prelim.norm() to set up the data for the algorithm
prelim.mi <- prelim.norm(datamat)
# Look at the numbers of missing values and missing data patterns
prelim.mi$nmis
prelim.mi$r
# This produces
# > prelim.mi$nmis
# [1] 214 238
#
#> prelim.mi$r
# [,1] [,2]
# 548 1 1
# 214 0 1
# 238 1 0
# Run the EM algorithm initially with the default settings to
# get the form of the starting values
theta.init <- em.norm(prelim.mi,showits=FALSE)
# Extract the parameters so you can see the format
theta.init <- getparam.norm(prelim.mi,theta.init,corr=TRUE)
theta.init$mu # the mean vector
theta.init$sdv # the standard deviations
theta.init$r # the correlation matrix
# Convert these to the form used by the function em.norm
theta.init <- makeparam.norm(prelim.mi,theta.init)
# Create M imputed data sets using proper imputation
# and carry out the desired analysis on each one; save
# them in a big matrix in case you want to use them
# for something else
imputed.data <- NULL
# the mi.inference function wants the parameters and their
# standard errors saved in lists. We'll also save the full
# asymptotic covariance matrices for use with our own multivariate
# mi inference function below
mu.list <- vector("list",M)
ses.list <- vector("list",M)
covs.list <- vector("list",M)
covparms.list <- vector("list",M)
# Set the seed for the MCMC
rngseed(82)
for (m in 1:M){
# Impute the missing values to create a single data set using MCMC.
# Use the da.norm (for "data augmentation") function in the norm package
# to impute the missing values. Here, steps is apparently the number
# of iterations in the chain between draws - the documentation does not give
# details, and it is not clear if there is a burn-in period
imp.dat <- da.norm(prelim.mi,theta.init,steps=200,return.ymis=TRUE)
# misobs is a vector containing the imputed missing values in the order
# they are missing in the original data set, so insert them into a copy
# of the original data set.
misobs <- imp.dat$ymis
this.imp <- datamat
this.imp[is.na(this.imp)] <- misobs
# Save this imputed data set in case you want to do other stuff with it
imputed.data <- rbind(imputed.data,this.imp)
# Reconfigure the imputed data set to 1 record per observation
# for use with gls()
this.imp.alt <- NULL
for (i in 1:N){
this <-cbind(rep(i,nvar),seq(1,nvar,1),this.imp[i,1:2,drop=TRUE])
this.imp.alt <- rbind(this.imp.alt,this)
}
# Call gls() to fit the multivariate normal model to the reconfigured
# imputed data set
id <- factor(this.imp.alt[,1])
ind <- factor(this.imp.alt[,2])
y <- this.imp.alt[,3]
time <- rep(seq(1,2,1),N)
gls.fit <- gls(y ~ -1 + ind,correlation=corSymm(form = ~time | id),
weights=varIdent(form= ~1 | ind),method="ML")
# Get the estimates of the mean parameters and their standard errors
# and also the full asymptotic covariance matrices
this.mu <- gls.fit$coef
this.ses <- sqrt(diag(gls.fit$varBeta))
this.cov <- gls.fit$varBeta
# Save these in the lists, as the mi.inference function
# requires that the parameter estimates from each imputed data set and
# their standard errors be in lists
mu.list[[m]] <- this.mu
ses.list[[m]] <- this.ses
covs.list[[m]] <- this.cov
# Save the estimates of the variance and covariance parameters
this.covmat <- getVarCov(gls.fit)
this.covparms <- c(this.covmat[1,1],this.covmat[1,2],this.covmat[2,2])
covparms.list[[m]] <- this.covparms
# Unfortunately, getting their standard errors is hard -- they are computed
# but are available in a different (and not clear) parameterization via
# gls.fit$apVar
# We won't bother trying to extract them; usually these aren't of
# interest anyway
}
# Now call the function mi.inference() to obtain the multiple
# imputation estimate for mu and the ses via Rubin's formula. This
# function requires the parameters and their standard errors to be in
# lists, as noted aboe
mi.mu <- mi.inference(mu.list,ses.list,confidence=0.95) # confidence=0.95 is the default
# Display the results in the same format as SAS proc mianalyze
mu.imp <- simplify2array(mu.list)
mi.results <- cbind(mi.mu$est,mi.mu$std.err,mi.mu$lower,mi.mu$upper,mi.mu$df,apply(mu.imp,1,min),apply(mu.imp,1,max))
colnames(mi.results) <- c("Est","StdErr","Lower","Upper","DF","Min","Max")
# Results of running this as above
#> mi.results
# Est StdErr Lower Upper DF Min Max
#ind1 4.986591 0.03711372 4.913196 5.059986 135.8841 4.953036 5.018024
#ind2 7.923550 0.03669786 7.851316 7.995784 283.9978 7.901227 7.950898
# If we are willing to do a little of our own programming, we
# can write a function to do the full multivariate analysis. This
# one takes as input list of the parameters and asymptotic covariance
# matrices from each imputation and returns the imputation estimator,
# the entire covariance matrix of this estimator, the within and among
# components thereof, and the associated standard errors/confidence limits.
mi.mv.inference <- function (est, covmat, confidence = 0.95){
# Get the mean of estimates and mean of (within) covariance matrices
# (presumably these lists are of the same length; don't bother
# checking this)
m <- length(est)
qmat <- simplify2array(est)
qbar <- apply(qmat,1,mean)
wcov <- Reduce('+',covmat)/m
# Get among-imputation covariance matrix
bcov <- sweep(data.matrix(qmat),1,qbar)%*%t(sweep(data.matrix(qmat),1,qbar))/(m-1)
# Rubin covariance matrix and diagonal elements of each component
qcovmat <- wcov + (1+1/m)*bcov
bm <- apply(simplify2array(est),1,var) # should = diag(bcov)
ubar <- diag(wcov)
# This code is from mi.inference - CIs, DFs, etc for each component
tm <- ubar + ((1 + (1/m)) * bm) # should - diag(qcovmat)
rem <- (1 + (1/m)) * bm/ubar
nu <- (m - 1) * (1 + (1/rem))^2
alpha <- 1 - (1 - confidence)/2
low <- qbar - qt(alpha, nu) * sqrt(tm)
up <- qbar + qt(alpha, nu) * sqrt(tm)
pval <- 2 * (1 - pt(abs(qbar/sqrt(tm)), nu))
fminf <- (rem + 2/(nu + 3))/(rem + 1)
# First 3 elements are the mean of estimates, their SEs,
# entire covariance matrix using Rubin's formula; last 2
# are the within and among components
result <- list(est = qbar, std.err = sqrt(tm), cov.mat = qcovmat,
df = nu, signif = pval,lower = low, upper = up, r =
rem, fminf = fminf, within = wcov, between = bcov)
result
}
# Call the multivariate function
mi.mv.mu <- mi.mv.inference(mu.list,covs.list,confidence=0.95)
# Display the results -- should be identical to mi.inference
mi.mv.results <- cbind(mi.mv.mu$est,mi.mv.mu$std.err,mi.mv.mu$lower,mi.mv.mu$upper,
mi.mv.mu$df,apply(mu.imp,1,min),apply(mu.imp,1,max))
colnames(mi.mv.results) <- c("Est","StdErr","Lower","Upper","DF","Min","Max")
#> mi.mv.results
# Est StdErr Lower Upper DF Min Max
# ind1 4.986591 0.03711372 4.913196 5.059986 135.8841 4.953036 5.018024
# ind2 7.923550 0.03669786 7.851316 7.995784 283.9978 7.901227 7.950898
# get the components of the full Rubin covariance matrix
within.cov <- mi.mv.mu$within
between.cov <- mi.mv.mu$between
Rubin.cov <- mi.mv.mu$cov.mat
#> within.cov
# ind1 ind2
# ind1 0.0010229366 0.0005132697
# ind2 0.0005132697 0.0011069902
#> between.cov
# ind1 ind2
# ind1 3.222650e-04 6.834349e-06
# ind2 6.834349e-06 2.179478e-04
#> Rubin.cov
# ind1 ind2
# ind1 0.0013774280 0.0005207875
# ind2 0.0005207875 0.0013467327
|
#' Probability Plots Using Maximum Likelihood Estimates
#'
#' Make quantile-quantile plots and probability-probability plots using maximum
#' likelihood estimation.
#'
#' `qqmlplot` produces a quantile-quantile plot (Q-Q plot) of the values in
#' `y` with respect to the distribution defined by `obj`, which is
#' either a `univariateML` object or a function returning a
#' `univariateML` object when called with `y`. `qqmlline` adds a
#' line to a “theoretical”, quantile-quantile plot which passes through
#' the `probs` quantiles, by default the first and third quartiles.
#' `qqmlpoints`behaves like `stats::points` and adds a Q-Q plot to
#' an existing plot.
#'
#' `ppmlplot`, `ppmlline`, and `ppmlpoints` produce
#' probability-probability plots (or P-P plots). They behave similarly to the
#' quantile-quantile plot functions.
#'
#' This function is modeled after [qqnorm][stats::qqnorm].
#'
#' Graphical parameters may be given as arguments to all the functions below.
#'
#' @param y Numeric vector; The data to plot on the `y` axis when
#' `datax` is `FALSE`.
#' @param obj Either an `univariateML` object or a function that returns
#' a `univariateML` object when called with `y` as its only
#' argument.
#' @param plot.it Logical; should the result be plotted?
#' @param datax Logical; should `y` be plotted on the `x`-axis?
#' Defaults to `FALSE` in `qqmlplot` and `ppmlplot` but
#' `TRUE` in `qqmlpoints` and `ppmlpoints`.
#' @param probs Numeric vector of length two, representing probabilities.
#' Corresponding quantile pairs define the line drawn.
#' @param qtype The `type` of quantile computation used in `quantile`.
#' @param ... Graphical parameters.
#' @return For `qqmlplot`, `qqmlpoints`, `ppmlplot`, and
#' `ppmlpoints`, a list with components `x` (plotted on the x axis)
#' and `y` (plotted on the y axis). `qqmlline` and `ppmlline`
#' returns nothing.
#'
#' @examples
#' ## Make a single probability plot with a line.
#'
#' obj <- mlgamma(Nile)
#' qqmlplot(Nile, obj)
#' qqmlline(Nile, obj)
#'
#' ## Make multiple probability plots. datax = TRUE must be used to make this
#' ## look good.
#'
#' ppmlplot(airquality$Wind, mlgamma, main = "Many P-P plots")
#' ppmlpoints(airquality$Wind, mlexp, col = "red")
#' ppmlpoints(airquality$Wind, mlweibull, col = "purple")
#' ppmlpoints(airquality$Wind, mllnorm, col = "blue")
#' @name ProbabilityPlots
#' @export
#' @references
#' M. B. Wilk, R. Gnadadesikan, Probability plotting methods for the analysis
#' for the analysis of data, Biometrika, Volume 55, Issue 1, March 1968,
#' Pages 1–17, https://doi.org/10.1093/biomet/55.1.1
ppmlplot <- function(y, obj, plot.it = TRUE, datax = FALSE, ...) {
pp <- ppqq_wrangler(y, obj, datax, pp = TRUE, ...)
if (plot.it) do.call(graphics::plot, pp$args)
invisible(pp$value)
}
#' @rdname ProbabilityPlots
#' @export
ppmlline <- function(...) graphics::abline(a = 0, b = 1, ...)
#' @rdname ProbabilityPlots
#' @export
ppmlpoints <- function(y, obj, plot.it = TRUE, datax = TRUE, ...) {
pp <- ppqq_wrangler(y, obj, datax, pp = TRUE, ...)
if (plot.it) do.call(graphics::points, pp$args)
invisible(pp$value)
}
#' @rdname ProbabilityPlots
#' @export
qqmlplot <- function(y, obj, plot.it = TRUE, datax = FALSE, ...) {
qq <- ppqq_wrangler(y, obj, datax, pp = FALSE, ...)
if (plot.it) do.call(graphics::plot, qq$args)
invisible(qq$value)
}
#' @rdname ProbabilityPlots
#' @export
qqmlline <- function(y, obj, datax = FALSE, probs = c(0.25, 0.75), qtype = 7,
...) {
obj <- to_univariateML(y, obj)
y <- stats::quantile(y, probs, names = FALSE, type = qtype, na.rm = TRUE)
x <- qml(probs, obj)
if (datax) {
slope <- diff(x) / diff(y)
int <- x[1L] - slope * y[1L]
} else {
slope <- diff(y) / diff(x)
int <- y[1L] - slope * x[1L]
}
graphics::abline(int, slope, ...)
}
#' @rdname ProbabilityPlots
#' @export
qqmlpoints <- function(y, obj, plot.it = TRUE, datax = TRUE, ...) {
qq <- ppqq_wrangler(y, obj, datax, pp = FALSE, ...)
if (plot.it) do.call(graphics::points, qq$args)
invisible(qq$value)
}
| /R/probability_plots.R | permissive | JonasMoss/univariateML | R | false | false | 4,108 | r | #' Probability Plots Using Maximum Likelihood Estimates
#'
#' Make quantile-quantile plots and probability-probability plots using maximum
#' likelihood estimation.
#'
#' `qqmlplot` produces a quantile-quantile plot (Q-Q plot) of the values in
#' `y` with respect to the distribution defined by `obj`, which is
#' either a `univariateML` object or a function returning a
#' `univariateML` object when called with `y`. `qqmlline` adds a
#' line to a “theoretical”, quantile-quantile plot which passes through
#' the `probs` quantiles, by default the first and third quartiles.
#' `qqmlpoints`behaves like `stats::points` and adds a Q-Q plot to
#' an existing plot.
#'
#' `ppmlplot`, `ppmlline`, and `ppmlpoints` produce
#' probability-probability plots (or P-P plots). They behave similarly to the
#' quantile-quantile plot functions.
#'
#' This function is modeled after [qqnorm][stats::qqnorm].
#'
#' Graphical parameters may be given as arguments to all the functions below.
#'
#' @param y Numeric vector; The data to plot on the `y` axis when
#' `datax` is `FALSE`.
#' @param obj Either an `univariateML` object or a function that returns
#' a `univariateML` object when called with `y` as its only
#' argument.
#' @param plot.it Logical; should the result be plotted?
#' @param datax Logical; should `y` be plotted on the `x`-axis?
#' Defaults to `FALSE` in `qqmlplot` and `ppmlplot` but
#' `TRUE` in `qqmlpoints` and `ppmlpoints`.
#' @param probs Numeric vector of length two, representing probabilities.
#' Corresponding quantile pairs define the line drawn.
#' @param qtype The `type` of quantile computation used in `quantile`.
#' @param ... Graphical parameters.
#' @return For `qqmlplot`, `qqmlpoints`, `ppmlplot`, and
#' `ppmlpoints`, a list with components `x` (plotted on the x axis)
#' and `y` (plotted on the y axis). `qqmlline` and `ppmlline`
#' returns nothing.
#'
#' @examples
#' ## Make a single probability plot with a line.
#'
#' obj <- mlgamma(Nile)
#' qqmlplot(Nile, obj)
#' qqmlline(Nile, obj)
#'
#' ## Make multiple probability plots. datax = TRUE must be used to make this
#' ## look good.
#'
#' ppmlplot(airquality$Wind, mlgamma, main = "Many P-P plots")
#' ppmlpoints(airquality$Wind, mlexp, col = "red")
#' ppmlpoints(airquality$Wind, mlweibull, col = "purple")
#' ppmlpoints(airquality$Wind, mllnorm, col = "blue")
#' @name ProbabilityPlots
#' @export
#' @references
#' M. B. Wilk, R. Gnadadesikan, Probability plotting methods for the analysis
#' for the analysis of data, Biometrika, Volume 55, Issue 1, March 1968,
#' Pages 1–17, https://doi.org/10.1093/biomet/55.1.1
ppmlplot <- function(y, obj, plot.it = TRUE, datax = FALSE, ...) {
pp <- ppqq_wrangler(y, obj, datax, pp = TRUE, ...)
if (plot.it) do.call(graphics::plot, pp$args)
invisible(pp$value)
}
#' @rdname ProbabilityPlots
#' @export
ppmlline <- function(...) graphics::abline(a = 0, b = 1, ...)
#' @rdname ProbabilityPlots
#' @export
ppmlpoints <- function(y, obj, plot.it = TRUE, datax = TRUE, ...) {
pp <- ppqq_wrangler(y, obj, datax, pp = TRUE, ...)
if (plot.it) do.call(graphics::points, pp$args)
invisible(pp$value)
}
#' @rdname ProbabilityPlots
#' @export
qqmlplot <- function(y, obj, plot.it = TRUE, datax = FALSE, ...) {
qq <- ppqq_wrangler(y, obj, datax, pp = FALSE, ...)
if (plot.it) do.call(graphics::plot, qq$args)
invisible(qq$value)
}
#' @rdname ProbabilityPlots
#' @export
qqmlline <- function(y, obj, datax = FALSE, probs = c(0.25, 0.75), qtype = 7,
...) {
obj <- to_univariateML(y, obj)
y <- stats::quantile(y, probs, names = FALSE, type = qtype, na.rm = TRUE)
x <- qml(probs, obj)
if (datax) {
slope <- diff(x) / diff(y)
int <- x[1L] - slope * y[1L]
} else {
slope <- diff(y) / diff(x)
int <- y[1L] - slope * x[1L]
}
graphics::abline(int, slope, ...)
}
#' @rdname ProbabilityPlots
#' @export
qqmlpoints <- function(y, obj, plot.it = TRUE, datax = TRUE, ...) {
qq <- ppqq_wrangler(y, obj, datax, pp = FALSE, ...)
if (plot.it) do.call(graphics::points, qq$args)
invisible(qq$value)
}
|
#' Creates all the dataframes and save them in the specified folder
#' @inheritParams default_params_doc
#' @export
run_all <- function(
address1 = "https://docs.google.com/spreadsheets/d/1wKeDUhL4TJJ9yVUDN49kOANU_5Y77r6-vIxaq4Wgdks/",
address2 = "https://docs.google.com/spreadsheets/d/1AipazAj6Ebfuv0Kek4xMRYva8sodUQs-4AI3li0IbzY/",
folder
) {
# if (!require("devtools")) {install.packages("devtools")}
# devtools::install_github("Giappo/dbmefu"); library(dbmefu, quietly = TRUE)
df1 <- dbmefu::import_df(address1)
df2 <- dbmefu::import_df(address2)
df1 <- dbmefu::ripulisci_df(df1)
df2 <- dbmefu::ripulisci_df(df2)
dfmerged <- dbmefu::merge_db(df1 = df1, df2 = df2, folder = folder)
not_in_df1 <- dbmefu::in_db2_not_in_db1(df1 = df1, df2 = df2, folder = folder)
not_in_df2 <- dbmefu::in_db1_not_in_db2(df1 = df1, df2 = df2, folder = folder)
nots <- dbmefu::find_nots(df1 = df1, df2 = df2, folder = folder)
return(list(
dfmerged = dfmerged,
not_in_df1 = not_in_df1,
not_in_df2 = not_in_df2,
nots = nots
))
}
| /R/run_all.R | no_license | Giappo/dbmefu | R | false | false | 1,059 | r | #' Creates all the dataframes and save them in the specified folder
#' @inheritParams default_params_doc
#' @export
run_all <- function(
address1 = "https://docs.google.com/spreadsheets/d/1wKeDUhL4TJJ9yVUDN49kOANU_5Y77r6-vIxaq4Wgdks/",
address2 = "https://docs.google.com/spreadsheets/d/1AipazAj6Ebfuv0Kek4xMRYva8sodUQs-4AI3li0IbzY/",
folder
) {
# if (!require("devtools")) {install.packages("devtools")}
# devtools::install_github("Giappo/dbmefu"); library(dbmefu, quietly = TRUE)
df1 <- dbmefu::import_df(address1)
df2 <- dbmefu::import_df(address2)
df1 <- dbmefu::ripulisci_df(df1)
df2 <- dbmefu::ripulisci_df(df2)
dfmerged <- dbmefu::merge_db(df1 = df1, df2 = df2, folder = folder)
not_in_df1 <- dbmefu::in_db2_not_in_db1(df1 = df1, df2 = df2, folder = folder)
not_in_df2 <- dbmefu::in_db1_not_in_db2(df1 = df1, df2 = df2, folder = folder)
nots <- dbmefu::find_nots(df1 = df1, df2 = df2, folder = folder)
return(list(
dfmerged = dfmerged,
not_in_df1 = not_in_df1,
not_in_df2 = not_in_df2,
nots = nots
))
}
|
# Load data. This assumes that the data file is in the working directory
epc <- read.table('./household_power_consumption.txt', sep=";", header=TRUE)
# Get subset for dates between 2/1/2007 and 2/2/2007
epc$Date <- as.character(epc$Date)
epc.sub <- epc[(epc$Date == "1/2/2007") | (epc$Date == "2/2/2007"), ]
#make a vector of date/times for the plot
epc.sub$Time <- as.character(epc.sub$Time)
date_times <- strptime(paste(epc.sub$Date, epc.sub$Time), "%d/%m/%Y %T")
# convert factor data to numeric
sub.1 <- as.numeric(as.character(epc.sub$Sub_metering_1))
sub.2 <- as.numeric(as.character(epc.sub$Sub_metering_2))
sub.3 <- as.numeric(as.character(epc.sub$Sub_metering_3))
# open png device and make plot.
png(file = 'plot3.png')
par(mfrow=c(1,1)) #set layout
plot(date_times, sub.1, type='l', col="black", xlab="", ylab="Energy sub metering")
lines(date_times, sub.2, type='l', col="red")
lines(date_times, sub.3, type='l', col="blue")
legend("topright",
lty=1,
col = c("black", "red", "blue"),
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
dev.off()
| /plot3.R | no_license | msbuckley/ExData_Plotting1 | R | false | false | 1,101 | r | # Load data. This assumes that the data file is in the working directory
epc <- read.table('./household_power_consumption.txt', sep=";", header=TRUE)
# Get subset for dates between 2/1/2007 and 2/2/2007
epc$Date <- as.character(epc$Date)
epc.sub <- epc[(epc$Date == "1/2/2007") | (epc$Date == "2/2/2007"), ]
#make a vector of date/times for the plot
epc.sub$Time <- as.character(epc.sub$Time)
date_times <- strptime(paste(epc.sub$Date, epc.sub$Time), "%d/%m/%Y %T")
# convert factor data to numeric
sub.1 <- as.numeric(as.character(epc.sub$Sub_metering_1))
sub.2 <- as.numeric(as.character(epc.sub$Sub_metering_2))
sub.3 <- as.numeric(as.character(epc.sub$Sub_metering_3))
# open png device and make plot.
png(file = 'plot3.png')
par(mfrow=c(1,1)) #set layout
plot(date_times, sub.1, type='l', col="black", xlab="", ylab="Energy sub metering")
lines(date_times, sub.2, type='l', col="red")
lines(date_times, sub.3, type='l', col="blue")
legend("topright",
lty=1,
col = c("black", "red", "blue"),
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
dev.off()
|
install.packages("locfit")
if (!require("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("DESeq2") | /batchx/deg-patterns/install.deg-patterns2.R | permissive | lpantano/DEGreport | R | false | false | 140 | r |
install.packages("locfit")
if (!require("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("DESeq2") |
#Brandon Vermeer
#Thesis Code
#Spring 2018
#############################################################
#clear items and install packages
rm(list=ls())
install.packages("car")
library("car")
#set working directory
getwd()
setwd("/Users/BrandonVermeer/Documents/Thesis/NHL_Team_Stats")
#Load 2015-2016 Season Team Data
Season12_Teams <- read.csv("16-17Teams.csv")
head(Season12_Teams)
str(Season12_Teams)
dim(Season12_Teams)
attach(Season12_Teams)
#Wins vs Goals Allowed 2016-2017
WinsVsGA12 <- lm(W ~ GA)
summary(WinsVsGA12)
plot(WinsVsGA12)
#Wins vs Goals For 2016-2017
WinsVsGF12 <- lm(W ~ GF)
summary(WinsVsGF12)
plot(WinsVsGF12)
#Wins vs Goals For + Goals Against 2016-2017
WinsVsGF12andGA12 <- lm(W ~ GF + GA)
summary(WinsVsGF12andGA12)
plot(WinsVsGF12andGA12)
predict(WinsVsGF12andGA12)
#W=GF+GA Residuals
r <- residuals(WinsVsGF12andGA12)
residualPlots(WinsVsGF12andGA12)
qqnorm(r)
qqline(r)
shapiro.test(residuals(WinsVsGF12andGA12))
#Load Corsi Based Data
Season12_Corsi <- read.csv("16-17Corsi.csv")
attach(Season12_Corsi)
#Create Corsi based modles
WinsVsCorsi <- lm(Wins ~ Corsi)
summary(WinsVsCorsi)
WinsVsCorsiAVG <- lm(Wins ~ CorsiAVG)
summary(WinsVsCorsiAVG)
#Load data for MAX models
Season12_MAX <- read.csv("16-17WOTeams.csv")
attach(Season12_MAX)
#Create MAX Model
max.mod <- lm(W ~ ., Season12_MAX)
summary(max.mod)
step.mod <- step(max.mod)
summary(step.mod)
#Load data for All Season Regressions
AllSeasons <- read.csv("AllSeasons.csv")
attach(AllSeasons)
#Create all season regressions
AllSeasonsGFandGA <- lm(WA ~ GFA + GAA)
summary(AllSeasonsGFandGA)
plot(AllSeasonsGFandGA)
#Residuals for plot
r2 <- residuals(AllSeasonsGFandGA)
residualPlots(AllSeasonsGFandGA)
qqnorm(r2)
qqline(r2) | /NHL_Analysis.R | no_license | brandonbev/Regression_to_predict_NHL_wins | R | false | false | 1,731 | r | #Brandon Vermeer
#Thesis Code
#Spring 2018
#############################################################
#clear items and install packages
rm(list=ls())
install.packages("car")
library("car")
#set working directory
getwd()
setwd("/Users/BrandonVermeer/Documents/Thesis/NHL_Team_Stats")
#Load 2015-2016 Season Team Data
Season12_Teams <- read.csv("16-17Teams.csv")
head(Season12_Teams)
str(Season12_Teams)
dim(Season12_Teams)
attach(Season12_Teams)
#Wins vs Goals Allowed 2016-2017
WinsVsGA12 <- lm(W ~ GA)
summary(WinsVsGA12)
plot(WinsVsGA12)
#Wins vs Goals For 2016-2017
WinsVsGF12 <- lm(W ~ GF)
summary(WinsVsGF12)
plot(WinsVsGF12)
#Wins vs Goals For + Goals Against 2016-2017
WinsVsGF12andGA12 <- lm(W ~ GF + GA)
summary(WinsVsGF12andGA12)
plot(WinsVsGF12andGA12)
predict(WinsVsGF12andGA12)
#W=GF+GA Residuals
r <- residuals(WinsVsGF12andGA12)
residualPlots(WinsVsGF12andGA12)
qqnorm(r)
qqline(r)
shapiro.test(residuals(WinsVsGF12andGA12))
#Load Corsi Based Data
Season12_Corsi <- read.csv("16-17Corsi.csv")
attach(Season12_Corsi)
#Create Corsi based modles
WinsVsCorsi <- lm(Wins ~ Corsi)
summary(WinsVsCorsi)
WinsVsCorsiAVG <- lm(Wins ~ CorsiAVG)
summary(WinsVsCorsiAVG)
#Load data for MAX models
Season12_MAX <- read.csv("16-17WOTeams.csv")
attach(Season12_MAX)
#Create MAX Model
max.mod <- lm(W ~ ., Season12_MAX)
summary(max.mod)
step.mod <- step(max.mod)
summary(step.mod)
#Load data for All Season Regressions
AllSeasons <- read.csv("AllSeasons.csv")
attach(AllSeasons)
#Create all season regressions
AllSeasonsGFandGA <- lm(WA ~ GFA + GAA)
summary(AllSeasonsGFandGA)
plot(AllSeasonsGFandGA)
#Residuals for plot
r2 <- residuals(AllSeasonsGFandGA)
residualPlots(AllSeasonsGFandGA)
qqnorm(r2)
qqline(r2) |
# this returns a scatterplot for all countries in which
# we can compare the urban and rural unemployment with plotly
# load in packages
library(dplyr)
source('./scripts/datafunctions.R')
# data to test out our function
data <- read.csv("./data/ilodata.csv")
data <- filter(data, !is.na(Obs_Value))
# pare down columns in dataframe to just country, sex, age, urban status, year, and unemployment
short.data <- select(data, Country_Label, Country_Code, Sex_Item_Label,
Classif1_Item_Label, Classif2_Item_Label, Time, Obs_Value)
# create a plotly scatterplot that plots obs value for urban vs rural
# first things first let's join some tables!
table1 <- FilterMapData("Urban", "Total", 1990, 2015, "Total")
| /finalproject-master/scripts/scatter.R | no_license | Anushree-12/WINFO-Hackathon-2018 | R | false | false | 736 | r | # this returns a scatterplot for all countries in which
# we can compare the urban and rural unemployment with plotly
# load in packages
library(dplyr)
source('./scripts/datafunctions.R')
# data to test out our function
data <- read.csv("./data/ilodata.csv")
data <- filter(data, !is.na(Obs_Value))
# pare down columns in dataframe to just country, sex, age, urban status, year, and unemployment
short.data <- select(data, Country_Label, Country_Code, Sex_Item_Label,
Classif1_Item_Label, Classif2_Item_Label, Time, Obs_Value)
# create a plotly scatterplot that plots obs value for urban vs rural
# first things first let's join some tables!
table1 <- FilterMapData("Urban", "Total", 1990, 2015, "Total")
|
context("gce-token-mocked")
test_that('Can list service accounts', {
service_accounts = c('account1@project.gserviceaccount.com', 'default')
request_mock <- function(path, ...) {
stopifnot(path == 'instance/service-accounts')
httr:::response(
url = path,
status_code = 200,
header = list(`metadata-flavor` = 'Google'),
content = charToRaw(paste0(c(service_accounts, ''), collapse = '/\n'))
)
}
testthat::with_mock(
`gargle::gce_metadata_request` = request_mock,
expect_equal(service_accounts, list_service_accounts())
)
})
test_that('GCE metadata env vars are respected', {
tryCatch({
expect_equal('http://metadata.google.internal/', gce_metadata_url())
Sys.setenv(GCE_METADATA_URL = 'fake.url')
expect_equal('http://fake.url/', gce_metadata_url())
options(gargle.gce.use_ip = TRUE)
expect_equal('http://169.254.169.254/', gce_metadata_url())
Sys.setenv(GCE_METADATA_IP='1.2.3.4')
expect_equal('http://1.2.3.4/', gce_metadata_url())
}, finally = {
# We could save and restore these values, but there's no reason they should
# be set in tests.
Sys.unsetenv('GCE_METADATA_IP')
Sys.unsetenv('GCE_METADATA_URL')
options(gargle.gce.use_ip = NULL)
})
})
test_that('GCE metadata detection fails not on GCE', {
tryCatch({
Sys.setenv(GCE_METADATA_URL = 'some.fake.address')
expect_false(detect_gce())
}, finally = {
Sys.unsetenv('GCE_METADATA_URL')
})
})
| /tests/testthat/test-gce-token.R | permissive | takewiki/gargle | R | false | false | 1,477 | r | context("gce-token-mocked")
test_that('Can list service accounts', {
service_accounts = c('account1@project.gserviceaccount.com', 'default')
request_mock <- function(path, ...) {
stopifnot(path == 'instance/service-accounts')
httr:::response(
url = path,
status_code = 200,
header = list(`metadata-flavor` = 'Google'),
content = charToRaw(paste0(c(service_accounts, ''), collapse = '/\n'))
)
}
testthat::with_mock(
`gargle::gce_metadata_request` = request_mock,
expect_equal(service_accounts, list_service_accounts())
)
})
test_that('GCE metadata env vars are respected', {
tryCatch({
expect_equal('http://metadata.google.internal/', gce_metadata_url())
Sys.setenv(GCE_METADATA_URL = 'fake.url')
expect_equal('http://fake.url/', gce_metadata_url())
options(gargle.gce.use_ip = TRUE)
expect_equal('http://169.254.169.254/', gce_metadata_url())
Sys.setenv(GCE_METADATA_IP='1.2.3.4')
expect_equal('http://1.2.3.4/', gce_metadata_url())
}, finally = {
# We could save and restore these values, but there's no reason they should
# be set in tests.
Sys.unsetenv('GCE_METADATA_IP')
Sys.unsetenv('GCE_METADATA_URL')
options(gargle.gce.use_ip = NULL)
})
})
test_that('GCE metadata detection fails not on GCE', {
tryCatch({
Sys.setenv(GCE_METADATA_URL = 'some.fake.address')
expect_false(detect_gce())
}, finally = {
Sys.unsetenv('GCE_METADATA_URL')
})
})
|
birth1 <- c(1,0,0,0,1,1,0,1,0,1,0,0,1,1,0,1,1,0,0,0,1,0,0,0,1,0,
0,0,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,0,1,0,0,1,1,0,1,0,0,0,0,0,0,0,
1,1,0,1,0,0,1,0,0,0,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,0,0,1,0,1,1,0,
1,0,1,1,1,0,1,1,1,1)
birth2 <- c(0,1,0,1,0,1,1,1,0,0,1,1,1,1,1,0,0,1,1,1,0,0,1,1,1,0,
1,1,1,0,1,1,1,0,1,0,0,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,0,1,1,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,0,0,1,1,
0,0,0,1,1,1,0,0,0,0) | /data/homeworkch3.R | permissive | StatisticalRethinkingJulia/DynamicHMCModels.jl | R | false | false | 438 | r | birth1 <- c(1,0,0,0,1,1,0,1,0,1,0,0,1,1,0,1,1,0,0,0,1,0,0,0,1,0,
0,0,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,0,1,0,0,1,1,0,1,0,0,0,0,0,0,0,
1,1,0,1,0,0,1,0,0,0,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,0,0,1,0,1,1,0,
1,0,1,1,1,0,1,1,1,1)
birth2 <- c(0,1,0,1,0,1,1,1,0,0,1,1,1,1,1,0,0,1,1,1,0,0,1,1,1,0,
1,1,1,0,1,1,1,0,1,0,0,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,0,1,1,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,0,0,1,1,
0,0,0,1,1,1,0,0,0,0) |
# tests for avisHasSpecies in rAvis
context("avisHasSpecies")
test_that("Pica pica is in the database, Pica pic is not",{
nameraw<- "Pica pica"
expect_true(avisHasSpecies (nameraw))
nameraw<- "Pica pic"
expect_false(avisHasSpecies (nameraw))
})
| /rAvis/tests/testthat_disabled/test-avisHasSpecies.R | no_license | ingted/R-Examples | R | false | false | 279 | r | # tests for avisHasSpecies in rAvis
context("avisHasSpecies")
test_that("Pica pica is in the database, Pica pic is not",{
nameraw<- "Pica pica"
expect_true(avisHasSpecies (nameraw))
nameraw<- "Pica pic"
expect_false(avisHasSpecies (nameraw))
})
|
#Primary functions for running the selection model
#' Fit the Selection Model for Proteomics
#'
#' @param dat Correctly formated and normalized data frame
#' @param ndraws Number of draws of the Gibbs Sampler
#' @param burn Number of draws to discard before summarizing the posterior
#' @param fc_prior Explicitly set a prior for the variance of the fold change
#' parameter. By default this is set to zero which uses the usual shared
#' variance component. Specifying a weak prior will avoid shrinkage in the
#' estimates.
#'
#' @export
smp <- function(dat, ndraws = 20000, burn = 1000, melted = FALSE, fc_prior = 0){
if(melted){
readyDat <- dat
pop <- FALSE
}else{
if(dat[2, 1] == 1){
pop <- TRUE
stop("Sorry, the population level model is currently in development")
}else{
pop <- FALSE
}
#make sure protein names do not have "_" characters
dat <- within(dat, Protein <- gsub("_", "-", Protein))
#transform data and initialize the Gibbs sampler
readyDat <- transformDat(dat)
}
initList <- prepare(readyDat, ndraws, pop) #function returns, in order:
#y_list, y_miss, r_obs, matList, pointers,
# fcs, peps, int_mu, miss_a, miss_b,
#sigma, tau_int, tau_fc, tau_pep, pop_mu, n_used, estimable, resids
#reset tau_fc if a prior was selected
if(fc_prior > 0){
initList[[13]][1, 1] <- fc_prior
initList[[14]][1, 1] <- fc_prior
}
yVec <- readyDat$lintensity
yVec[is.na(yVec)] <- 0
#call the C++ Gibbs Sampler
testRes <- gibbsCpp(initList[[1]],
as.matrix(initList[[2]]),
as.matrix(initList[[3]]),
initList[[4]],
initList[[5]],
as.matrix(initList[[6]]),
as.matrix(initList[[7]]),
as.matrix(initList[[8]]),
as.matrix(initList[[9]]),
as.matrix(initList[[10]]),
as.matrix(initList[[11]]),
as.matrix(initList[[12]]),
as.matrix(initList[[13]]),
as.matrix(initList[[14]]),
as.matrix(yVec), rProbit, sn::rsn,
as.matrix(initList[[18]]),
fc_prior)
#extract summary information
postMeans <- apply(testRes[["fcs"]][ , burn:ndraws], 1, mean)
postVar <- apply(testRes[["fcs"]][ , burn:ndraws], 1, var)
protNames <- levels(factor(readyDat$protein))
conditions <- length(levels(factor(readyDat$condID)))
nameCol <- rep(protNames, each = (conditions - 1))
condCol <- rep(2:conditions, length(protNames))
resTable <- data.frame(Protein = nameCol, Condition = condCol,
Mean = postMeans, Var = postVar,
N_used = initList[[16]],
Estimable = initList[[17]] )
list(resTable, testRes)
} #end of smp function
| /R/main.R | no_license | Feigeliudan01/missMS | R | false | false | 2,918 | r | #Primary functions for running the selection model
#' Fit the Selection Model for Proteomics
#'
#' @param dat Correctly formated and normalized data frame
#' @param ndraws Number of draws of the Gibbs Sampler
#' @param burn Number of draws to discard before summarizing the posterior
#' @param fc_prior Explicitly set a prior for the variance of the fold change
#' parameter. By default this is set to zero which uses the usual shared
#' variance component. Specifying a weak prior will avoid shrinkage in the
#' estimates.
#'
#' @export
smp <- function(dat, ndraws = 20000, burn = 1000, melted = FALSE, fc_prior = 0){
if(melted){
readyDat <- dat
pop <- FALSE
}else{
if(dat[2, 1] == 1){
pop <- TRUE
stop("Sorry, the population level model is currently in development")
}else{
pop <- FALSE
}
#make sure protein names do not have "_" characters
dat <- within(dat, Protein <- gsub("_", "-", Protein))
#transform data and initialize the Gibbs sampler
readyDat <- transformDat(dat)
}
initList <- prepare(readyDat, ndraws, pop) #function returns, in order:
#y_list, y_miss, r_obs, matList, pointers,
# fcs, peps, int_mu, miss_a, miss_b,
#sigma, tau_int, tau_fc, tau_pep, pop_mu, n_used, estimable, resids
#reset tau_fc if a prior was selected
if(fc_prior > 0){
initList[[13]][1, 1] <- fc_prior
initList[[14]][1, 1] <- fc_prior
}
yVec <- readyDat$lintensity
yVec[is.na(yVec)] <- 0
#call the C++ Gibbs Sampler
testRes <- gibbsCpp(initList[[1]],
as.matrix(initList[[2]]),
as.matrix(initList[[3]]),
initList[[4]],
initList[[5]],
as.matrix(initList[[6]]),
as.matrix(initList[[7]]),
as.matrix(initList[[8]]),
as.matrix(initList[[9]]),
as.matrix(initList[[10]]),
as.matrix(initList[[11]]),
as.matrix(initList[[12]]),
as.matrix(initList[[13]]),
as.matrix(initList[[14]]),
as.matrix(yVec), rProbit, sn::rsn,
as.matrix(initList[[18]]),
fc_prior)
#extract summary information
postMeans <- apply(testRes[["fcs"]][ , burn:ndraws], 1, mean)
postVar <- apply(testRes[["fcs"]][ , burn:ndraws], 1, var)
protNames <- levels(factor(readyDat$protein))
conditions <- length(levels(factor(readyDat$condID)))
nameCol <- rep(protNames, each = (conditions - 1))
condCol <- rep(2:conditions, length(protNames))
resTable <- data.frame(Protein = nameCol, Condition = condCol,
Mean = postMeans, Var = postVar,
N_used = initList[[16]],
Estimable = initList[[17]] )
list(resTable, testRes)
} #end of smp function
|
# Load packages
library(tidyverse)
library(tidymodels)
library(naniar)
library(corrplot)
library(corrr)
library(glmnet)
library(ranger)
# set seed
set.seed(123)
# load data
loan_train <- read_csv("stat-301-3-classification-2021-loan-repayment/train.csv")
loan_test <- read_csv("stat-301-3-classification-2021-loan-repayment/test.csv")
dim(loan_train)
dim(loan_test)
loan_train <- loan_train %>%
mutate(hi_int_prncp_pd_f = factor(hi_int_prncp_pd))
# split data
loan_folds <- vfold_cv(data = loan_train, v = 5, repeats = 3)
# create another recipe
loan_recipe2 <-
recipe(hi_int_prncp_pd_f ~ int_rate + loan_amnt +
out_prncp_inv + application_type + grade + initial_list_status + term,
data = loan_train) %>%
step_dummy(all_nominal_predictors(), one_hot = TRUE) %>%
step_normalize(all_predictors())
# random forest model
rf_model <- rand_forest(
mode = "classification",
mtry = tune(),
min_n = tune()
) %>%
set_engine("ranger", importance = "impurity")
# set-up tuning grid ----
rf_params <- parameters(rf_model) %>%
update(mtry = mtry(range = c(2,6)))
# define tuning grid
rf_grid <- grid_regular(rf_params, levels = c(3,4))
# workflow ----
rf_workflow <- workflow() %>%
add_model(rf_model) %>%
add_recipe(loan_recipe2)
# Tuning/fitting
rf_tuned <- rf_workflow %>%
tune_grid(loan_folds, rf_grid)
write_rds(rf_tuned, "rf_results.rds")
| /rf_results.R | no_license | lilyyan2023/STAT301-3Classification | R | false | false | 1,397 | r | # Load packages
library(tidyverse)
library(tidymodels)
library(naniar)
library(corrplot)
library(corrr)
library(glmnet)
library(ranger)
# set seed
set.seed(123)
# load data
loan_train <- read_csv("stat-301-3-classification-2021-loan-repayment/train.csv")
loan_test <- read_csv("stat-301-3-classification-2021-loan-repayment/test.csv")
dim(loan_train)
dim(loan_test)
loan_train <- loan_train %>%
mutate(hi_int_prncp_pd_f = factor(hi_int_prncp_pd))
# split data
loan_folds <- vfold_cv(data = loan_train, v = 5, repeats = 3)
# create another recipe
loan_recipe2 <-
recipe(hi_int_prncp_pd_f ~ int_rate + loan_amnt +
out_prncp_inv + application_type + grade + initial_list_status + term,
data = loan_train) %>%
step_dummy(all_nominal_predictors(), one_hot = TRUE) %>%
step_normalize(all_predictors())
# random forest model
rf_model <- rand_forest(
mode = "classification",
mtry = tune(),
min_n = tune()
) %>%
set_engine("ranger", importance = "impurity")
# set-up tuning grid ----
rf_params <- parameters(rf_model) %>%
update(mtry = mtry(range = c(2,6)))
# define tuning grid
rf_grid <- grid_regular(rf_params, levels = c(3,4))
# workflow ----
rf_workflow <- workflow() %>%
add_model(rf_model) %>%
add_recipe(loan_recipe2)
# Tuning/fitting
rf_tuned <- rf_workflow %>%
tune_grid(loan_folds, rf_grid)
write_rds(rf_tuned, "rf_results.rds")
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/write_JAGS_model.R
\name{write_JAGS_model}
\alias{write_JAGS_model}
\title{Write the JAGS model file}
\usage{
write_JAGS_model(
filename = "MixSIAR_model.txt",
resid_err = TRUE,
process_err = TRUE,
mix,
source
)
}
\arguments{
\item{filename}{the JAGS model file is saved in the working directory as 'filename'
(default is "MixSIAR_model.txt", but user can specify).}
\item{resid_err}{T/F: include residual error in the model?}
\item{process_err}{T/F: include process error in the model?}
\item{mix}{output from \code{\link{load_mix_data}}}
\item{source}{output from \code{\link{load_source_data}}}
}
\description{
\code{write_JAGS_model} creates "MixSIAR_model.txt", which is passed to JAGS
by \code{\link{run_model}} when the "RUN MODEL" button is clicked in the GUI.
Several model options will have already been specified when loading the mix
and source data, but here is where the error term options are selected:
\enumerate{
\item Residual * Process (resid_err = TRUE, process_err = TRUE)
\item Residual only (resid_err = TRUE, process_err = FALSE)
\item Process only (resid_err = FALSE, process_err = TRUE)
}
}
\details{
WARNING messages are displayed if:
\itemize{
\item resid_err = FALSE and process_err = FALSE are both selected.
\item N=1 mix data point and did not choose "Process only" error model (MixSIR)
\item Fitting each individual mix data point separately as a Fixed Effect,
but did not choose "Process only" error model (MixSIR).
}
}
| /man/write_JAGS_model.Rd | no_license | cran/MixSIAR | R | false | true | 1,557 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/write_JAGS_model.R
\name{write_JAGS_model}
\alias{write_JAGS_model}
\title{Write the JAGS model file}
\usage{
write_JAGS_model(
filename = "MixSIAR_model.txt",
resid_err = TRUE,
process_err = TRUE,
mix,
source
)
}
\arguments{
\item{filename}{the JAGS model file is saved in the working directory as 'filename'
(default is "MixSIAR_model.txt", but user can specify).}
\item{resid_err}{T/F: include residual error in the model?}
\item{process_err}{T/F: include process error in the model?}
\item{mix}{output from \code{\link{load_mix_data}}}
\item{source}{output from \code{\link{load_source_data}}}
}
\description{
\code{write_JAGS_model} creates "MixSIAR_model.txt", which is passed to JAGS
by \code{\link{run_model}} when the "RUN MODEL" button is clicked in the GUI.
Several model options will have already been specified when loading the mix
and source data, but here is where the error term options are selected:
\enumerate{
\item Residual * Process (resid_err = TRUE, process_err = TRUE)
\item Residual only (resid_err = TRUE, process_err = FALSE)
\item Process only (resid_err = FALSE, process_err = TRUE)
}
}
\details{
WARNING messages are displayed if:
\itemize{
\item resid_err = FALSE and process_err = FALSE are both selected.
\item N=1 mix data point and did not choose "Process only" error model (MixSIR)
\item Fitting each individual mix data point separately as a Fixed Effect,
but did not choose "Process only" error model (MixSIR).
}
}
|
#' @rdname stat_summary
#' @inheritParams stat_bin
#' @export
stat_summary_bin <- function(mapping = NULL, data = NULL,
geom = "pointrange", position = "identity",
...,
fun.data = NULL,
fun = NULL,
fun.max = NULL,
fun.min = NULL,
fun.args = list(),
bins = 30,
binwidth = NULL,
breaks = NULL,
na.rm = FALSE,
orientation = NA,
show.legend = NA,
inherit.aes = TRUE,
fun.y = deprecated(),
fun.ymin = deprecated(),
fun.ymax = deprecated()) {
if (lifecycle::is_present(fun.y)) {
deprecate_warn0("3.3.0", "stat_summary_bin(fun.y)", "stat_summary_bin(fun)")
fun = fun %||% fun.y
}
if (lifecycle::is_present(fun.ymin)) {
deprecate_warn0("3.3.0", "stat_summary_bin(fun.ymin)", "stat_summary_bin(fun.min)")
fun.min = fun.min %||% fun.ymin
}
if (lifecycle::is_present(fun.ymax)) {
deprecate_warn0("3.3.0", "stat_summary_bin(fun.ymax)", "stat_summary_bin(fun.max)")
fun.max = fun.max %||% fun.ymax
}
layer(
data = data,
mapping = mapping,
stat = StatSummaryBin,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list2(
fun.data = fun.data,
fun = fun,
fun.max = fun.max,
fun.min = fun.min,
fun.args = fun.args,
bins = bins,
binwidth = binwidth,
breaks = breaks,
na.rm = na.rm,
orientation = orientation,
...
)
)
}
#' @rdname ggplot2-ggproto
#' @format NULL
#' @usage NULL
#' @export
StatSummaryBin <- ggproto("StatSummaryBin", Stat,
required_aes = c("x", "y"),
extra_params = c("na.rm", "orientation"),
setup_params = function(data, params) {
params$flipped_aes <- has_flipped_aes(data, params, ambiguous = TRUE)
params
},
compute_group = function(data, scales, fun.data = NULL, fun = NULL,
fun.max = NULL, fun.min = NULL, fun.args = list(),
bins = 30, binwidth = NULL, breaks = NULL,
origin = NULL, right = FALSE, na.rm = FALSE,
flipped_aes = FALSE) {
data <- flip_data(data, flipped_aes)
fun <- make_summary_fun(fun.data, fun, fun.max, fun.min, fun.args)
x <- flipped_names(flipped_aes)$x
breaks <- bin2d_breaks(scales[[x]], breaks, origin, binwidth, bins, right = right)
data$bin <- cut(data$x, breaks, include.lowest = TRUE, labels = FALSE)
out <- dapply(data, "bin", fun)
locs <- bin_loc(breaks, out$bin)
out$x <- locs$mid
out$width <- if (scales[[x]]$is_discrete()) 0.9 else locs$length
out$flipped_aes <- flipped_aes
flip_data(out, flipped_aes)
}
)
make_summary_fun <- function(fun.data, fun, fun.max, fun.min, fun.args) {
force(fun.data)
force(fun)
force(fun.max)
force(fun.min)
force(fun.args)
if (!is.null(fun.data)) {
# Function that takes complete data frame as input
fun.data <- as_function(fun.data)
function(df) {
inject(fun.data(df$y, !!!fun.args))
}
} else if (!is.null(fun) || !is.null(fun.max) || !is.null(fun.min)) {
# Three functions that take vectors as inputs
call_f <- function(fun, x) {
if (is.null(fun)) return(NA_real_)
fun <- as_function(fun)
inject(fun(x, !!!fun.args))
}
function(df, ...) {
data_frame0(
ymin = call_f(fun.min, df$y),
y = call_f(fun, df$y),
ymax = call_f(fun.max, df$y)
)
}
} else {
cli::cli_inform("No summary function supplied, defaulting to {.fn mean_se}")
function(df) {
mean_se(df$y)
}
}
}
| /R/stat-summary-bin.R | no_license | cran/ggplot2 | R | false | false | 4,149 | r | #' @rdname stat_summary
#' @inheritParams stat_bin
#' @export
stat_summary_bin <- function(mapping = NULL, data = NULL,
geom = "pointrange", position = "identity",
...,
fun.data = NULL,
fun = NULL,
fun.max = NULL,
fun.min = NULL,
fun.args = list(),
bins = 30,
binwidth = NULL,
breaks = NULL,
na.rm = FALSE,
orientation = NA,
show.legend = NA,
inherit.aes = TRUE,
fun.y = deprecated(),
fun.ymin = deprecated(),
fun.ymax = deprecated()) {
if (lifecycle::is_present(fun.y)) {
deprecate_warn0("3.3.0", "stat_summary_bin(fun.y)", "stat_summary_bin(fun)")
fun = fun %||% fun.y
}
if (lifecycle::is_present(fun.ymin)) {
deprecate_warn0("3.3.0", "stat_summary_bin(fun.ymin)", "stat_summary_bin(fun.min)")
fun.min = fun.min %||% fun.ymin
}
if (lifecycle::is_present(fun.ymax)) {
deprecate_warn0("3.3.0", "stat_summary_bin(fun.ymax)", "stat_summary_bin(fun.max)")
fun.max = fun.max %||% fun.ymax
}
layer(
data = data,
mapping = mapping,
stat = StatSummaryBin,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list2(
fun.data = fun.data,
fun = fun,
fun.max = fun.max,
fun.min = fun.min,
fun.args = fun.args,
bins = bins,
binwidth = binwidth,
breaks = breaks,
na.rm = na.rm,
orientation = orientation,
...
)
)
}
#' @rdname ggplot2-ggproto
#' @format NULL
#' @usage NULL
#' @export
StatSummaryBin <- ggproto("StatSummaryBin", Stat,
required_aes = c("x", "y"),
extra_params = c("na.rm", "orientation"),
setup_params = function(data, params) {
params$flipped_aes <- has_flipped_aes(data, params, ambiguous = TRUE)
params
},
compute_group = function(data, scales, fun.data = NULL, fun = NULL,
fun.max = NULL, fun.min = NULL, fun.args = list(),
bins = 30, binwidth = NULL, breaks = NULL,
origin = NULL, right = FALSE, na.rm = FALSE,
flipped_aes = FALSE) {
data <- flip_data(data, flipped_aes)
fun <- make_summary_fun(fun.data, fun, fun.max, fun.min, fun.args)
x <- flipped_names(flipped_aes)$x
breaks <- bin2d_breaks(scales[[x]], breaks, origin, binwidth, bins, right = right)
data$bin <- cut(data$x, breaks, include.lowest = TRUE, labels = FALSE)
out <- dapply(data, "bin", fun)
locs <- bin_loc(breaks, out$bin)
out$x <- locs$mid
out$width <- if (scales[[x]]$is_discrete()) 0.9 else locs$length
out$flipped_aes <- flipped_aes
flip_data(out, flipped_aes)
}
)
make_summary_fun <- function(fun.data, fun, fun.max, fun.min, fun.args) {
force(fun.data)
force(fun)
force(fun.max)
force(fun.min)
force(fun.args)
if (!is.null(fun.data)) {
# Function that takes complete data frame as input
fun.data <- as_function(fun.data)
function(df) {
inject(fun.data(df$y, !!!fun.args))
}
} else if (!is.null(fun) || !is.null(fun.max) || !is.null(fun.min)) {
# Three functions that take vectors as inputs
call_f <- function(fun, x) {
if (is.null(fun)) return(NA_real_)
fun <- as_function(fun)
inject(fun(x, !!!fun.args))
}
function(df, ...) {
data_frame0(
ymin = call_f(fun.min, df$y),
y = call_f(fun, df$y),
ymax = call_f(fun.max, df$y)
)
}
} else {
cli::cli_inform("No summary function supplied, defaulting to {.fn mean_se}")
function(df) {
mean_se(df$y)
}
}
}
|
computeCost <- function(X, y, theta){
m = length(y)
return ((1/(2*m)) * sum((X %*% theta - y) ^ 2))
} | /exercise1/computeCost.R | no_license | Lemmawool/R-Practice | R | false | false | 105 | r | computeCost <- function(X, y, theta){
m = length(y)
return ((1/(2*m)) * sum((X %*% theta - y) ^ 2))
} |
## The function cacheSolve computes the inverse of matrix X.
## If it is already computed, then return the cached data.
## It uses the makeCacheMatrix "matrix" object that can
## cache its inverse.
## makeCacheMatrix function is a special "matrix" object.
## set: store the data matrix.
## get: return the data matrix.
## setinverse: store the inverse of the matrix
## getinverse: return the inverse of the matrix
makeCacheMatrix <- function(X = matrix()) {
invX <- NULL
set <- function(Y) {
X <<- Y # set X
invX <<- NULL
}
get <- function() X # return X
setinverse <- function(inverseX)
invX <<- inverseX
getinverse <- function() invX
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Return the inverse of 'X' if it is already computed, otherwise
## computes the inverse using 'solve', stores the inverse and
## return the inverse matrix.
cacheSolve <- function(X, ...) {
Xinv <- X$getinverse()
if(!is.null(Xinv)) {
message("getting cached data")
return(Xinv)
}
data <- X$get()
Xinv <- solve(data)
X$setinverse(Xinv)
Xinv
}
| /cachematrix.R | no_license | djusto/ProgrammingAssignment2 | R | false | false | 1,258 | r | ## The function cacheSolve computes the inverse of matrix X.
## If it is already computed, then return the cached data.
## It uses the makeCacheMatrix "matrix" object that can
## cache its inverse.
## makeCacheMatrix function is a special "matrix" object.
## set: store the data matrix.
## get: return the data matrix.
## setinverse: store the inverse of the matrix
## getinverse: return the inverse of the matrix
makeCacheMatrix <- function(X = matrix()) {
invX <- NULL
set <- function(Y) {
X <<- Y # set X
invX <<- NULL
}
get <- function() X # return X
setinverse <- function(inverseX)
invX <<- inverseX
getinverse <- function() invX
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Return the inverse of 'X' if it is already computed, otherwise
## computes the inverse using 'solve', stores the inverse and
## return the inverse matrix.
cacheSolve <- function(X, ...) {
Xinv <- X$getinverse()
if(!is.null(Xinv)) {
message("getting cached data")
return(Xinv)
}
data <- X$get()
Xinv <- solve(data)
X$setinverse(Xinv)
Xinv
}
|
defExonicRegions <-
function(regionsGene)
{
## regionsGene: matrix with the structure of the exons of a gene
## we sort the exons based on the genomic start
if(is.unsorted(regionsGene$Exon.Chr.Start..bp.,))
{
regionsGene <- regionsGene[order(regionsGene$Exon.Chr.Start..bp.),]
}
## we check whether there are regions with length 1bp
if(length(which(regionsGene[,1]==regionsGene[,2]))>0)
{
regionsGene <- regionsGene[-which(regionsGene[,1]==regionsGene[,2]),]
}
## we check that there is no overlpapping region anin case me merge the region
j <-2
for (i in 2:nrow(regionsGene))
{
if(j>nrow(regionsGene)){
break
}
if((regionsGene[j,1] - regionsGene[j-1,2]) <1)
{
## we check whether the exon is not included already in the exon
if (regionsGene[j,2] - regionsGene[j-1,2]>0){
regionsGene[j-1,2] <- regionsGene[j,2]
regionsGene <- regionsGene[-j,]
}else{
regionsGene <- regionsGene[-j,]
}
}else{
j <-j+1
}
}
rm(j,i)
return(regionsGene)
}
| /R/defExonicRegions.R | no_license | gughi/eQTLPipeline | R | false | false | 1,079 | r | defExonicRegions <-
function(regionsGene)
{
## regionsGene: matrix with the structure of the exons of a gene
## we sort the exons based on the genomic start
if(is.unsorted(regionsGene$Exon.Chr.Start..bp.,))
{
regionsGene <- regionsGene[order(regionsGene$Exon.Chr.Start..bp.),]
}
## we check whether there are regions with length 1bp
if(length(which(regionsGene[,1]==regionsGene[,2]))>0)
{
regionsGene <- regionsGene[-which(regionsGene[,1]==regionsGene[,2]),]
}
## we check that there is no overlpapping region anin case me merge the region
j <-2
for (i in 2:nrow(regionsGene))
{
if(j>nrow(regionsGene)){
break
}
if((regionsGene[j,1] - regionsGene[j-1,2]) <1)
{
## we check whether the exon is not included already in the exon
if (regionsGene[j,2] - regionsGene[j-1,2]>0){
regionsGene[j-1,2] <- regionsGene[j,2]
regionsGene <- regionsGene[-j,]
}else{
regionsGene <- regionsGene[-j,]
}
}else{
j <-j+1
}
}
rm(j,i)
return(regionsGene)
}
|
# Packages and helpers specific to model fitting and prediction
if (!exists("MODELING_R__")) {
library("glmnet")
library("gbm")
.get_mm <- function (d, f, discrete_y = TRUE) {
# Given a data.frame and formula, return the model matrix X and y as a list
# Args:
# d: data frame used for training
# f: model formula
# discrete_y: boolean indicating whether y is discrete or continuous
# Reutrns:
# List with elements X (the model matrix) and y (labels, extracted from the
# LHS of formula f)
X <- model.matrix(f, d)
# Extract target column from LHS of f
y <- d[[as.character(rlang::f_lhs(f))]]
# Heuristic to determine whether y should be discrete or continuous
if (discrete_y) {
y <- as.factor(y)
}
list(X = X, y = y)
}
pred_with_mm <- function(d, f, m, use_column, as = NULL, ...) {
# Generate predictions and appends to the data frame as a new column, for a
# model by first converting the data to a model matrix based on the formula
# provided
# Args:
# d: data frame to predict for
# f: model formula
# m: prediction model
# use_column: the column from prediction results to keep in the data frame
# e.g., for 1 for glmnet (single column), and 2 for randomForest
# (assuming the positive class prediction is of interest)
# as: character name of prediction column to add
# ...: other arguments passed to the general predict function
# Reutrns:
# data frame with single column of name `as` containing predictions
mm <- .get_mm(d, f) # Don't worry about y --- not used
if (is.null(as)) {
predict(m, mm$X, ...)[, use_column]
} else {
d %>%
transmute(!!as := predict(m, mm$X, ...)[, use_column])
}
}
fit_glmnet <-
function(d,
f,
family = "binomial",
alpha = 1,
...) {
# Fits a glmnet model, taking care of model matrix and other junk
#
# Args:
# d: data frame used for training
# f: model formula
# family: model type, passed as the family argument to cv.glmnet
# alpha: 1 for Lasso, 0 for Ridge; passed to cv.glmnet
# ...: arguments passed to cv.glmnet
#
# Reutrns:
# cv.glmnet object
# Extract model matrix given data and formula
mm <-
.get_mm(d, f, discrete_y = ifelse(family == "binomial", TRUE, FALSE))
X <- mm$X
y <- mm$y
cv.glmnet(X,
y,
family = family,
alpha = alpha,
parallel = TRUE,
...)
}
mm_lr <- function(df, f, beta) {
# manually calculate logistic regression given a feature matrix and a beta
# coef matrix representing a series of beta coefs
#
# Args:
# mm: matrix including the intercept of size n x m
# beta: beta coefs of size k x m
#
# Return:
# df: modified df with pos_sample_id and pos_sample_preds
# with n * n_pos_samples rows
prob_mm <- inv.logit(.get_mm(df, f)$X %*% t(beta))
n_pos_samples <- ncol(prob_mm)
prob_mm_vec <- as.vector(t(prob_mm))
df %>%
mutate(pos_sample_id = map(1:nrow(df), ~ 1:n_pos_samples)) %>%
unnest(pos_sample_id) %>%
mutate(pos_sample_preds = prob_mm_vec)
}
recall_from_pos_samples <-
function(posterior_preds,
site = F,
risk_col = "pos_sample_choice",
outcome_col = "outcome") {
# Obtain recall mean and SD from posterior samples
#
# Args:
# posterior_preds: matrix including the intercept of size n x m
# site: if aggregate by site (for LSI-R data)
# risk_col: risk column name
# outcome_col: outcome column name
#
# Return:
# posterior recalls for each proportion of individuals detained
if (site) {
return(
posterior_preds %>%
eval_recall(risk_col = risk_col, outcome_col = outcome_col,
groupby_vars = c("model", "features", "target", "user_group", "pos_sample_id", "site")) %>%
group_by(model, features, target, user_group, prop, site) %>%
summarize(
recall_mean = mean(recall),
recall_sd = sd(recall)
) %>%
ungroup()
)
} else {
return(
posterior_preds %>%
eval_recall(risk_col = risk_col, outcome_col = outcome_col,
groupby_vars = c("model", "features", "target", "user_group", "pos_sample_id")) %>%
group_by(model, features, target, user_group, prop) %>%
summarize(
recall_mean = mean(recall),
recall_sd = sd(recall)
) %>%
ungroup()
)
}
}
pred_loo <- function(d, fs, ms, models = names(ms)) {
# Given some data frame d, compute LOO predictions for given formulas
future_map_dfr(1:nrow(d), .progress = TRUE, function(i) {
# Fit models leaving the i-th row out
train <- d[-i, ]
test <- d[i, ]
models_df <- expand.grid(
features = names(fs),
model = models,
stringsAsFactors = FALSE
) %>%
as_tibble() %>%
mutate(f = fs[features],
m = map2(f, model, ~ ms[[.y]](.x, train)))
models_df %>%
mutate(index = i,
preds = pmap(list(model, m, f, list(test)), get_preds)) %>%
unnest(preds) %>%
select(-f, -m)
}) %>%
mutate(choice =
SURVEY_SCALE[vapply(pred,
function(x)
which.min(abs(x - SURVEY_SCALE)),
integer(1))])
}
# Compas covariates ------------------------------------------------------
df_covars <- c("sex",
"age",
"juv_fel_count",
"juv_misd_count",
"priors_count",
"degree")
df_race <- c("race")
df_recid_target <- "two_year_recid"
df_violent_target <- "is_violent_recid"
compas_recid_score <- "compas_decile_score"
compas_violent_score <- "v_decile_score"
# Setup for modeling
df_covariates <- list(
full = c(
df_race,
df_covars,
compas_recid_score,
compas_violent_score
),
long = c(df_covars, compas_recid_score, compas_violent_score),
short = df_covars
)
df_targets <- c(recid = df_recid_target,
violent = df_violent_target)
# LSI covariates ----------------------------------------------------------
lsi_target <- "outcome"
lsi_covars_full <-
c("ch",
"ee",
"fin",
"fam",
"acc",
"leisure",
"peers",
"drugs",
"mh",
"cog")
lsi_covars_long <-
c(
"ch_cat",
"ee_cat",
"fin_cat",
"fam_cat",
"acc_cat",
"leisure_cat",
"peers_cat",
"drugs_cat",
"mh_cat",
"cog_cat"
)
lsi_covars_short <- "ch_cat"
lsi_covars_demo <- c("age", "male")
lsi_formulas <- c(
full = reformulate(
c(lsi_covars_demo, lsi_covars_full, lsi_covars_long),
lsi_target
),
long = reformulate(c(lsi_covars_demo, lsi_covars_long), lsi_target),
short = reformulate(c(lsi_covars_demo, lsi_covars_short), lsi_target)
)
# Model specifications ----------------------------------------------------
model_specs <- c(
logit = function(f, x)
glm(f, x, family = binomial),
gbm = function(f, x)
gbm(
f,
data = x,
distribution = "adaboost",
n.trees = 1000,
shrinkage = 0.01,
train.fraction = .8,
interaction.depth = 5,
n.cores = 1
),
l1 = function(f, x)
fit_glmnet(x, f),
l2 = function(f, x)
fit_glmnet(x, f, alpha = 0)
)
get_preds <- function(typ, mod, fun, dat) {
pred_specs <- c(
logit = function(f, m, d)
d %>%
mutate(pred = predict(m, d, type = "response")),
gbm = function(f, m, d)
d %>%
mutate(pred = predict(
m,
d,
type = "response",
n.trees = gbm.perf(m, method = "test",
plot.it = FALSE)
)),
l1 = function(f, m, d)
d %>%
mutate(pred = pred_with_mm(
d, f, m, 1,
s = "lambda.min", type = "response"
)),
l2 = function(f, m, d)
d %>%
mutate(pred = pred_with_mm(
d, f, m, 1,
s = "lambda.min", type = "response"
))
)
pred_fun <- pred_specs[[typ]]
pred_fun(fun, mod, dat)
}
MODELING_R__ <- TRUE
} else {
message("modeling.R already loaded")
}
| /src/modeling.R | no_license | jballesterosc/recidivism-predictions | R | false | false | 8,929 | r | # Packages and helpers specific to model fitting and prediction
if (!exists("MODELING_R__")) {
library("glmnet")
library("gbm")
.get_mm <- function (d, f, discrete_y = TRUE) {
# Given a data.frame and formula, return the model matrix X and y as a list
# Args:
# d: data frame used for training
# f: model formula
# discrete_y: boolean indicating whether y is discrete or continuous
# Reutrns:
# List with elements X (the model matrix) and y (labels, extracted from the
# LHS of formula f)
X <- model.matrix(f, d)
# Extract target column from LHS of f
y <- d[[as.character(rlang::f_lhs(f))]]
# Heuristic to determine whether y should be discrete or continuous
if (discrete_y) {
y <- as.factor(y)
}
list(X = X, y = y)
}
pred_with_mm <- function(d, f, m, use_column, as = NULL, ...) {
# Generate predictions and appends to the data frame as a new column, for a
# model by first converting the data to a model matrix based on the formula
# provided
# Args:
# d: data frame to predict for
# f: model formula
# m: prediction model
# use_column: the column from prediction results to keep in the data frame
# e.g., for 1 for glmnet (single column), and 2 for randomForest
# (assuming the positive class prediction is of interest)
# as: character name of prediction column to add
# ...: other arguments passed to the general predict function
# Reutrns:
# data frame with single column of name `as` containing predictions
mm <- .get_mm(d, f) # Don't worry about y --- not used
if (is.null(as)) {
predict(m, mm$X, ...)[, use_column]
} else {
d %>%
transmute(!!as := predict(m, mm$X, ...)[, use_column])
}
}
fit_glmnet <-
function(d,
f,
family = "binomial",
alpha = 1,
...) {
# Fits a glmnet model, taking care of model matrix and other junk
#
# Args:
# d: data frame used for training
# f: model formula
# family: model type, passed as the family argument to cv.glmnet
# alpha: 1 for Lasso, 0 for Ridge; passed to cv.glmnet
# ...: arguments passed to cv.glmnet
#
# Reutrns:
# cv.glmnet object
# Extract model matrix given data and formula
mm <-
.get_mm(d, f, discrete_y = ifelse(family == "binomial", TRUE, FALSE))
X <- mm$X
y <- mm$y
cv.glmnet(X,
y,
family = family,
alpha = alpha,
parallel = TRUE,
...)
}
mm_lr <- function(df, f, beta) {
# manually calculate logistic regression given a feature matrix and a beta
# coef matrix representing a series of beta coefs
#
# Args:
# mm: matrix including the intercept of size n x m
# beta: beta coefs of size k x m
#
# Return:
# df: modified df with pos_sample_id and pos_sample_preds
# with n * n_pos_samples rows
prob_mm <- inv.logit(.get_mm(df, f)$X %*% t(beta))
n_pos_samples <- ncol(prob_mm)
prob_mm_vec <- as.vector(t(prob_mm))
df %>%
mutate(pos_sample_id = map(1:nrow(df), ~ 1:n_pos_samples)) %>%
unnest(pos_sample_id) %>%
mutate(pos_sample_preds = prob_mm_vec)
}
recall_from_pos_samples <-
function(posterior_preds,
site = F,
risk_col = "pos_sample_choice",
outcome_col = "outcome") {
# Obtain recall mean and SD from posterior samples
#
# Args:
# posterior_preds: matrix including the intercept of size n x m
# site: if aggregate by site (for LSI-R data)
# risk_col: risk column name
# outcome_col: outcome column name
#
# Return:
# posterior recalls for each proportion of individuals detained
if (site) {
return(
posterior_preds %>%
eval_recall(risk_col = risk_col, outcome_col = outcome_col,
groupby_vars = c("model", "features", "target", "user_group", "pos_sample_id", "site")) %>%
group_by(model, features, target, user_group, prop, site) %>%
summarize(
recall_mean = mean(recall),
recall_sd = sd(recall)
) %>%
ungroup()
)
} else {
return(
posterior_preds %>%
eval_recall(risk_col = risk_col, outcome_col = outcome_col,
groupby_vars = c("model", "features", "target", "user_group", "pos_sample_id")) %>%
group_by(model, features, target, user_group, prop) %>%
summarize(
recall_mean = mean(recall),
recall_sd = sd(recall)
) %>%
ungroup()
)
}
}
pred_loo <- function(d, fs, ms, models = names(ms)) {
# Given some data frame d, compute LOO predictions for given formulas
future_map_dfr(1:nrow(d), .progress = TRUE, function(i) {
# Fit models leaving the i-th row out
train <- d[-i, ]
test <- d[i, ]
models_df <- expand.grid(
features = names(fs),
model = models,
stringsAsFactors = FALSE
) %>%
as_tibble() %>%
mutate(f = fs[features],
m = map2(f, model, ~ ms[[.y]](.x, train)))
models_df %>%
mutate(index = i,
preds = pmap(list(model, m, f, list(test)), get_preds)) %>%
unnest(preds) %>%
select(-f, -m)
}) %>%
mutate(choice =
SURVEY_SCALE[vapply(pred,
function(x)
which.min(abs(x - SURVEY_SCALE)),
integer(1))])
}
# Compas covariates ------------------------------------------------------
df_covars <- c("sex",
"age",
"juv_fel_count",
"juv_misd_count",
"priors_count",
"degree")
df_race <- c("race")
df_recid_target <- "two_year_recid"
df_violent_target <- "is_violent_recid"
compas_recid_score <- "compas_decile_score"
compas_violent_score <- "v_decile_score"
# Setup for modeling
df_covariates <- list(
full = c(
df_race,
df_covars,
compas_recid_score,
compas_violent_score
),
long = c(df_covars, compas_recid_score, compas_violent_score),
short = df_covars
)
df_targets <- c(recid = df_recid_target,
violent = df_violent_target)
# LSI covariates ----------------------------------------------------------
lsi_target <- "outcome"
lsi_covars_full <-
c("ch",
"ee",
"fin",
"fam",
"acc",
"leisure",
"peers",
"drugs",
"mh",
"cog")
lsi_covars_long <-
c(
"ch_cat",
"ee_cat",
"fin_cat",
"fam_cat",
"acc_cat",
"leisure_cat",
"peers_cat",
"drugs_cat",
"mh_cat",
"cog_cat"
)
lsi_covars_short <- "ch_cat"
lsi_covars_demo <- c("age", "male")
lsi_formulas <- c(
full = reformulate(
c(lsi_covars_demo, lsi_covars_full, lsi_covars_long),
lsi_target
),
long = reformulate(c(lsi_covars_demo, lsi_covars_long), lsi_target),
short = reformulate(c(lsi_covars_demo, lsi_covars_short), lsi_target)
)
# Model specifications ----------------------------------------------------
model_specs <- c(
logit = function(f, x)
glm(f, x, family = binomial),
gbm = function(f, x)
gbm(
f,
data = x,
distribution = "adaboost",
n.trees = 1000,
shrinkage = 0.01,
train.fraction = .8,
interaction.depth = 5,
n.cores = 1
),
l1 = function(f, x)
fit_glmnet(x, f),
l2 = function(f, x)
fit_glmnet(x, f, alpha = 0)
)
get_preds <- function(typ, mod, fun, dat) {
pred_specs <- c(
logit = function(f, m, d)
d %>%
mutate(pred = predict(m, d, type = "response")),
gbm = function(f, m, d)
d %>%
mutate(pred = predict(
m,
d,
type = "response",
n.trees = gbm.perf(m, method = "test",
plot.it = FALSE)
)),
l1 = function(f, m, d)
d %>%
mutate(pred = pred_with_mm(
d, f, m, 1,
s = "lambda.min", type = "response"
)),
l2 = function(f, m, d)
d %>%
mutate(pred = pred_with_mm(
d, f, m, 1,
s = "lambda.min", type = "response"
))
)
pred_fun <- pred_specs[[typ]]
pred_fun(fun, mod, dat)
}
MODELING_R__ <- TRUE
} else {
message("modeling.R already loaded")
}
|
file1<-read_excel("Centroid_Location1.xls")
install.packages("readxl")
#access library
library("readxl")
sheet1 <- read_excel("Centroid_Location1.xlsx", sheet = 1)
sheet2 <- read_excel("Centroid_Location1.xlsx", sheet = 2)
sheet3 <- read_excel("Centroid_Location1.xlsx", sheet = 3)
sheet4 <- read_excel("Centroid_Location1.xlsx", sheet = 4)
sheet5 <- read_excel("Centroid_Location1.xlsx", sheet = 5)
sheet6 <- read_excel("Centroid_Location1.xlsx", sheet = 6)
sheet7 <- read_excel("Centroid_Location1.xlsx", sheet = 7)
sheet8 <- read_excel("Centroid_Location1.xlsx", sheet = 8)
sheet9 <- read_excel("Centroid_Location1.xlsx", sheet = 9)
sheet10 <- read_excel("Centroid_Location1.xlsx", sheet = 10)
sheet11 <- read_excel("Centroid_Location1.xlsx", sheet = 11)
sheet12 <- read_excel("Centroid_Location1.xlsx", sheet = 12)
sheet13 <- read_excel("Centroid_Location1.xlsx", sheet = 13)
sheet14 <- read_excel("Centroid_Location1.xlsx", sheet = 14)
sheet15 <- read_excel("Centroid_Location1.xlsx", sheet = 15)
sheet16 <- read_excel("Centroid_Location1.xlsx", sheet = 16)
sheet17 <- read_excel("Centroid_Location1.xlsx", sheet = 17)
sheet18 <- read_excel("Centroid_Location1.xlsx", sheet = 18)
sheet19 <- read_excel("Centroid_Location1.xlsx", sheet = 19)
sheet20 <- read_excel("Centroid_Location1.xlsx", sheet = 20)
sheet21 <- read_excel("Centroid_Location1.xlsx", sheet = 21)
sheet22 <- read_excel("Centroid_Location1.xlsx", sheet = 22)
sheet23 <- read_excel("Centroid_Location1.xlsx", sheet = 23)
sheet24 <- read_excel("Centroid_Location1.xlsx", sheet = 24)
sheet25 <- read_excel("Centroid_Location1.xlsx", sheet = 25)
sheet26 <- read_excel("Centroid_Location1.xlsx", sheet = 26)
sheet27 <- read_excel("Centroid_Location1.xlsx", sheet = 27)
sheet28 <- read_excel("Centroid_Location1.xlsx", sheet = 28)
sheet29 <- read_excel("Centroid_Location1.xlsx", sheet = 29)
sheet30 <- read_excel("Centroid_Location1.xlsx", sheet = 30)
sheet31 <- read_excel("Centroid_Location1.xlsx", sheet = 31)
sheet32 <- read_excel("Centroid_Location1.xlsx", sheet = 32)
sheet33 <- read_excel("Centroid_Location1.xlsx", sheet = 33)
sheet34 <- read_excel("Centroid_Location1.xlsx", sheet = 34)
sheet35 <- read_excel("Centroid_Location1.xlsx", sheet = 35)
sheet36 <- read_excel("Centroid_Location1.xlsx", sheet = 36)
sheet37 <- read_excel("Centroid_Location1.xlsx", sheet = 37)
sheet38 <- read_excel("Centroid_Location1.xlsx", sheet = 38)
sheet39 <- read_excel("Centroid_Location1.xlsx", sheet = 39)
sheet40 <- read_excel("Centroid_Location1.xlsx", sheet = 40)
sheet41 <- read_excel("Centroid_Location1.xlsx", sheet = 41)
sheet42 <- read_excel("Centroid_Location1.xlsx", sheet = 42)
sheet43 <- read_excel("Centroid_Location1.xlsx", sheet = 43)
sheet44 <- read_excel("Centroid_Location1.xlsx", sheet = 44)
sheet45 <- read_excel("Centroid_Location1.xlsx", sheet = 45)
sheet46 <- read_excel("Centroid_Location1.xlsx", sheet = 46)
sheet47 <- read_excel("Centroid_Location1.xlsx", sheet = 47)
sheet48 <- read_excel("Centroid_Location1.xlsx", sheet = 48)
sheet49 <- read_excel("Centroid_Location1.xlsx", sheet = 49)
sheet50 <- read_excel("Centroid_Location1.xlsx", sheet = 50)
| /facility location/Thesis_facility_location/code/excel_upload.R | no_license | ranasingh-gkp/Thesis_facility_location | R | false | false | 3,140 | r | file1<-read_excel("Centroid_Location1.xls")
install.packages("readxl")
#access library
library("readxl")
sheet1 <- read_excel("Centroid_Location1.xlsx", sheet = 1)
sheet2 <- read_excel("Centroid_Location1.xlsx", sheet = 2)
sheet3 <- read_excel("Centroid_Location1.xlsx", sheet = 3)
sheet4 <- read_excel("Centroid_Location1.xlsx", sheet = 4)
sheet5 <- read_excel("Centroid_Location1.xlsx", sheet = 5)
sheet6 <- read_excel("Centroid_Location1.xlsx", sheet = 6)
sheet7 <- read_excel("Centroid_Location1.xlsx", sheet = 7)
sheet8 <- read_excel("Centroid_Location1.xlsx", sheet = 8)
sheet9 <- read_excel("Centroid_Location1.xlsx", sheet = 9)
sheet10 <- read_excel("Centroid_Location1.xlsx", sheet = 10)
sheet11 <- read_excel("Centroid_Location1.xlsx", sheet = 11)
sheet12 <- read_excel("Centroid_Location1.xlsx", sheet = 12)
sheet13 <- read_excel("Centroid_Location1.xlsx", sheet = 13)
sheet14 <- read_excel("Centroid_Location1.xlsx", sheet = 14)
sheet15 <- read_excel("Centroid_Location1.xlsx", sheet = 15)
sheet16 <- read_excel("Centroid_Location1.xlsx", sheet = 16)
sheet17 <- read_excel("Centroid_Location1.xlsx", sheet = 17)
sheet18 <- read_excel("Centroid_Location1.xlsx", sheet = 18)
sheet19 <- read_excel("Centroid_Location1.xlsx", sheet = 19)
sheet20 <- read_excel("Centroid_Location1.xlsx", sheet = 20)
sheet21 <- read_excel("Centroid_Location1.xlsx", sheet = 21)
sheet22 <- read_excel("Centroid_Location1.xlsx", sheet = 22)
sheet23 <- read_excel("Centroid_Location1.xlsx", sheet = 23)
sheet24 <- read_excel("Centroid_Location1.xlsx", sheet = 24)
sheet25 <- read_excel("Centroid_Location1.xlsx", sheet = 25)
sheet26 <- read_excel("Centroid_Location1.xlsx", sheet = 26)
sheet27 <- read_excel("Centroid_Location1.xlsx", sheet = 27)
sheet28 <- read_excel("Centroid_Location1.xlsx", sheet = 28)
sheet29 <- read_excel("Centroid_Location1.xlsx", sheet = 29)
sheet30 <- read_excel("Centroid_Location1.xlsx", sheet = 30)
sheet31 <- read_excel("Centroid_Location1.xlsx", sheet = 31)
sheet32 <- read_excel("Centroid_Location1.xlsx", sheet = 32)
sheet33 <- read_excel("Centroid_Location1.xlsx", sheet = 33)
sheet34 <- read_excel("Centroid_Location1.xlsx", sheet = 34)
sheet35 <- read_excel("Centroid_Location1.xlsx", sheet = 35)
sheet36 <- read_excel("Centroid_Location1.xlsx", sheet = 36)
sheet37 <- read_excel("Centroid_Location1.xlsx", sheet = 37)
sheet38 <- read_excel("Centroid_Location1.xlsx", sheet = 38)
sheet39 <- read_excel("Centroid_Location1.xlsx", sheet = 39)
sheet40 <- read_excel("Centroid_Location1.xlsx", sheet = 40)
sheet41 <- read_excel("Centroid_Location1.xlsx", sheet = 41)
sheet42 <- read_excel("Centroid_Location1.xlsx", sheet = 42)
sheet43 <- read_excel("Centroid_Location1.xlsx", sheet = 43)
sheet44 <- read_excel("Centroid_Location1.xlsx", sheet = 44)
sheet45 <- read_excel("Centroid_Location1.xlsx", sheet = 45)
sheet46 <- read_excel("Centroid_Location1.xlsx", sheet = 46)
sheet47 <- read_excel("Centroid_Location1.xlsx", sheet = 47)
sheet48 <- read_excel("Centroid_Location1.xlsx", sheet = 48)
sheet49 <- read_excel("Centroid_Location1.xlsx", sheet = 49)
sheet50 <- read_excel("Centroid_Location1.xlsx", sheet = 50)
|
c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 239615
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 236510
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 236510
c
c Input Parameter (command line, file):
c input filename QBFLIB/Kronegger-Pfandler-Pichler/bomb/p20-5.pddl_planlen=40.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 8300
c no.of clauses 239615
c no.of taut cls 4195
c
c Output Parameters:
c remaining no.of clauses 236510
c
c QBFLIB/Kronegger-Pfandler-Pichler/bomb/p20-5.pddl_planlen=40.qdimacs 8300 239615 E1 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 29 30 31 32 33 35 36 37 40 41 42 43 44 45 48 49 50 51 52 54 55 56 57 59 61 62 63 64 65 67 68 71 72 73 75 78 79 80 81 82 83 85 86 87 88 90 91 93 94 95 96 97 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300] 4195 20 5180 236510 RED
| /code/dcnf-ankit-optimized/Results/QBFLIB-2018/E1/Experiments/Kronegger-Pfandler-Pichler/bomb/p20-5.pddl_planlen=40/p20-5.pddl_planlen=40.R | no_license | arey0pushpa/dcnf-autarky | R | false | false | 15,784 | r | c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 239615
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 236510
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 236510
c
c Input Parameter (command line, file):
c input filename QBFLIB/Kronegger-Pfandler-Pichler/bomb/p20-5.pddl_planlen=40.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 8300
c no.of clauses 239615
c no.of taut cls 4195
c
c Output Parameters:
c remaining no.of clauses 236510
c
c QBFLIB/Kronegger-Pfandler-Pichler/bomb/p20-5.pddl_planlen=40.qdimacs 8300 239615 E1 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 29 30 31 32 33 35 36 37 40 41 42 43 44 45 48 49 50 51 52 54 55 56 57 59 61 62 63 64 65 67 68 71 72 73 75 78 79 80 81 82 83 85 86 87 88 90 91 93 94 95 96 97 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300] 4195 20 5180 236510 RED
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sof.schaffer.function.2.R
\name{makeSchafferN2Function}
\alias{makeSchafferN2Function}
\title{Modified Schaffer Function N. 2}
\usage{
makeSchafferN2Function()
}
\value{
[\code{smoof_single_objective_function}]
}
\description{
Second function by Schaffer. The defintion is given by the formula
\deqn{f(\mathbf{x}) = 0.5 + \frac{\sin^2(\mathbf{x}_1^2 - \mathbf{x}_2^2) - 0.5}{(1 + 0.001(\mathbf{x}_1^2 + \mathbf{x}_2^2))^2}}
subject to \eqn{\mathbf{x}_i \in [-100, 100], i = 1, 2}.
}
\references{
S. K. Mishra, Some New Test Functions For Global Optimization
And Performance of Repulsive Particle Swarm Method.
}
| /man/makeSchafferN2Function.Rd | no_license | mllg/smoof | R | false | true | 691 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sof.schaffer.function.2.R
\name{makeSchafferN2Function}
\alias{makeSchafferN2Function}
\title{Modified Schaffer Function N. 2}
\usage{
makeSchafferN2Function()
}
\value{
[\code{smoof_single_objective_function}]
}
\description{
Second function by Schaffer. The defintion is given by the formula
\deqn{f(\mathbf{x}) = 0.5 + \frac{\sin^2(\mathbf{x}_1^2 - \mathbf{x}_2^2) - 0.5}{(1 + 0.001(\mathbf{x}_1^2 + \mathbf{x}_2^2))^2}}
subject to \eqn{\mathbf{x}_i \in [-100, 100], i = 1, 2}.
}
\references{
S. K. Mishra, Some New Test Functions For Global Optimization
And Performance of Repulsive Particle Swarm Method.
}
|
#KoNLP 설치
install.packages("KoNLP")
library(KoNLP)
library(stringi)
#KoNLP를 불러올때 에러가 난다면 JAVA의 경로를 다시 세팅
#Sys.setenv(JAVA_HOME="C:/Program Files/Java/jre1.8.0_131/")
#문석 대상 텍스트
sentence1 = "류현진(30·LA다저스)이 복귀전에서 5회를 버티지 못했다. 하지만 충분히 박수를 받을만한 경기였다."
sentence2 = "샌프란시스코 자이언츠 내야수 황재균은 2일(한국시간) PNC파크에서 열린 피츠버그 파이어리츠와의 원정 시리즈 두번째 경기에서 8회초 대타로 등장, 상대 투수 후안 니카시오를 상대로 좌익수 방면 2루타를 때렸다."
#명사만 추출
extractNoun(sentence1)
extractNoun(sentence2)
# 세종사전 사용하기
useSejongDic()
# NIA(한국정보화진흥원) 형태소사전 사용하기
useNIADic(category_dic_nms = "sports")
#POS 태깅 정보 추출
SimplePos22(sentence1)
#################################################
# NLP4kec와 비교
library(NLP4kec)
test = text_parser(path = "./test_text.csv", language = "ko", korDicPath = "./dictionary.txt")
test
| /FastCampus/Week_3/konlp_test.R | no_license | NamyounKim/RWork | R | false | false | 1,132 | r | #KoNLP 설치
install.packages("KoNLP")
library(KoNLP)
library(stringi)
#KoNLP를 불러올때 에러가 난다면 JAVA의 경로를 다시 세팅
#Sys.setenv(JAVA_HOME="C:/Program Files/Java/jre1.8.0_131/")
#문석 대상 텍스트
sentence1 = "류현진(30·LA다저스)이 복귀전에서 5회를 버티지 못했다. 하지만 충분히 박수를 받을만한 경기였다."
sentence2 = "샌프란시스코 자이언츠 내야수 황재균은 2일(한국시간) PNC파크에서 열린 피츠버그 파이어리츠와의 원정 시리즈 두번째 경기에서 8회초 대타로 등장, 상대 투수 후안 니카시오를 상대로 좌익수 방면 2루타를 때렸다."
#명사만 추출
extractNoun(sentence1)
extractNoun(sentence2)
# 세종사전 사용하기
useSejongDic()
# NIA(한국정보화진흥원) 형태소사전 사용하기
useNIADic(category_dic_nms = "sports")
#POS 태깅 정보 추출
SimplePos22(sentence1)
#################################################
# NLP4kec와 비교
library(NLP4kec)
test = text_parser(path = "./test_text.csv", language = "ko", korDicPath = "./dictionary.txt")
test
|
\name{several.breakpoints}
\alias{several.breakpoints}
\title{several breakpoints}
\description{Zero-one loss when breakpoint annotations are considered to mean
presence of 1 or more breakpoints.}
\usage{several.breakpoints(counts, anns)}
\arguments{
\item{counts}{Counts of breakpoints of model.}
\item{anns}{Annotations.}
}
\value{Matrix of 0 and 1.}
\author{Toby Dylan Hocking}
| /man/several.breakpoints.Rd | no_license | tdhock/bams | R | false | false | 411 | rd | \name{several.breakpoints}
\alias{several.breakpoints}
\title{several breakpoints}
\description{Zero-one loss when breakpoint annotations are considered to mean
presence of 1 or more breakpoints.}
\usage{several.breakpoints(counts, anns)}
\arguments{
\item{counts}{Counts of breakpoints of model.}
\item{anns}{Annotations.}
}
\value{Matrix of 0 and 1.}
\author{Toby Dylan Hocking}
|
# Data Management 1----
rm(list=ls())
library(plyr)
library(tidyverse)
library(magrittr)
library(ggiraph)
library(stargazer)
library(foreign)
library(ggthemes)
library(readxl)
library(bit64)
library(data.table)
library(plm)
load("data/aiddata.Rdata")
countrynames2<- c("Cabo Verde", "Gambia, The", "Ivory Coast","Angola","Benin","Botswana","Burkina Faso","Burundi","Cameroon","Cape Verde","Central African Republic","Chad",
"Comoros","Congo, Rep.","Congo, Dem. Rep.","Cote d'Ivoire", "Cote D'Ivoire","Djibouti","Equatorial Guinea","Eritrea","Ethiopia", "Gabon", "Gambia"
,"Ghana", "Guinea","Guinea-Bissau","Kenya","Lesotho","Liberia","Madagascar","Malawi","Mali","Mauritania","Mauritius","Mozambique","Namibia","Niger",
"Nigeria","Rwanda","Sao Tome and Principe","Senegal","Seychelles","Sierra Leone","Somalia","South Africa","Swaziland","Tanzania","Togo","Uganda","Zambia","Zimbabwe", "Sudan")
countrynames<- c("Angola","Benin","Botswana","Burkina Faso","Burundi","Cameroon","Cape Verde","Central African Republic","Chad",
"Comoros","Congo, Rep.","Congo, Dem. Rep.","Ivory Coast","Cote d'Ivoire", "Cote D'Ivoire","Djibouti","Equatorial Guinea","Eritrea","Ethiopia", "Gabon", "Gambia"
,"Ghana", "Guinea","Guinea-Bissau","Kenya","Lesotho","Liberia","Madagascar","Malawi","Mali","Mauritania","Mauritius","Mozambique","Namibia","Niger",
"Nigeria","Rwanda","Sao Tome and Principe","Senegal","Seychelles","Sierra Leone","Somalia","South Africa","Swaziland","Tanzania","Togo","Uganda","Zambia","Zimbabwe", "Sudan")
countrynames3<- c("Cabo Verde", "Gambia, The", "Ivory Coast","Angola","Benin","Botswana","Burkina Faso","Burundi","Cameroon","Cape Verde","Central African Republic","Chad",
"Comoros","Congo, Rep.","Congo, Dem. Rep.","Cote d'Ivoire", "Cote D'Ivoire","Djibouti","Equatorial Guinea","Eritrea","Ethiopia", "Gabon", "Gambia"
,"Ghana", "Guinea","Guinea-Bissau","Kenya","Lesotho","Liberia","Madagascar","Malawi","Mali","Mauritania","Mauritius","Mozambique","Namibia","Niger",
"Nigeria","Rwanda","Sao Tome and Principe","Senegal","Seychelles","Sierra Leone","Somalia","South Africa","Swaziland","Tanzania","Togo","Uganda","Zambia","Zimbabwe", "Sudan", "Republic of Congo")
countrycodes<- c("ANG","AGO","BEN","BWA","BFA", "BDI","CMR","CPV","CAF","TCD","COM","COD","COG","CIV",
"DJI","GNQ","ERI","ETH","GAB","GMB","GHA","GIN","GNB","KEN","LSO","LBR","MDG",
"MWI","MLI","MRT","MUS","MOZ","NAM","NER","NGA","RWA","STP","SEN","SYC","SLE",
"SOM","ZAF","SSD","TZA","TGO","UGA","ZMB","ZWE")
aiddata$country<-aiddata$donor
df_USA <-
aiddata %>%
filter(donor_iso == "US") %>%
group_by(recipient_iso,year) %>%
summarise(sum = sum(commitment_amount_usd_constant,na.rm = TRUE)) %>%
as.data.frame()
# Democracy data ----
df_Dem1<- read_excel("data/p4v2015.xls")
df_Dem <- data.frame(df_Dem1)
df_Dem$country[df_Dem$country== "Congo Kinshasa"] <- "Congo, Dem. Rep."
df_Dem$country[df_Dem$country== "Congo Brazzaville"] <- "Congo, Rep."
df_Dem$country[df_Dem$country== "Ivory Coast"] <- "Ivory Coast"
df_Dem <- df_Dem[df_Dem$year %in% c(2010, 2011, 2012),]
myvars_Dem <- c("scode", "country", "year", "polity2")
df_Dem <- df_Dem[myvars_Dem]
# Worldbank Data ----
#Dataset:WB Data
df_worlddata <- fread("data/worldbank.csv",
sep=",",
nrows = -1,
na.strings = c("NA","N/A",""),
stringsAsFactors=FALSE,
header=TRUE
)
df_worlddata2<- data.frame(df_worlddata)
df_worlddata2<-df_worlddata2[df_worlddata2$Country.Name %in% countrynames2,]
df_worlddata2$Country.Name[df_worlddata2$Country.Name== "Cabo Verde"] <- "Cape Verde"
df_worlddata2$Country.Name[df_worlddata2$Country.Name== "Gambia, The"] <- "Gambia"
df_worlddata2$Country.Name[df_worlddata2$Country.Name== "Cote d'Ivoire"] <- "Ivory Coast"
names(df_worlddata2)[names(df_worlddata2) == "Country.Name"] <- "country"
library(reshape2)
library(stringr)
#Melting and Merging
melted <-
melt(data = df_worlddata2,
id.vars = c("Series.Name",
"Series.Code",
"country",
"Country.Code"),
variable.name = "year",value.name = "value")
melted$year <- melted$year %>% str_sub(start = 2,end = 5) %>% as.numeric()
melted<-melted[-2]
wide_again <- melted %>% spread(key = Series.Name, #oder .Code, wie du willst
value = value)
df_world <- wide_again
merged1 <- left_join(df_world,aiddata,
by = c("country","year"))
merged2 <- left_join(merged1,df_Dem,
by = c("country","year"))
df_main_raw<- merged2
# Subset and Select needed variables ----
#Transform variables to needed format
df_main<-df_main_raw
df_main$export_cost <- as.character(df_main$"Cost to export (US$ per container)")%>% as.numeric() #USD per Container
df_main$CPIA <- as.character(df_main$"CPIA property rights and rule-based governance rating (1=low to 6=high)")%>% as.numeric() #1=low 6= high
df_main$export <- as.character(df_main$export)%>% as.numeric() #Constant USD 2010 to 2011
df_main$export <- df_main$export * 1.03
df_main$FDI <- as.character(df_main$`Foreign direct investment, net inflows (% of GDP)`)%>% as.numeric() #% of GDP
df_main$GDPpc<-as.character(df_main$`GDP per capita (constant 2010 US$)`)%>% as.numeric() #as constant of 2010--> 2011
df_main$GDPpc<- df_main$GDPpc*1.03
df_main$loggdppc<- log(df_main$GDPpc)
df_main$Military<- as.character(df_main$`Military expenditure (% of GDP)`)%>% as.numeric() #% of GDP
df_main$ODA_total<- as.character(df_main$`Net official aid received (constant 2015 US$)`)%>% as.numeric() # To 2010_: 0.93
df_main$ODA_total <- df_main$ODA_total * 0.93
df_main$PopTotal<- as.character(df_main$`Population, total`)%>% as.numeric()
df_main$logpop<- log(df_main$PopTotal)
df_main$Rail<- as.character(df_main$`Rail lines (total route-km)`)%>% as.numeric()
df_main$Exporttax<- as.character(df_main$`Taxes on exports (% of tax revenue)`)%>% as.numeric()
df_main$Resourcerent_perc<- as.character(df_main$`Total natural resources rents (% of GDP)`)%>% as.numeric()
df_main$gdp_2010 <- as.character(df_main$ "GDP (constant 2010 US$)")%>% as.numeric()
df_main$Resourcerent_tot <- df_main$Resourcerent_perc * df_main$gdp_2010
df_main$log_Resourcerent <- log(df_main$Resourcerent_tot)
df_main$aid<- df_main$commitment_amount_usd_constant
save(df_main,file="df_aiddata.Rdata")
#pd for main
pd_main<-pdata.frame(df_main,index=c("country","year"))
pd_main$lpolity2<- lag(pd_main$polity2, k=1)
# Data Visualization----
'to be continued'
| /Files/Course Scripts/script_aiddata.R | no_license | LuMesserschmidt/stats_CoronaNet | R | false | false | 6,806 | r |
# Data Management 1----
rm(list=ls())
library(plyr)
library(tidyverse)
library(magrittr)
library(ggiraph)
library(stargazer)
library(foreign)
library(ggthemes)
library(readxl)
library(bit64)
library(data.table)
library(plm)
load("data/aiddata.Rdata")
countrynames2<- c("Cabo Verde", "Gambia, The", "Ivory Coast","Angola","Benin","Botswana","Burkina Faso","Burundi","Cameroon","Cape Verde","Central African Republic","Chad",
"Comoros","Congo, Rep.","Congo, Dem. Rep.","Cote d'Ivoire", "Cote D'Ivoire","Djibouti","Equatorial Guinea","Eritrea","Ethiopia", "Gabon", "Gambia"
,"Ghana", "Guinea","Guinea-Bissau","Kenya","Lesotho","Liberia","Madagascar","Malawi","Mali","Mauritania","Mauritius","Mozambique","Namibia","Niger",
"Nigeria","Rwanda","Sao Tome and Principe","Senegal","Seychelles","Sierra Leone","Somalia","South Africa","Swaziland","Tanzania","Togo","Uganda","Zambia","Zimbabwe", "Sudan")
countrynames<- c("Angola","Benin","Botswana","Burkina Faso","Burundi","Cameroon","Cape Verde","Central African Republic","Chad",
"Comoros","Congo, Rep.","Congo, Dem. Rep.","Ivory Coast","Cote d'Ivoire", "Cote D'Ivoire","Djibouti","Equatorial Guinea","Eritrea","Ethiopia", "Gabon", "Gambia"
,"Ghana", "Guinea","Guinea-Bissau","Kenya","Lesotho","Liberia","Madagascar","Malawi","Mali","Mauritania","Mauritius","Mozambique","Namibia","Niger",
"Nigeria","Rwanda","Sao Tome and Principe","Senegal","Seychelles","Sierra Leone","Somalia","South Africa","Swaziland","Tanzania","Togo","Uganda","Zambia","Zimbabwe", "Sudan")
countrynames3<- c("Cabo Verde", "Gambia, The", "Ivory Coast","Angola","Benin","Botswana","Burkina Faso","Burundi","Cameroon","Cape Verde","Central African Republic","Chad",
"Comoros","Congo, Rep.","Congo, Dem. Rep.","Cote d'Ivoire", "Cote D'Ivoire","Djibouti","Equatorial Guinea","Eritrea","Ethiopia", "Gabon", "Gambia"
,"Ghana", "Guinea","Guinea-Bissau","Kenya","Lesotho","Liberia","Madagascar","Malawi","Mali","Mauritania","Mauritius","Mozambique","Namibia","Niger",
"Nigeria","Rwanda","Sao Tome and Principe","Senegal","Seychelles","Sierra Leone","Somalia","South Africa","Swaziland","Tanzania","Togo","Uganda","Zambia","Zimbabwe", "Sudan", "Republic of Congo")
countrycodes<- c("ANG","AGO","BEN","BWA","BFA", "BDI","CMR","CPV","CAF","TCD","COM","COD","COG","CIV",
"DJI","GNQ","ERI","ETH","GAB","GMB","GHA","GIN","GNB","KEN","LSO","LBR","MDG",
"MWI","MLI","MRT","MUS","MOZ","NAM","NER","NGA","RWA","STP","SEN","SYC","SLE",
"SOM","ZAF","SSD","TZA","TGO","UGA","ZMB","ZWE")
aiddata$country<-aiddata$donor
df_USA <-
aiddata %>%
filter(donor_iso == "US") %>%
group_by(recipient_iso,year) %>%
summarise(sum = sum(commitment_amount_usd_constant,na.rm = TRUE)) %>%
as.data.frame()
# Democracy data ----
df_Dem1<- read_excel("data/p4v2015.xls")
df_Dem <- data.frame(df_Dem1)
df_Dem$country[df_Dem$country== "Congo Kinshasa"] <- "Congo, Dem. Rep."
df_Dem$country[df_Dem$country== "Congo Brazzaville"] <- "Congo, Rep."
df_Dem$country[df_Dem$country== "Ivory Coast"] <- "Ivory Coast"
df_Dem <- df_Dem[df_Dem$year %in% c(2010, 2011, 2012),]
myvars_Dem <- c("scode", "country", "year", "polity2")
df_Dem <- df_Dem[myvars_Dem]
# Worldbank Data ----
#Dataset:WB Data
df_worlddata <- fread("data/worldbank.csv",
sep=",",
nrows = -1,
na.strings = c("NA","N/A",""),
stringsAsFactors=FALSE,
header=TRUE
)
df_worlddata2<- data.frame(df_worlddata)
df_worlddata2<-df_worlddata2[df_worlddata2$Country.Name %in% countrynames2,]
df_worlddata2$Country.Name[df_worlddata2$Country.Name== "Cabo Verde"] <- "Cape Verde"
df_worlddata2$Country.Name[df_worlddata2$Country.Name== "Gambia, The"] <- "Gambia"
df_worlddata2$Country.Name[df_worlddata2$Country.Name== "Cote d'Ivoire"] <- "Ivory Coast"
names(df_worlddata2)[names(df_worlddata2) == "Country.Name"] <- "country"
library(reshape2)
library(stringr)
#Melting and Merging
melted <-
melt(data = df_worlddata2,
id.vars = c("Series.Name",
"Series.Code",
"country",
"Country.Code"),
variable.name = "year",value.name = "value")
melted$year <- melted$year %>% str_sub(start = 2,end = 5) %>% as.numeric()
melted<-melted[-2]
wide_again <- melted %>% spread(key = Series.Name, #oder .Code, wie du willst
value = value)
df_world <- wide_again
merged1 <- left_join(df_world,aiddata,
by = c("country","year"))
merged2 <- left_join(merged1,df_Dem,
by = c("country","year"))
df_main_raw<- merged2
# Subset and Select needed variables ----
#Transform variables to needed format
df_main<-df_main_raw
df_main$export_cost <- as.character(df_main$"Cost to export (US$ per container)")%>% as.numeric() #USD per Container
df_main$CPIA <- as.character(df_main$"CPIA property rights and rule-based governance rating (1=low to 6=high)")%>% as.numeric() #1=low 6= high
df_main$export <- as.character(df_main$export)%>% as.numeric() #Constant USD 2010 to 2011
df_main$export <- df_main$export * 1.03
df_main$FDI <- as.character(df_main$`Foreign direct investment, net inflows (% of GDP)`)%>% as.numeric() #% of GDP
df_main$GDPpc<-as.character(df_main$`GDP per capita (constant 2010 US$)`)%>% as.numeric() #as constant of 2010--> 2011
df_main$GDPpc<- df_main$GDPpc*1.03
df_main$loggdppc<- log(df_main$GDPpc)
df_main$Military<- as.character(df_main$`Military expenditure (% of GDP)`)%>% as.numeric() #% of GDP
df_main$ODA_total<- as.character(df_main$`Net official aid received (constant 2015 US$)`)%>% as.numeric() # To 2010_: 0.93
df_main$ODA_total <- df_main$ODA_total * 0.93
df_main$PopTotal<- as.character(df_main$`Population, total`)%>% as.numeric()
df_main$logpop<- log(df_main$PopTotal)
df_main$Rail<- as.character(df_main$`Rail lines (total route-km)`)%>% as.numeric()
df_main$Exporttax<- as.character(df_main$`Taxes on exports (% of tax revenue)`)%>% as.numeric()
df_main$Resourcerent_perc<- as.character(df_main$`Total natural resources rents (% of GDP)`)%>% as.numeric()
df_main$gdp_2010 <- as.character(df_main$ "GDP (constant 2010 US$)")%>% as.numeric()
df_main$Resourcerent_tot <- df_main$Resourcerent_perc * df_main$gdp_2010
df_main$log_Resourcerent <- log(df_main$Resourcerent_tot)
df_main$aid<- df_main$commitment_amount_usd_constant
save(df_main,file="df_aiddata.Rdata")
#pd for main
pd_main<-pdata.frame(df_main,index=c("country","year"))
pd_main$lpolity2<- lag(pd_main$polity2, k=1)
# Data Visualization----
'to be continued'
|
## ----setup, include=FALSE-----------------------------------------------------------------------------------------------------------
library(rgl)
knitr::opts_chunk$set(echo = TRUE)
knitr::knit_hooks$set(webgl = hook_webgl)
## .extracode {
## background-color: lightblue;
## }
## -----------------------------------------------------------------------------------------------------------------------------------
seed=2781991
B=1000
## -----------------------------------------------------------------------------------------------------------------------------------
set.seed(seed)
data=stabledist::rstable(1000,1.5,0)
hist(data)
median(data)
## -----------------------------------------------------------------------------------------------------------------------------------
median(data)
## -----------------------------------------------------------------------------------------------------------------------------------
uni_t_perm=function(data,mu0,B=1000){
data_trans=data-mu0
T0=abs(median(data_trans))
T_perm=numeric(B)
n=length(data)
for(perm in 1:B){
refl <- rbinom(n, 1, 0.5)*2 - 1
T_perm[perm]=abs(median(data_trans*refl))
}
return(sum(T_perm>=T0)/B)
}
## -----------------------------------------------------------------------------------------------------------------------------------
grid=seq(-3,3,by=0.001)
length(grid)
## -----------------------------------------------------------------------------------------------------------------------------------
library(pbapply)
library(parallel)
## -----------------------------------------------------------------------------------------------------------------------------------
detectCores()
## -----------------------------------------------------------------------------------------------------------------------------------
cl=makeCluster(16)
## -----------------------------------------------------------------------------------------------------------------------------------
clusterExport(cl,varlist=list("data","uni_t_perm"))
## -----------------------------------------------------------------------------------------------------------------------------------
perm_wrapper=function(grid_point){uni_t_perm(data,grid_point,B=2000)}
pval_function=pbsapply(grid,perm_wrapper,cl=cl)
## -----------------------------------------------------------------------------------------------------------------------------------
plot(grid,pval_function,type='l')
range(grid[pval_function>0.05])
| /Block II - Nonparametric Inference/NPS-lab07_Confidence.R | no_license | EricaManf/lab_nonparametricstatistics | R | false | false | 2,499 | r | ## ----setup, include=FALSE-----------------------------------------------------------------------------------------------------------
library(rgl)
knitr::opts_chunk$set(echo = TRUE)
knitr::knit_hooks$set(webgl = hook_webgl)
## .extracode {
## background-color: lightblue;
## }
## -----------------------------------------------------------------------------------------------------------------------------------
seed=2781991
B=1000
## -----------------------------------------------------------------------------------------------------------------------------------
set.seed(seed)
data=stabledist::rstable(1000,1.5,0)
hist(data)
median(data)
## -----------------------------------------------------------------------------------------------------------------------------------
median(data)
## -----------------------------------------------------------------------------------------------------------------------------------
uni_t_perm=function(data,mu0,B=1000){
data_trans=data-mu0
T0=abs(median(data_trans))
T_perm=numeric(B)
n=length(data)
for(perm in 1:B){
refl <- rbinom(n, 1, 0.5)*2 - 1
T_perm[perm]=abs(median(data_trans*refl))
}
return(sum(T_perm>=T0)/B)
}
## -----------------------------------------------------------------------------------------------------------------------------------
grid=seq(-3,3,by=0.001)
length(grid)
## -----------------------------------------------------------------------------------------------------------------------------------
library(pbapply)
library(parallel)
## -----------------------------------------------------------------------------------------------------------------------------------
detectCores()
## -----------------------------------------------------------------------------------------------------------------------------------
cl=makeCluster(16)
## -----------------------------------------------------------------------------------------------------------------------------------
clusterExport(cl,varlist=list("data","uni_t_perm"))
## -----------------------------------------------------------------------------------------------------------------------------------
perm_wrapper=function(grid_point){uni_t_perm(data,grid_point,B=2000)}
pval_function=pbsapply(grid,perm_wrapper,cl=cl)
## -----------------------------------------------------------------------------------------------------------------------------------
plot(grid,pval_function,type='l')
range(grid[pval_function>0.05])
|
\name{atoms.sort}
\alias{atoms.sort}
\title{Sorts atoms}
\usage{
atoms.sort(atoms, sortindices = c(7, 3, 1, 2))
}
\arguments{
\item{atoms}{dataframe of atoms}
\item{sortindices}{vector of indices after which to sort.
\code{c(1,3)} will sort by rx then by rz}
}
\description{
\code{atoms.sort} sorts atoms.
}
| /Rvasp/man/atoms.sort.Rd | permissive | gokhansurucu/Rvasp | R | false | false | 320 | rd | \name{atoms.sort}
\alias{atoms.sort}
\title{Sorts atoms}
\usage{
atoms.sort(atoms, sortindices = c(7, 3, 1, 2))
}
\arguments{
\item{atoms}{dataframe of atoms}
\item{sortindices}{vector of indices after which to sort.
\code{c(1,3)} will sort by rx then by rz}
}
\description{
\code{atoms.sort} sorts atoms.
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/esm.R
\name{esm}
\alias{esm}
\title{Errore standard (della media)}
\usage{
esm(x, q = 1.96, digits = 6)
}
\arguments{
\item{x}{vettore}
\item{q}{quantile (o qualunque valore) della distribuzione normale
default = 1.96 (int. conf 95\%); per un intervallo di confidenza
del 99\% impostarlo a 2.58.}
\item{digits}{decimali}
}
\value{
Valore della media, della deviazione standard, dell'errore standard,
estremi dell'intervallo di confidenza, valore p dell'area.
}
\description{
Calcola l'errore standard dalla media, e gli estremi dell'intervallo di confidenza.
Di default, considera solo i casi validi con un intervallo di confidenza del 95\%.
}
\examples{
esm(cars$speed)
}
| /man/esm.Rd | no_license | cran/LabRS | R | false | true | 781 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/esm.R
\name{esm}
\alias{esm}
\title{Errore standard (della media)}
\usage{
esm(x, q = 1.96, digits = 6)
}
\arguments{
\item{x}{vettore}
\item{q}{quantile (o qualunque valore) della distribuzione normale
default = 1.96 (int. conf 95\%); per un intervallo di confidenza
del 99\% impostarlo a 2.58.}
\item{digits}{decimali}
}
\value{
Valore della media, della deviazione standard, dell'errore standard,
estremi dell'intervallo di confidenza, valore p dell'area.
}
\description{
Calcola l'errore standard dalla media, e gli estremi dell'intervallo di confidenza.
Di default, considera solo i casi validi con un intervallo di confidenza del 95\%.
}
\examples{
esm(cars$speed)
}
|
## Put comments here that give an overall description of what your
## functions do
##Creating two functions that work together to return the inverse of a matrix.
## Write a short comment describing this function
##makeCacheMatrix sets up the functions/objects to store,set and retrieve the inverse
makeCacheMatrix <- function(x = matrix()) {
i<-NULL
set<- function(y){
x<<-y
i<<-NULL
}
get<-function() x
setinverse<-function(inverse) i<<-inverse
getinverse<-function() i
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Write a short comment describing this function
##cacheSolve checks if the inverse is cached, if not then it calculates it and sets it. If the inverse is cached, then it just returns the inverse and message
cacheSolve <- function(x, ...) {
i <- x$getinverse()
if(!is.null(i)){
message("getting cached data")
return(i)
}
data<-x$get()
i<-solve(data,...)
x$setinverse(i)
i
## Return a matrix that is the inverse of 'x'
}
| /cachematrix.R | no_license | hardisoneverett/ProgrammingAssignment2 | R | false | false | 1,047 | r | ## Put comments here that give an overall description of what your
## functions do
##Creating two functions that work together to return the inverse of a matrix.
## Write a short comment describing this function
##makeCacheMatrix sets up the functions/objects to store,set and retrieve the inverse
makeCacheMatrix <- function(x = matrix()) {
i<-NULL
set<- function(y){
x<<-y
i<<-NULL
}
get<-function() x
setinverse<-function(inverse) i<<-inverse
getinverse<-function() i
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Write a short comment describing this function
##cacheSolve checks if the inverse is cached, if not then it calculates it and sets it. If the inverse is cached, then it just returns the inverse and message
cacheSolve <- function(x, ...) {
i <- x$getinverse()
if(!is.null(i)){
message("getting cached data")
return(i)
}
data<-x$get()
i<-solve(data,...)
x$setinverse(i)
i
## Return a matrix that is the inverse of 'x'
}
|
testlist <- list(type = 207L, z = 3.23785921002061e-319)
result <- do.call(esreg::G1_fun,testlist)
str(result) | /esreg/inst/testfiles/G1_fun/libFuzzer_G1_fun/G1_fun_valgrind_files/1609894290-test.R | no_license | akhikolla/updated-only-Issues | R | false | false | 110 | r | testlist <- list(type = 207L, z = 3.23785921002061e-319)
result <- do.call(esreg::G1_fun,testlist)
str(result) |
#' ARMET-tc main
#'
#' @description This function calls the stan model.
#'
#'
#' @import dplyr
#' @import purrr
#'
#' @importFrom tidybulk aggregate_duplicates
#' @importFrom tidybulk scale_abundance
#' @importFrom tidybulk as_matrix
#'
#' @importFrom tidyr spread
#' @importFrom tidyr gather
#' @importFrom tidyr drop_na
#' @importFrom rlang enquo
#' @importFrom tibble tibble
#' @importFrom tidybayes gather_draws
#'
#' @importFrom tidybayes gather_samples
#' @importFrom tidybayes median_qi
#'
#' @importFrom magrittr equals
#' @importFrom magrittr %$%
#'
#' @import data.tree
#'
#' @param .data A tibble
#' @param .formula A formula
#' @param .sample A column symbol
#' @param .transcript A column symbol
#' @param .abundance A column symbol
#' @param reference A tibble
#' @param approximate_posterior A boolean for variational Bayes
#' @param prior_survival_time An array
#' @param transform_time_function transformation of the time covariate
#' @param reference A tibble
#'
#' @rdname setup_convolved_lm
#' @name setup_convolved_lm
#'
#' @return An ARMET object
#'
#' @export
#'
#'
#'
#'
setup_convolved_lm_NON_hierarchical = function(.data,
.formula = ~ 1,
.sample = NULL,
.transcript = NULL,
.abundance = NULL,
approximate_posterior = F,
prior_survival_time = c(),
transform_time_function = sqrt,
reference = NULL,
iterations_warmup = 1200,
iterations_sampling = 200,
...) {
# At the moment is not active
full_bayesian = F
.n_markers = n_markers
do_regression = T
cores = 4
shards = cores
iterations = iterations_warmup
sampling_iterations = iterations_sampling
model = stanmodels$ARMET_tc_fix
input = c(as.list(environment()))
input$.formula = .formula
# Get column names
.sample = enquo(.sample)
.transcript = enquo(.transcript)
.abundance = enquo(.abundance)
col_names = get_sample_transcript_counts(.data, .sample, .transcript, .abundance)
.sample = col_names$.sample
.transcript = col_names$.transcript
.abundance = col_names$.abundance
# Rename columns mix
.data = .data |> rename( sample = !!.sample, symbol = !!.transcript , count = !!.abundance)
input$.data = .data
# Warning is sensitive names in columns
names_taken = c("level")
if(.data |> colnames() %in% names_taken |> any()) stop(sprintf("ARMET says: your input data frame includes reserved column names: %s", names_taken))
# Check if count is integer
if(.data |> select(count) |> lapply(class) |> unlist() |> equals("integer") |> not())
stop(sprintf("ARMET says: the %s column must be integer as the deconvolution model is Negative Binomial", quo_name(.abundance)))
# Covariate column
if(do_regression & paste(as.character(.formula), collapse="") != "~1"){
formula_df = parse_formula(.formula)
# Censoring column
if(do_regression && length(formula_df$censored_column) == 1) {
cens = .data |> select(sample, formula_df$censored_column) |> distinct() |> arrange(sample) |> pull(2)
# Check cens right type
if(typeof(cens) %in% c("integer", "logical") |> any() |> not()) stop("ARMET says: censoring variable should be logical of integer (0,1)")
if(length(prior_survival_time) == 0) stop("ARMET says: you really need to provide third party survival time for your condition/disease")
sd_survival_months = .data |> select(sample, formula_df$censored_value_column) |> distinct() |> pull(formula_df$censored_value_column) |> sd()
prior_survival_time = transform_time_function( when(min(prior_survival_time)==0, ~ prior_survival_time + 1, prior_survival_time))
time_column = formula_df$censored_value_column
X =
model.matrix(
object = formula_df$formula_formatted,
data =
.data |>
select(sample, one_of(formula_df$covariates_formatted)) |>
distinct() |>
arrange(sample) |>
mutate(!!as.symbol(formula_df$censored_value_column ) := transform_time_function(!!as.symbol(formula_df$censored_value_column )) )
)
columns_idx_including_time =
which(grepl(time_column, colnames(X))) |>
as.array() %>%
# Fix if NULL
when(is.null(.) ~ c(), ~ (.))
}
else{
X =
model.matrix(
object = formula_df$formula_formatted,
data =
.data |>
select(sample, one_of(formula_df$covariates_formatted)) |>
distinct() |>
arrange(sample)
)
cens = NULL
columns_idx_including_time = array(0)[0]
}
} else {
formula_df = cens = NULL
columns_idx_including_time = array(0)[0]
X =
model.matrix(
object = ~ 1,
data = .data |> select(sample) |> distinct() |> arrange(sample)
)
}
# Do regression
#if(length(formula_df$covariates_formatted) > 0 & (formula_df$covariates_formatted |> is.na() |> not())) do_regression = T
# distinct_at is not released yet for dplyr, thus we have to use this trick
df_for_edgeR <- .data |>
# Stop if any counts is NA
error_if_counts_is_na(count) |>
# Stop if there are duplicated transcripts
error_if_duplicated_genes(sample,symbol,count) |>
# Prepare the data frame
select(symbol,
sample,
count,
one_of(formula_df$covariates_formatted)) |>
distinct() |>
# Check if data rectangular
when(
check_if_data_rectangular(., sample,symbol,count) |> not() &
TRUE ~ eliminate_sparse_transcripts(., symbol),
~ (.)
) |>
when(
do_regression && length(formula_df$censored_column) == 1 ~
mutate(., !!formula_df$censored_value_column := !!as.symbol(formula_df$censored_value_column) / sd_survival_months),
~ (.)
)
mix =
.data |>
select(sample, symbol, count, one_of(formula_df$covariates_formatted)) |>
distinct()
# Print overlap descriptive stats
#get_overlap_descriptive_stats(mix |> slice(1) |> gather(symbol, count, -sample), reference)
# Prepare data frames -
# For Q query first
# For G house keeing first
# For GM level 1 first
Q = mix |> distinct(sample) |> nrow()
if(!check_if_data_rectangular(reference, cell_type, symbol, count)){
warning("tidybulk says: the data does not have the same number of transcript per sample. The data set is not rectangular.")
reference =
reference |>
# Filter genes common to all cell types
add_count(symbol) |>
filter(n==max(n)) |>
select(-n)
}
reference_filtered = reference |> mutate(C = cell_type |> as.factor() |> droplevels() |> as.numeric())
# Find normalisation
sample_scaling =
reference_filtered |>
mutate(sample = "reference") |>
tidybulk::aggregate_duplicates(sample, symbol, count, aggregation_function = median) |>
bind_rows(mix) |>
tidybulk::identify_abundant(sample, symbol, count) |>
tidybulk::scale_abundance(sample, symbol, count, reference_sample = "reference", action ="get", .subset_for_scaling = .abundant) |>
distinct(sample, multiplier) |>
mutate(exposure_rate = -log(multiplier)) |>
mutate(exposure_multiplier = exp(exposure_rate))
# Default internals
list(
internals = list(
prop = NULL,
fit = NULL,
df = NULL,
#prop_posterior = get_null_prop_posterior(tree_propeties$ct_in_nodes),
alpha = NULL,
Q = Q,
reference_filtered = reference_filtered,
mix = mix,
X = X,
cens = cens,
#tree_properties = tree_propeties,
prior_survival_time = prior_survival_time,
formula_df = formula_df,
sample_scaling = sample_scaling,
columns_idx_including_time = columns_idx_including_time,
approximate_posterior = approximate_posterior,
transform_time_function = transform_time_function,
shards = shards,
full_bayesian = full_bayesian,
iterations = iterations,
sampling_iterations = sampling_iterations ,
do_regression = do_regression,
.formula = .formula,
model = model
),
input = input
)
}
median_qi_nest_draws_NO_hierarchical = function(d){
# Anonymous function to add the draws to the summary
left_join(
d |>
#group_by(.variable, Q, C) |>
tidybayes::median_qi() |>
ungroup(),
# Reattach draws as nested
d |>
ungroup() |>
nest(.draws = c(.chain, .iteration, .draw , .value, .value_relative)),
by = c(".variable", "Q", "sample", "C")
)
}
# @description Parse the stan fit object and check for divergences
parse_summary_check_divergence_NO_hierarchical = function(draws) {
draws |>
group_by(.variable, Q, sample, C) |>
# If not converged choose the majority chains
mutate(converged = diptest::dip.test(`.value_relative`) %$% `p.value` > 0.05) %>%
# Anonymous function - add summary fit to converged label
# input: tibble
# output: tibble
{
left_join(
(.) |> select(-converged) |> median_qi_nest_draws_NO_hierarchical(),
(.) |> distinct(converged),
by = c( ".variable", "Q", "sample", "C")
)
} |>
ungroup()
}
get_generated_quantities_standalone_NO_hierarchy = function(fit, internals){
left_join(
fit |>
draws_to_tibble("prop_", "Q", "C") |>
mutate(Q = as.integer(Q)) |>
mutate(.variable = gsub("_rng", "", .variable)) |>
separate(.variable, c("par", "node"), remove = F) |>
select(-par) |>
nest(rng_prop = -c(node, C)) |>
mutate(C = 1:n()),
fit |>
draws_to_tibble("mu_", "Q", "C") |>
mutate(Q = as.integer(Q)) |>
mutate(.variable = gsub("_rng", "", .variable)) |>
separate(.variable, c("par", "node"), remove = F) |>
select(-par) |>
nest(rng_mu = -c(node, C)) |>
mutate(C = 1:n()),
by=c("C", "node")
)
}
get_generated_quantities_standalone_NO_hierarchy_cmdstanr = function(fit, internals, model_data){
left_join(
fit$draws("prop_1_rng", format = "draws_df") |>
pivot_longer(
names_to = c( ".variable", "C", "Q"),
cols = contains("prop_1_rng"),
names_sep = "\\[|,|\\]|:",
values_to = ".value"
) |>
suppressWarnings() |>
mutate(Q = as.integer(Q), C = as.integer(C)) |>
nest(rng_prop = -C),
fit$draws("mu_1_rng", format = "draws_df") |>
pivot_longer(
names_to = c( ".variable", "Q", "C"),
cols = contains("mu_1_rng"),
names_sep = "\\[|,|\\]|:",
values_to = ".value"
) |>
suppressWarnings() |>
mutate(Q = as.integer(Q), C = as.integer(C)) |>
nest(rng_mu = -C),
by = "C"
) |>
mutate(node = "1")
}
get_alpha_NO_hierarchy = function(fit){
fit %>%
draws_to_tibble("alpha_", "A", "C") %>%
filter(!grepl("_raw" ,.variable)) %>%
# rebuild the last component sum-to-zero
#rebuild_last_component_sum_to_zero() %>%
arrange(.chain, .iteration, .draw, A) %>%
nest(draws = -c(C, .variable)) %>%
# Attach convergence information
left_join(
fit %>%
summary_to_tibble("alpha_", "A", "C") %>%
filter(!grepl("_raw" ,.variable)) %>%
filter(A == 2) %>%
select(.variable, C, one_of("Rhat")),
by = c(".variable", "C")
) %>%
# FOR HIERARCHICAL
mutate(C = 1:n()) %>%
# Attach generated quantities
separate(.variable, c("par", "node"), remove = F)
}
get_alpha_NO_hierarchy_cmdstanr = function(fit){
fit$draws("alpha_1", format = "draws_df") |>
# rebuild the last component sum-to-zero
#rebuild_last_component_sum_to_zero() %>%
pivot_longer(
names_to = c( ".variable", "A", "C"),
cols = contains("alpha_1"),
names_sep = "\\[|,|\\]|:",
values_to = ".value"
) |>
suppressWarnings() |>
mutate(A = as.integer(A), C = as.integer(C)) |>
arrange(.chain, .iteration, .draw, A) %>%
nest(draws = -c(C, .variable)) %>%
# Attach convergence information
left_join(
fit$summary("alpha_1") %>%
tidyr::extract(variable, c(".variable", "A", "C"), "([a-z0-9_]+)\\[([0-9]+),([0-9]+)\\]") |>
mutate(A = as.integer(A), C = as.integer(C)) |>
filter(A == 2) |>
rename(Rhat = rhat) |>
select(.variable, C, one_of("Rhat")),
by = c(".variable", "C")
) %>%
# FOR HIERARCHICAL
mutate(C = 1:n()) %>%
# Attach generated quantities
separate(.variable, c("par", "node"), remove = F)
}
#' estimate_convoluted_lm
#'
#' @description This function does inference for higher levels of the hierarchy
#'
#' @rdname estimate_convoluted_lm
#' @name estimate_convoluted_lm
#'
#' @param armet_obj An ARMET object
#'
#' @export
estimate_convoluted_lm = function(armet_obj, use_data = TRUE, use_cmdstanr = FALSE){
internals =
run_lv(
armet_obj$internals,
armet_obj$internals$shards,
armet_obj$internals$full_bayesian,
armet_obj$internals$approximate_posterior,
iterations = armet_obj$internals$iterations,
sampling_iterations = armet_obj$internals$sampling_iterations ,
do_regression = armet_obj$internals$do_regression,
.formula = armet_obj$internals$.formula,
model = armet_obj$internals$model,
use_data = use_data,
use_cmdstanr = use_cmdstanr
)
proportions =
armet_obj$input$.data %>%
select(c(sample, (.) %>% get_specific_annotation_columns(sample))) |>
distinct() |>
left_join(internals$prop, by="sample") |>
# Attach alpha if regression
ifelse_pipe(
internals$do_regression, # && paste(as.character(internals$.formula), collapse="") != "~1" ,
~ .x |>
nest(proportions = -c( C)) |>
left_join(
internals$alpha |> select( C, contains("alpha"), draws, rng_prop, rng_mu, .variable, one_of("Rhat")),
by = c("C")
)
) |>
# Add cell type
left_join(internals$reference_filtered |> distinct(cell_type, C), by="C") |>
select(-C) |>
select(cell_type, everything())
attrib =
list(
# Matrix of proportions
proportions = proportions,
# # Return the input itself
input = armet_obj$input,
# Return the fitted object
internals = internals
)
proportions |>
get_estimates_NO_hierarchy(X = attrib$internals$X) |>
add_attr(attrib, "full_results")
}
run_lv = function(internals,
shards,
full_bayesian,
approximate_posterior,
iterations = iterations,
sampling_iterations = sampling_iterations,
do_regression = do_regression,
.formula = .formula, model = stanmodels$ARMET_tc_fix, use_data = TRUE, use_cmdstanr = FALSE){
reference_filtered = internals$reference_filtered
mix = internals$mix
prop_posterior = internals$prop_posterior
X = internals$X
cens = internals$cens
Q = internals$Q
model = stanmodels$ARMET_tc_fix
prior_survival_time = internals$prior_survival_time
sample_scaling = internals$sample_scaling
columns_idx_including_time = internals$columns_idx_including_time
# Inference
# Global properties - derived by previous analyses of the whole reference dataset
sigma_intercept = 1.3420415
sigma_slope = -0.3386389
sigma_sigma = 1.1720851
lambda_mu_mu = 5.612671
lambda_sigma = 7.131593
# Non centred
lambda_mu_prior = c(6.2, 1)
lambda_sigma_prior = c(3.3 , 1)
lambda_skew_prior = c(-2.7, 1)
sigma_intercept_prior = c(1.9 , 0.1)
# Filter on level considered
my_genes = reference_filtered |> filter(is_marker) |> pull(symbol) |> unique()
reference_filtered = reference_filtered |> filter(symbol %in% my_genes)
# Number of cell types
number_of_cell_types = reference_filtered |> distinct(cell_type) |> nrow()
# Format
df = ref_mix_format(reference_filtered, mix)
GM = df |> distinct(symbol) |> nrow()
y_source =
df |>
filter(`query`) |>
select(S, Q, symbol, count, GM, sample)
# Dirichlet regression
A = X |> ncol()
# library(rstan)
# fileConn<-file("~/.R/Makevars")
# writeLines(c( "CXX14FLAGS += -O2","CXX14FLAGS += -DSTAN_THREADS", "CXX14FLAGS += -pthread"), fileConn)
# close(fileConn)
# ARMET_tc_model = rstan::stan_model("~/PhD/deconvolution/ARMET/inst/stan/ARMET_tc_fix.stan", auto_write = F)
exposure_multiplier =
sample_scaling |>
filter(sample %in% (y_source |> pull(sample))) |>
arrange(sample) |>
pull(exposure_multiplier) |>
as.array()
init_list = list(
lambda_UFO = rep(6.2, GM),
prop_1 = matrix(rep(1.0/number_of_cell_types, number_of_cell_types*Q), nrow = Q ),
phi = rep(5, number_of_cell_types)
)
ref =
df |>
# Eliminate the query part, not the house keeping of the query
filter(!`query`) |>
select(C, GM, count ) |>
distinct() |>
arrange(C, GM) |>
spread(GM, count) |>
tidybulk::as_matrix(rownames = "C")
y =
y_source |>
select(Q, GM, count) |>
distinct() |>
arrange(Q, GM) |>
spread(GM, count) |>
tidybulk::as_matrix(rownames = "Q")
max_y = max(y)
Sys.setenv("STAN_NUM_THREADS" = shards)
if(cens |> is.null()) cens = rep(0, Q)
which_cens = which(cens == 1) |> as.array()
which_not_cens = which(cens == 0) |> as.array()
how_many_cens = length(which_cens)
max_unseen = ifelse(how_many_cens>0, max(X[,2]), 0 )
if(is.null(prior_survival_time)) prior_survival_time = array(1)[0]
spt = length(prior_survival_time)
CIT = length(columns_idx_including_time)
model_data = list(
shards = shards,
GM = GM,
sigma_slope = sigma_slope,
sigma_sigma = sigma_sigma,
Q = Q,
number_of_cell_types = number_of_cell_types,
y = y,
max_y = max_y,
ref = ref,
A = A,
X = X,
do_regression = do_regression,
how_many_cens = how_many_cens,
which_cens = which_cens,
which_not_cens = which_not_cens,
max_unseen = max_unseen,
spt = spt,
prior_survival_time = prior_survival_time,
CIT = CIT,
columns_idx_including_time = columns_idx_including_time,
exposure_multiplier = exposure_multiplier,
use_data = use_data
)
if( use_cmdstanr ){
# Lad model code
if(file.exists("ARMET_tc_fix_cmdstanr.rds"))
mod = readRDS("ARMET_tc_fix_cmdstanr.rds")
else {
readr::write_file(ARMET_tc_fix_cmdstanr, "ARMET_tc_fix_cmdstanr.stan")
mod = cmdstanr::cmdstan_model( "ARMET_tc_fix_cmdstanr.stan") #, cpp_options = list(stan_threads = TRUE) )
mod %>% saveRDS("ARMET_tc_fix_cmdstanr.rds")
}
if(approximate_posterior)
fit =
mod$variational(
data = model_data ,
init = function () init_list
) %>%
suppressWarnings()
else
fit =
mod$sample(
data = model_data ,
init = function () init_list,
iter_warmup = iterations - sampling_iterations,
iter_sampling = sampling_iterations,
parallel_chains = 3, chains = 3,
threads_per_chain = ceiling(shards / 3)
) %>%
suppressWarnings()
fit$summary() |> arrange(rhat |> desc()) |> filter(rhat > 1.2) |> print()
fit_prop_parsed =
fit$draws("prop_1", format = "draws_df") |>
pivot_longer(
names_to = c( ".variable", "C", "Q"),
cols = contains("prop_1"),
names_sep = "\\[|,|\\]|:",
values_to = ".value"
) |>
suppressWarnings() |>
mutate(Q = as.integer(Q), C = as.integer(C))
if (do_regression) # && paste(as.character(.formula), collapse="") != "~1" )
internals$alpha =
get_alpha_NO_hierarchy_cmdstanr(fit) |>
left_join(
get_generated_quantities_standalone_NO_hierarchy_cmdstanr(fit, internals, model_data),
by = c("node", "C")
)
}
else {
fit =
approximate_posterior |>
when(
(.) ~ vb_iterative(model,
# rstan::stan_model("~/PhD/deconvolution/ARMET/inst/stan/ARMET_tc_fix_hierarchical.stan", auto_write = F),
iter = 50000,
tol_rel_obj = 0.0005,
init = function () init_list
),
~ sampling(
model,
#rstan::stan_model("~/PhD/deconvolution/ARMET/inst/stan/ARMET_tc_fix_hierarchical.stan", auto_write = F),
chains = 3,
cores = 3,
iter = iterations,
warmup = iterations - sampling_iterations,
data = ,
#data = prop_posterior |> c(tree_properties),
# pars=
# c("prop_1", "prop_2", "prop_3", sprintf("prop_%s", letters[1:9])) |>
# c("alpha_1", sprintf("alpha_%s", letters[1:9])) |>
# c("exposure_rate") |>
# c("lambda_UFO") |>
# c("prop_UFO") |>
# c(additional_par_to_save),
init = function () init_list,
save_warmup = FALSE
# ,
# control=list( adapt_delta=0.9,stepsize = 0.01, max_treedepth =10 )
)) %>%
{
(.) |> rstan::summary() %$% summary |> as_tibble(rownames = "par") |> arrange(Rhat |> desc()) |> filter(Rhat > 1.5) |> ifelse_pipe(nrow(.) > 0, ~ print(.x))
(.)
}
fit_prop_parsed =
fit |>
draws_to_tibble("prop_1", "C", "Q") |>
filter(!grepl("_UFO|_rng", .variable)) |>
mutate(Q = Q |> as.integer())
if (do_regression) # && paste(as.character(.formula), collapse="") != "~1" )
internals$alpha =
get_alpha_NO_hierarchy(fit) |>
left_join(
get_generated_quantities_standalone_NO_hierarchy(fit, internals),
by = c("node", "C")
)
}
# Parsing
draws =
fit_prop_parsed |>
ungroup() |>
select(-.variable) |>
mutate(.value_relative = .value)
prop =
fit_prop_parsed |>
drop_na() |>
ungroup() |>
# Add relative proportions
mutate(.value_relative = .value) |>
# add sample annotation
left_join(df |> distinct(Q, sample), by = "Q") |>
# If MCMC is used check divergences as well
parse_summary_check_divergence_NO_hierarchical() |>
# Parse
separate(.variable, c(".variable", "level"), convert = T) |>
# Add sample information
left_join(df |>
filter(`query`) |>
distinct(Q, sample),
by = c("Q", "sample")
)
internals$prop = prop
internals$fit = list(fit)
internals$df = list(df)
internals$draws = list(draws)
internals$prop_posterior[[1]] = fit_prop_parsed |> group_by(.variable, Q, C) |> prop_to_list() %>% `[[` ("prop_1")
internals
}
get_estimates_NO_hierarchy = function(.data, X) {
.data %>%
filter(.variable %>% is.na %>% `!`) %>%
select(cell_type, draws) %>%
mutate(regression = map(draws,
~ .x %>%
group_by(A) %>%
summarise(.median = median(.value), .sd = sd(.value)) %>%
#tidybayes::median_qi(.width = credible_interval) %>%
left_join(tibble(A=1:ncol(X), A_name = colnames(X)) , by = "A") %>%
select(-A) %>%
pivot_wider(
names_from = A_name,
values_from = c(.median, .sd)
))) %>%
select(-draws) %>%
unnest(regression)
}
| /R/functions_NON_hierarchical.R | no_license | stemangiola/ARMET | R | false | false | 22,427 | r | #' ARMET-tc main
#'
#' @description This function calls the stan model.
#'
#'
#' @import dplyr
#' @import purrr
#'
#' @importFrom tidybulk aggregate_duplicates
#' @importFrom tidybulk scale_abundance
#' @importFrom tidybulk as_matrix
#'
#' @importFrom tidyr spread
#' @importFrom tidyr gather
#' @importFrom tidyr drop_na
#' @importFrom rlang enquo
#' @importFrom tibble tibble
#' @importFrom tidybayes gather_draws
#'
#' @importFrom tidybayes gather_samples
#' @importFrom tidybayes median_qi
#'
#' @importFrom magrittr equals
#' @importFrom magrittr %$%
#'
#' @import data.tree
#'
#' @param .data A tibble
#' @param .formula A formula
#' @param .sample A column symbol
#' @param .transcript A column symbol
#' @param .abundance A column symbol
#' @param reference A tibble
#' @param approximate_posterior A boolean for variational Bayes
#' @param prior_survival_time An array
#' @param transform_time_function transformation of the time covariate
#' @param reference A tibble
#'
#' @rdname setup_convolved_lm
#' @name setup_convolved_lm
#'
#' @return An ARMET object
#'
#' @export
#'
#'
#'
#'
setup_convolved_lm_NON_hierarchical = function(.data,
.formula = ~ 1,
.sample = NULL,
.transcript = NULL,
.abundance = NULL,
approximate_posterior = F,
prior_survival_time = c(),
transform_time_function = sqrt,
reference = NULL,
iterations_warmup = 1200,
iterations_sampling = 200,
...) {
# At the moment is not active
full_bayesian = F
.n_markers = n_markers
do_regression = T
cores = 4
shards = cores
iterations = iterations_warmup
sampling_iterations = iterations_sampling
model = stanmodels$ARMET_tc_fix
input = c(as.list(environment()))
input$.formula = .formula
# Get column names
.sample = enquo(.sample)
.transcript = enquo(.transcript)
.abundance = enquo(.abundance)
col_names = get_sample_transcript_counts(.data, .sample, .transcript, .abundance)
.sample = col_names$.sample
.transcript = col_names$.transcript
.abundance = col_names$.abundance
# Rename columns mix
.data = .data |> rename( sample = !!.sample, symbol = !!.transcript , count = !!.abundance)
input$.data = .data
# Warning is sensitive names in columns
names_taken = c("level")
if(.data |> colnames() %in% names_taken |> any()) stop(sprintf("ARMET says: your input data frame includes reserved column names: %s", names_taken))
# Check if count is integer
if(.data |> select(count) |> lapply(class) |> unlist() |> equals("integer") |> not())
stop(sprintf("ARMET says: the %s column must be integer as the deconvolution model is Negative Binomial", quo_name(.abundance)))
# Covariate column
if(do_regression & paste(as.character(.formula), collapse="") != "~1"){
formula_df = parse_formula(.formula)
# Censoring column
if(do_regression && length(formula_df$censored_column) == 1) {
cens = .data |> select(sample, formula_df$censored_column) |> distinct() |> arrange(sample) |> pull(2)
# Check cens right type
if(typeof(cens) %in% c("integer", "logical") |> any() |> not()) stop("ARMET says: censoring variable should be logical of integer (0,1)")
if(length(prior_survival_time) == 0) stop("ARMET says: you really need to provide third party survival time for your condition/disease")
sd_survival_months = .data |> select(sample, formula_df$censored_value_column) |> distinct() |> pull(formula_df$censored_value_column) |> sd()
prior_survival_time = transform_time_function( when(min(prior_survival_time)==0, ~ prior_survival_time + 1, prior_survival_time))
time_column = formula_df$censored_value_column
X =
model.matrix(
object = formula_df$formula_formatted,
data =
.data |>
select(sample, one_of(formula_df$covariates_formatted)) |>
distinct() |>
arrange(sample) |>
mutate(!!as.symbol(formula_df$censored_value_column ) := transform_time_function(!!as.symbol(formula_df$censored_value_column )) )
)
columns_idx_including_time =
which(grepl(time_column, colnames(X))) |>
as.array() %>%
# Fix if NULL
when(is.null(.) ~ c(), ~ (.))
}
else{
X =
model.matrix(
object = formula_df$formula_formatted,
data =
.data |>
select(sample, one_of(formula_df$covariates_formatted)) |>
distinct() |>
arrange(sample)
)
cens = NULL
columns_idx_including_time = array(0)[0]
}
} else {
formula_df = cens = NULL
columns_idx_including_time = array(0)[0]
X =
model.matrix(
object = ~ 1,
data = .data |> select(sample) |> distinct() |> arrange(sample)
)
}
# Do regression
#if(length(formula_df$covariates_formatted) > 0 & (formula_df$covariates_formatted |> is.na() |> not())) do_regression = T
# distinct_at is not released yet for dplyr, thus we have to use this trick
df_for_edgeR <- .data |>
# Stop if any counts is NA
error_if_counts_is_na(count) |>
# Stop if there are duplicated transcripts
error_if_duplicated_genes(sample,symbol,count) |>
# Prepare the data frame
select(symbol,
sample,
count,
one_of(formula_df$covariates_formatted)) |>
distinct() |>
# Check if data rectangular
when(
check_if_data_rectangular(., sample,symbol,count) |> not() &
TRUE ~ eliminate_sparse_transcripts(., symbol),
~ (.)
) |>
when(
do_regression && length(formula_df$censored_column) == 1 ~
mutate(., !!formula_df$censored_value_column := !!as.symbol(formula_df$censored_value_column) / sd_survival_months),
~ (.)
)
mix =
.data |>
select(sample, symbol, count, one_of(formula_df$covariates_formatted)) |>
distinct()
# Print overlap descriptive stats
#get_overlap_descriptive_stats(mix |> slice(1) |> gather(symbol, count, -sample), reference)
# Prepare data frames -
# For Q query first
# For G house keeing first
# For GM level 1 first
Q = mix |> distinct(sample) |> nrow()
if(!check_if_data_rectangular(reference, cell_type, symbol, count)){
warning("tidybulk says: the data does not have the same number of transcript per sample. The data set is not rectangular.")
reference =
reference |>
# Filter genes common to all cell types
add_count(symbol) |>
filter(n==max(n)) |>
select(-n)
}
reference_filtered = reference |> mutate(C = cell_type |> as.factor() |> droplevels() |> as.numeric())
# Find normalisation
sample_scaling =
reference_filtered |>
mutate(sample = "reference") |>
tidybulk::aggregate_duplicates(sample, symbol, count, aggregation_function = median) |>
bind_rows(mix) |>
tidybulk::identify_abundant(sample, symbol, count) |>
tidybulk::scale_abundance(sample, symbol, count, reference_sample = "reference", action ="get", .subset_for_scaling = .abundant) |>
distinct(sample, multiplier) |>
mutate(exposure_rate = -log(multiplier)) |>
mutate(exposure_multiplier = exp(exposure_rate))
# Default internals
list(
internals = list(
prop = NULL,
fit = NULL,
df = NULL,
#prop_posterior = get_null_prop_posterior(tree_propeties$ct_in_nodes),
alpha = NULL,
Q = Q,
reference_filtered = reference_filtered,
mix = mix,
X = X,
cens = cens,
#tree_properties = tree_propeties,
prior_survival_time = prior_survival_time,
formula_df = formula_df,
sample_scaling = sample_scaling,
columns_idx_including_time = columns_idx_including_time,
approximate_posterior = approximate_posterior,
transform_time_function = transform_time_function,
shards = shards,
full_bayesian = full_bayesian,
iterations = iterations,
sampling_iterations = sampling_iterations ,
do_regression = do_regression,
.formula = .formula,
model = model
),
input = input
)
}
median_qi_nest_draws_NO_hierarchical = function(d){
# Anonymous function to add the draws to the summary
left_join(
d |>
#group_by(.variable, Q, C) |>
tidybayes::median_qi() |>
ungroup(),
# Reattach draws as nested
d |>
ungroup() |>
nest(.draws = c(.chain, .iteration, .draw , .value, .value_relative)),
by = c(".variable", "Q", "sample", "C")
)
}
# @description Parse the stan fit object and check for divergences
parse_summary_check_divergence_NO_hierarchical = function(draws) {
draws |>
group_by(.variable, Q, sample, C) |>
# If not converged choose the majority chains
mutate(converged = diptest::dip.test(`.value_relative`) %$% `p.value` > 0.05) %>%
# Anonymous function - add summary fit to converged label
# input: tibble
# output: tibble
{
left_join(
(.) |> select(-converged) |> median_qi_nest_draws_NO_hierarchical(),
(.) |> distinct(converged),
by = c( ".variable", "Q", "sample", "C")
)
} |>
ungroup()
}
get_generated_quantities_standalone_NO_hierarchy = function(fit, internals){
left_join(
fit |>
draws_to_tibble("prop_", "Q", "C") |>
mutate(Q = as.integer(Q)) |>
mutate(.variable = gsub("_rng", "", .variable)) |>
separate(.variable, c("par", "node"), remove = F) |>
select(-par) |>
nest(rng_prop = -c(node, C)) |>
mutate(C = 1:n()),
fit |>
draws_to_tibble("mu_", "Q", "C") |>
mutate(Q = as.integer(Q)) |>
mutate(.variable = gsub("_rng", "", .variable)) |>
separate(.variable, c("par", "node"), remove = F) |>
select(-par) |>
nest(rng_mu = -c(node, C)) |>
mutate(C = 1:n()),
by=c("C", "node")
)
}
get_generated_quantities_standalone_NO_hierarchy_cmdstanr = function(fit, internals, model_data){
left_join(
fit$draws("prop_1_rng", format = "draws_df") |>
pivot_longer(
names_to = c( ".variable", "C", "Q"),
cols = contains("prop_1_rng"),
names_sep = "\\[|,|\\]|:",
values_to = ".value"
) |>
suppressWarnings() |>
mutate(Q = as.integer(Q), C = as.integer(C)) |>
nest(rng_prop = -C),
fit$draws("mu_1_rng", format = "draws_df") |>
pivot_longer(
names_to = c( ".variable", "Q", "C"),
cols = contains("mu_1_rng"),
names_sep = "\\[|,|\\]|:",
values_to = ".value"
) |>
suppressWarnings() |>
mutate(Q = as.integer(Q), C = as.integer(C)) |>
nest(rng_mu = -C),
by = "C"
) |>
mutate(node = "1")
}
get_alpha_NO_hierarchy = function(fit){
fit %>%
draws_to_tibble("alpha_", "A", "C") %>%
filter(!grepl("_raw" ,.variable)) %>%
# rebuild the last component sum-to-zero
#rebuild_last_component_sum_to_zero() %>%
arrange(.chain, .iteration, .draw, A) %>%
nest(draws = -c(C, .variable)) %>%
# Attach convergence information
left_join(
fit %>%
summary_to_tibble("alpha_", "A", "C") %>%
filter(!grepl("_raw" ,.variable)) %>%
filter(A == 2) %>%
select(.variable, C, one_of("Rhat")),
by = c(".variable", "C")
) %>%
# FOR HIERARCHICAL
mutate(C = 1:n()) %>%
# Attach generated quantities
separate(.variable, c("par", "node"), remove = F)
}
get_alpha_NO_hierarchy_cmdstanr = function(fit){
fit$draws("alpha_1", format = "draws_df") |>
# rebuild the last component sum-to-zero
#rebuild_last_component_sum_to_zero() %>%
pivot_longer(
names_to = c( ".variable", "A", "C"),
cols = contains("alpha_1"),
names_sep = "\\[|,|\\]|:",
values_to = ".value"
) |>
suppressWarnings() |>
mutate(A = as.integer(A), C = as.integer(C)) |>
arrange(.chain, .iteration, .draw, A) %>%
nest(draws = -c(C, .variable)) %>%
# Attach convergence information
left_join(
fit$summary("alpha_1") %>%
tidyr::extract(variable, c(".variable", "A", "C"), "([a-z0-9_]+)\\[([0-9]+),([0-9]+)\\]") |>
mutate(A = as.integer(A), C = as.integer(C)) |>
filter(A == 2) |>
rename(Rhat = rhat) |>
select(.variable, C, one_of("Rhat")),
by = c(".variable", "C")
) %>%
# FOR HIERARCHICAL
mutate(C = 1:n()) %>%
# Attach generated quantities
separate(.variable, c("par", "node"), remove = F)
}
#' estimate_convoluted_lm
#'
#' @description This function does inference for higher levels of the hierarchy
#'
#' @rdname estimate_convoluted_lm
#' @name estimate_convoluted_lm
#'
#' @param armet_obj An ARMET object
#'
#' @export
estimate_convoluted_lm = function(armet_obj, use_data = TRUE, use_cmdstanr = FALSE){
internals =
run_lv(
armet_obj$internals,
armet_obj$internals$shards,
armet_obj$internals$full_bayesian,
armet_obj$internals$approximate_posterior,
iterations = armet_obj$internals$iterations,
sampling_iterations = armet_obj$internals$sampling_iterations ,
do_regression = armet_obj$internals$do_regression,
.formula = armet_obj$internals$.formula,
model = armet_obj$internals$model,
use_data = use_data,
use_cmdstanr = use_cmdstanr
)
proportions =
armet_obj$input$.data %>%
select(c(sample, (.) %>% get_specific_annotation_columns(sample))) |>
distinct() |>
left_join(internals$prop, by="sample") |>
# Attach alpha if regression
ifelse_pipe(
internals$do_regression, # && paste(as.character(internals$.formula), collapse="") != "~1" ,
~ .x |>
nest(proportions = -c( C)) |>
left_join(
internals$alpha |> select( C, contains("alpha"), draws, rng_prop, rng_mu, .variable, one_of("Rhat")),
by = c("C")
)
) |>
# Add cell type
left_join(internals$reference_filtered |> distinct(cell_type, C), by="C") |>
select(-C) |>
select(cell_type, everything())
attrib =
list(
# Matrix of proportions
proportions = proportions,
# # Return the input itself
input = armet_obj$input,
# Return the fitted object
internals = internals
)
proportions |>
get_estimates_NO_hierarchy(X = attrib$internals$X) |>
add_attr(attrib, "full_results")
}
run_lv = function(internals,
shards,
full_bayesian,
approximate_posterior,
iterations = iterations,
sampling_iterations = sampling_iterations,
do_regression = do_regression,
.formula = .formula, model = stanmodels$ARMET_tc_fix, use_data = TRUE, use_cmdstanr = FALSE){
reference_filtered = internals$reference_filtered
mix = internals$mix
prop_posterior = internals$prop_posterior
X = internals$X
cens = internals$cens
Q = internals$Q
model = stanmodels$ARMET_tc_fix
prior_survival_time = internals$prior_survival_time
sample_scaling = internals$sample_scaling
columns_idx_including_time = internals$columns_idx_including_time
# Inference
# Global properties - derived by previous analyses of the whole reference dataset
sigma_intercept = 1.3420415
sigma_slope = -0.3386389
sigma_sigma = 1.1720851
lambda_mu_mu = 5.612671
lambda_sigma = 7.131593
# Non centred
lambda_mu_prior = c(6.2, 1)
lambda_sigma_prior = c(3.3 , 1)
lambda_skew_prior = c(-2.7, 1)
sigma_intercept_prior = c(1.9 , 0.1)
# Filter on level considered
my_genes = reference_filtered |> filter(is_marker) |> pull(symbol) |> unique()
reference_filtered = reference_filtered |> filter(symbol %in% my_genes)
# Number of cell types
number_of_cell_types = reference_filtered |> distinct(cell_type) |> nrow()
# Format
df = ref_mix_format(reference_filtered, mix)
GM = df |> distinct(symbol) |> nrow()
y_source =
df |>
filter(`query`) |>
select(S, Q, symbol, count, GM, sample)
# Dirichlet regression
A = X |> ncol()
# library(rstan)
# fileConn<-file("~/.R/Makevars")
# writeLines(c( "CXX14FLAGS += -O2","CXX14FLAGS += -DSTAN_THREADS", "CXX14FLAGS += -pthread"), fileConn)
# close(fileConn)
# ARMET_tc_model = rstan::stan_model("~/PhD/deconvolution/ARMET/inst/stan/ARMET_tc_fix.stan", auto_write = F)
exposure_multiplier =
sample_scaling |>
filter(sample %in% (y_source |> pull(sample))) |>
arrange(sample) |>
pull(exposure_multiplier) |>
as.array()
init_list = list(
lambda_UFO = rep(6.2, GM),
prop_1 = matrix(rep(1.0/number_of_cell_types, number_of_cell_types*Q), nrow = Q ),
phi = rep(5, number_of_cell_types)
)
ref =
df |>
# Eliminate the query part, not the house keeping of the query
filter(!`query`) |>
select(C, GM, count ) |>
distinct() |>
arrange(C, GM) |>
spread(GM, count) |>
tidybulk::as_matrix(rownames = "C")
y =
y_source |>
select(Q, GM, count) |>
distinct() |>
arrange(Q, GM) |>
spread(GM, count) |>
tidybulk::as_matrix(rownames = "Q")
max_y = max(y)
Sys.setenv("STAN_NUM_THREADS" = shards)
if(cens |> is.null()) cens = rep(0, Q)
which_cens = which(cens == 1) |> as.array()
which_not_cens = which(cens == 0) |> as.array()
how_many_cens = length(which_cens)
max_unseen = ifelse(how_many_cens>0, max(X[,2]), 0 )
if(is.null(prior_survival_time)) prior_survival_time = array(1)[0]
spt = length(prior_survival_time)
CIT = length(columns_idx_including_time)
model_data = list(
shards = shards,
GM = GM,
sigma_slope = sigma_slope,
sigma_sigma = sigma_sigma,
Q = Q,
number_of_cell_types = number_of_cell_types,
y = y,
max_y = max_y,
ref = ref,
A = A,
X = X,
do_regression = do_regression,
how_many_cens = how_many_cens,
which_cens = which_cens,
which_not_cens = which_not_cens,
max_unseen = max_unseen,
spt = spt,
prior_survival_time = prior_survival_time,
CIT = CIT,
columns_idx_including_time = columns_idx_including_time,
exposure_multiplier = exposure_multiplier,
use_data = use_data
)
if( use_cmdstanr ){
# Lad model code
if(file.exists("ARMET_tc_fix_cmdstanr.rds"))
mod = readRDS("ARMET_tc_fix_cmdstanr.rds")
else {
readr::write_file(ARMET_tc_fix_cmdstanr, "ARMET_tc_fix_cmdstanr.stan")
mod = cmdstanr::cmdstan_model( "ARMET_tc_fix_cmdstanr.stan") #, cpp_options = list(stan_threads = TRUE) )
mod %>% saveRDS("ARMET_tc_fix_cmdstanr.rds")
}
if(approximate_posterior)
fit =
mod$variational(
data = model_data ,
init = function () init_list
) %>%
suppressWarnings()
else
fit =
mod$sample(
data = model_data ,
init = function () init_list,
iter_warmup = iterations - sampling_iterations,
iter_sampling = sampling_iterations,
parallel_chains = 3, chains = 3,
threads_per_chain = ceiling(shards / 3)
) %>%
suppressWarnings()
fit$summary() |> arrange(rhat |> desc()) |> filter(rhat > 1.2) |> print()
fit_prop_parsed =
fit$draws("prop_1", format = "draws_df") |>
pivot_longer(
names_to = c( ".variable", "C", "Q"),
cols = contains("prop_1"),
names_sep = "\\[|,|\\]|:",
values_to = ".value"
) |>
suppressWarnings() |>
mutate(Q = as.integer(Q), C = as.integer(C))
if (do_regression) # && paste(as.character(.formula), collapse="") != "~1" )
internals$alpha =
get_alpha_NO_hierarchy_cmdstanr(fit) |>
left_join(
get_generated_quantities_standalone_NO_hierarchy_cmdstanr(fit, internals, model_data),
by = c("node", "C")
)
}
else {
fit =
approximate_posterior |>
when(
(.) ~ vb_iterative(model,
# rstan::stan_model("~/PhD/deconvolution/ARMET/inst/stan/ARMET_tc_fix_hierarchical.stan", auto_write = F),
iter = 50000,
tol_rel_obj = 0.0005,
init = function () init_list
),
~ sampling(
model,
#rstan::stan_model("~/PhD/deconvolution/ARMET/inst/stan/ARMET_tc_fix_hierarchical.stan", auto_write = F),
chains = 3,
cores = 3,
iter = iterations,
warmup = iterations - sampling_iterations,
data = ,
#data = prop_posterior |> c(tree_properties),
# pars=
# c("prop_1", "prop_2", "prop_3", sprintf("prop_%s", letters[1:9])) |>
# c("alpha_1", sprintf("alpha_%s", letters[1:9])) |>
# c("exposure_rate") |>
# c("lambda_UFO") |>
# c("prop_UFO") |>
# c(additional_par_to_save),
init = function () init_list,
save_warmup = FALSE
# ,
# control=list( adapt_delta=0.9,stepsize = 0.01, max_treedepth =10 )
)) %>%
{
(.) |> rstan::summary() %$% summary |> as_tibble(rownames = "par") |> arrange(Rhat |> desc()) |> filter(Rhat > 1.5) |> ifelse_pipe(nrow(.) > 0, ~ print(.x))
(.)
}
fit_prop_parsed =
fit |>
draws_to_tibble("prop_1", "C", "Q") |>
filter(!grepl("_UFO|_rng", .variable)) |>
mutate(Q = Q |> as.integer())
if (do_regression) # && paste(as.character(.formula), collapse="") != "~1" )
internals$alpha =
get_alpha_NO_hierarchy(fit) |>
left_join(
get_generated_quantities_standalone_NO_hierarchy(fit, internals),
by = c("node", "C")
)
}
# Parsing
draws =
fit_prop_parsed |>
ungroup() |>
select(-.variable) |>
mutate(.value_relative = .value)
prop =
fit_prop_parsed |>
drop_na() |>
ungroup() |>
# Add relative proportions
mutate(.value_relative = .value) |>
# add sample annotation
left_join(df |> distinct(Q, sample), by = "Q") |>
# If MCMC is used check divergences as well
parse_summary_check_divergence_NO_hierarchical() |>
# Parse
separate(.variable, c(".variable", "level"), convert = T) |>
# Add sample information
left_join(df |>
filter(`query`) |>
distinct(Q, sample),
by = c("Q", "sample")
)
internals$prop = prop
internals$fit = list(fit)
internals$df = list(df)
internals$draws = list(draws)
internals$prop_posterior[[1]] = fit_prop_parsed |> group_by(.variable, Q, C) |> prop_to_list() %>% `[[` ("prop_1")
internals
}
get_estimates_NO_hierarchy = function(.data, X) {
.data %>%
filter(.variable %>% is.na %>% `!`) %>%
select(cell_type, draws) %>%
mutate(regression = map(draws,
~ .x %>%
group_by(A) %>%
summarise(.median = median(.value), .sd = sd(.value)) %>%
#tidybayes::median_qi(.width = credible_interval) %>%
left_join(tibble(A=1:ncol(X), A_name = colnames(X)) , by = "A") %>%
select(-A) %>%
pivot_wider(
names_from = A_name,
values_from = c(.median, .sd)
))) %>%
select(-draws) %>%
unnest(regression)
}
|
library(shiny)
library(bootstraplib)
library(waiter)
library(bsplus)
library(shinyjs)
bs_theme_new(version = "4+3", bootswatch = "slate")
bs_theme_accent_colors(secondary = "#f8f8f8e6")
bs_theme_add_variables(black = "#88837d")
ui = tagList(
## functions required to be used in the ui
bootstrap(),
use_waiter(include_js = FALSE),
use_bs_popover(),
useShinyjs(),
withMathJax(),
tags$footer(
fluidRow(
column(
width = 4
),
column(
width = 8,
tagList(
tags$img(src = "RStudio-Logo-White.png", width = "80px", height = "30px"),
tags$img(src = "pipe.png", width = "60px", height = "67px"),
tags$img(src = "shiny.png", width = "60px", height = "67px"),
tags$img(src = "tidyverse.png", width = "60px", height = "67px"),
tags$img(src = "gganimate.png", width = "60px", height = "67px"),
tags$img(src = "waiter.png", width = "60px", height = "67px"),
tags$img(src = "ggforce.png", width = "60px", height = "67px"),
tags$img(src = "glue.png", width = "60px", height = "67px")
)
)
),
style = "position:absolute; bottom:0; width:95%;
height:77px; /* Height of the footer */
color: white; padding: 10px;
background-color: #272b30; z-index: 1000;"
),
## color of the action button, height of the input n box
tags$head(
tags$style(HTML("#run{color:#272727; height: 47px}
#n{background:#272b30;}
.irs-bar {background:#272b30; border-top: #272b30; border-bottom: #272b30}
.irs-bar-edge {background:#272b30; border: #272b30;}
.irs-single {background:#272b30;}
.irs-max {background:#E7553C; color: #f8f8f8}
.irs-min {background:#f8f8f8}
.irs-grid-pol {background: #272b30}
#go_to_work{color:#e9ecef; height: 45px; background-color:#447099"))
),
## the actual page starts here!
navbarPage(
id = "navbar",
windowTitle = "Shiny app: Life of Pi",
## title
title = tagList(
fluidRow(
div(
tags$img(src = "ba.png", width = "32px", height = "26px"), HTML(" "),
"Life of Pi: A Monte Carlo Simulation", HTML(" "), style = "color:#aaa;"
),
div("BY ZAUAD SHAHREER ABEER", HTML(" "),
tags$a(href = "https://github.com/shahreyar-abeer", tags$img(src = "GitHub-Mark-Light-120px-plus.png", width = "26px", height = "26px")),
tags$a(href = "https://www.linkedin.com/in/zauad-shahreer/", tags$img(src = "LI-In-Bug.png", width = "30px", height = "26px")),
style = "color:#aaa; position:absolute; float:right; right: 10px;")
)
),
#############################################
## Home tab
tabPanel(
title = "Home",
fluidRow(
column(
width = 1,
br(),
br(),
tags$a(href = "https://github.com/shahreyar-abeer/life_of_pi", img(src = "life_of_pi_hex.png", width = "100px", height = "110px", style = "position: absolute; top: 200px; left:10px;"))
),
column(
width = 9,
p("This app is designed to run a Monte Carlo Simulation to
estimate the value of \\(\\pi\\). I'm sorry to disappoint some of you
who might have though it had something to do with the movie.
But I can share a bit of history though."),
p("Pi wasn’t always known as pi. Before the 1700s,
people referred to the number we know as pi as
'the quantity which when the diameter is multiplied by it, yields the circumference'.
Not surprisingly, people got tired of saying so much whenever they wanted
to talk about Pi. The Welsh mathematician William Jones,
a friend of Sir Isaac Newton, began using the symbol for \\(\\pi\\) in 1706."),
#
# p("This app shows a Monte Carlo estimation of pi
# Those who thought this app had something to do the movie, I'm sorry to disappoint.
# It has less to do with the movie and more to do with mathematician's favorite number, \\(\\pi\\)"),
# p("\\(\\pi\\) has been around since the inception of the earth,
# since it's the ratio of cirumference to the diamtere of a circle.
# So it's always been there! Waiting to be discovered by someone. "),
div(h4("The Algorithm"), align = "center"),
p("At first, we inscribe a circle with unit radius (\\(r = 1)\\) in a square (\\(length = 2 r\\)),
note down the area of the circle and the square. Then we let some points fall
freely on the canvass. The points are independent and may fall at any place within
the square. We then take a note of the poportion \\((p)\\) of points that have fallen inside
the circle to the total number of points. This proportion gives 1/4 th of \\(\\pi\\).
We then multiply the result with 4 to get an estimate of \\(\\pi\\)."),
p("The mathematics working behind is: "),
div(p("Area of the circle, \\(A = \\pi r^2 = \\pi\\)"), align = "center"),
div(p("Area of square, \\((2r)^2 = 4\\)"), align = "center"),
div(p("\\(P(a \\ point \\ falling \\ inside \\ the \\ circle) = \\pi/4\\)"), align = "center"),
div(p("\\(p = \\pi/4 \\implies \\pi = 4 p\\)"), align = "center"),
p("We shall estimate \\(\\pi\\) using this equation. If you are interested to know more, you should find some good stuff ",
tags$a("here.", href = 'http://www.science.smith.edu/dftwiki/images/b/b9/MonteCarloBookChapter.pdf', target = '_blank'),
"And no, there are no tigers there!"),
br(),
div(actionButton("go_to_work", "Enough chit-chat, show me some work!", status = "success"), align = "center")
),
column(
width = 2,
tags$a(href = "https://www.upwork.com/o/profiles/users/~01a42a4a2859568446/", tags$img(src = "logo.png", width = "200px", height = "100px", style = "position: absolute; top: 200px; right:10px;"))
)
),
),
#############################################
## Work tab
tabPanel(
title = "Work",
sidebarLayout(
sidebarPanel(
width = 3,
shinyWidgets::sliderTextInput("n", "Number of points", slider_vals, 1000, F, T)%>%
shinyInput_label_embed(
shiny_iconlink() %>%
bs_embed_popover(
title = "range: (100-10002)",
content = "Values that are multiples of 100 load quite fast. Special value: 10001.
Other values will take some time to render and the animation won't be quite as smooth.",
placement = "right"
)
),
div(actionButton("run", "Let's run!", icon = icon("walking"), width = "40%"), align = "center"),
br(),
p("Just a note: We will never be able to find all the digits of pi because of its very definition as an
irrational number. Babylonian civilization used the fraction 3 ⅛, the Chinese used
the integer 3. By 1665, Isaac Newton calculated pi to 16 decimal places."),
p("In 2017, a Swiss scientist computed more than 22 trillion digits of pi!
The calculation took over a hundred days."),
p("Oh, I hope you have tried the special number, it's 10002."),
p("And if you feel down, don't hesitate to have some pie!"),
hr()
),
mainPanel(
width = 9,
fluidRow(
column(
width = 6,
imageOutput("anim1")
),
column(
width = 6,
imageOutput("anim2")
)
)
)
)
)
),
waiter_show_on_load(html = spin_loaders(42, color = "#aaa"), color = "#272b30", logo = "logo.png")
) | /ui.R | no_license | shahreyar-abeer/life_of_pi | R | false | false | 8,167 | r |
library(shiny)
library(bootstraplib)
library(waiter)
library(bsplus)
library(shinyjs)
bs_theme_new(version = "4+3", bootswatch = "slate")
bs_theme_accent_colors(secondary = "#f8f8f8e6")
bs_theme_add_variables(black = "#88837d")
ui = tagList(
## functions required to be used in the ui
bootstrap(),
use_waiter(include_js = FALSE),
use_bs_popover(),
useShinyjs(),
withMathJax(),
tags$footer(
fluidRow(
column(
width = 4
),
column(
width = 8,
tagList(
tags$img(src = "RStudio-Logo-White.png", width = "80px", height = "30px"),
tags$img(src = "pipe.png", width = "60px", height = "67px"),
tags$img(src = "shiny.png", width = "60px", height = "67px"),
tags$img(src = "tidyverse.png", width = "60px", height = "67px"),
tags$img(src = "gganimate.png", width = "60px", height = "67px"),
tags$img(src = "waiter.png", width = "60px", height = "67px"),
tags$img(src = "ggforce.png", width = "60px", height = "67px"),
tags$img(src = "glue.png", width = "60px", height = "67px")
)
)
),
style = "position:absolute; bottom:0; width:95%;
height:77px; /* Height of the footer */
color: white; padding: 10px;
background-color: #272b30; z-index: 1000;"
),
## color of the action button, height of the input n box
tags$head(
tags$style(HTML("#run{color:#272727; height: 47px}
#n{background:#272b30;}
.irs-bar {background:#272b30; border-top: #272b30; border-bottom: #272b30}
.irs-bar-edge {background:#272b30; border: #272b30;}
.irs-single {background:#272b30;}
.irs-max {background:#E7553C; color: #f8f8f8}
.irs-min {background:#f8f8f8}
.irs-grid-pol {background: #272b30}
#go_to_work{color:#e9ecef; height: 45px; background-color:#447099"))
),
## the actual page starts here!
navbarPage(
id = "navbar",
windowTitle = "Shiny app: Life of Pi",
## title
title = tagList(
fluidRow(
div(
tags$img(src = "ba.png", width = "32px", height = "26px"), HTML(" "),
"Life of Pi: A Monte Carlo Simulation", HTML(" "), style = "color:#aaa;"
),
div("BY ZAUAD SHAHREER ABEER", HTML(" "),
tags$a(href = "https://github.com/shahreyar-abeer", tags$img(src = "GitHub-Mark-Light-120px-plus.png", width = "26px", height = "26px")),
tags$a(href = "https://www.linkedin.com/in/zauad-shahreer/", tags$img(src = "LI-In-Bug.png", width = "30px", height = "26px")),
style = "color:#aaa; position:absolute; float:right; right: 10px;")
)
),
#############################################
## Home tab
tabPanel(
title = "Home",
fluidRow(
column(
width = 1,
br(),
br(),
tags$a(href = "https://github.com/shahreyar-abeer/life_of_pi", img(src = "life_of_pi_hex.png", width = "100px", height = "110px", style = "position: absolute; top: 200px; left:10px;"))
),
column(
width = 9,
p("This app is designed to run a Monte Carlo Simulation to
estimate the value of \\(\\pi\\). I'm sorry to disappoint some of you
who might have though it had something to do with the movie.
But I can share a bit of history though."),
p("Pi wasn’t always known as pi. Before the 1700s,
people referred to the number we know as pi as
'the quantity which when the diameter is multiplied by it, yields the circumference'.
Not surprisingly, people got tired of saying so much whenever they wanted
to talk about Pi. The Welsh mathematician William Jones,
a friend of Sir Isaac Newton, began using the symbol for \\(\\pi\\) in 1706."),
#
# p("This app shows a Monte Carlo estimation of pi
# Those who thought this app had something to do the movie, I'm sorry to disappoint.
# It has less to do with the movie and more to do with mathematician's favorite number, \\(\\pi\\)"),
# p("\\(\\pi\\) has been around since the inception of the earth,
# since it's the ratio of cirumference to the diamtere of a circle.
# So it's always been there! Waiting to be discovered by someone. "),
div(h4("The Algorithm"), align = "center"),
p("At first, we inscribe a circle with unit radius (\\(r = 1)\\) in a square (\\(length = 2 r\\)),
note down the area of the circle and the square. Then we let some points fall
freely on the canvass. The points are independent and may fall at any place within
the square. We then take a note of the poportion \\((p)\\) of points that have fallen inside
the circle to the total number of points. This proportion gives 1/4 th of \\(\\pi\\).
We then multiply the result with 4 to get an estimate of \\(\\pi\\)."),
p("The mathematics working behind is: "),
div(p("Area of the circle, \\(A = \\pi r^2 = \\pi\\)"), align = "center"),
div(p("Area of square, \\((2r)^2 = 4\\)"), align = "center"),
div(p("\\(P(a \\ point \\ falling \\ inside \\ the \\ circle) = \\pi/4\\)"), align = "center"),
div(p("\\(p = \\pi/4 \\implies \\pi = 4 p\\)"), align = "center"),
p("We shall estimate \\(\\pi\\) using this equation. If you are interested to know more, you should find some good stuff ",
tags$a("here.", href = 'http://www.science.smith.edu/dftwiki/images/b/b9/MonteCarloBookChapter.pdf', target = '_blank'),
"And no, there are no tigers there!"),
br(),
div(actionButton("go_to_work", "Enough chit-chat, show me some work!", status = "success"), align = "center")
),
column(
width = 2,
tags$a(href = "https://www.upwork.com/o/profiles/users/~01a42a4a2859568446/", tags$img(src = "logo.png", width = "200px", height = "100px", style = "position: absolute; top: 200px; right:10px;"))
)
),
),
#############################################
## Work tab
tabPanel(
title = "Work",
sidebarLayout(
sidebarPanel(
width = 3,
shinyWidgets::sliderTextInput("n", "Number of points", slider_vals, 1000, F, T)%>%
shinyInput_label_embed(
shiny_iconlink() %>%
bs_embed_popover(
title = "range: (100-10002)",
content = "Values that are multiples of 100 load quite fast. Special value: 10001.
Other values will take some time to render and the animation won't be quite as smooth.",
placement = "right"
)
),
div(actionButton("run", "Let's run!", icon = icon("walking"), width = "40%"), align = "center"),
br(),
p("Just a note: We will never be able to find all the digits of pi because of its very definition as an
irrational number. Babylonian civilization used the fraction 3 ⅛, the Chinese used
the integer 3. By 1665, Isaac Newton calculated pi to 16 decimal places."),
p("In 2017, a Swiss scientist computed more than 22 trillion digits of pi!
The calculation took over a hundred days."),
p("Oh, I hope you have tried the special number, it's 10002."),
p("And if you feel down, don't hesitate to have some pie!"),
hr()
),
mainPanel(
width = 9,
fluidRow(
column(
width = 6,
imageOutput("anim1")
),
column(
width = 6,
imageOutput("anim2")
)
)
)
)
)
),
waiter_show_on_load(html = spin_loaders(42, color = "#aaa"), color = "#272b30", logo = "logo.png")
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.