blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 327 | content_id stringlengths 40 40 | detected_licenses listlengths 0 91 | license_type stringclasses 2 values | repo_name stringlengths 5 134 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 46 values | visit_date timestamp[us]date 2016-08-02 22:44:29 2023-09-06 08:39:28 | revision_date timestamp[us]date 1977-08-08 00:00:00 2023-09-05 12:13:49 | committer_date timestamp[us]date 1977-08-08 00:00:00 2023-09-05 12:13:49 | github_id int64 19.4k 671M ⌀ | star_events_count int64 0 40k | fork_events_count int64 0 32.4k | gha_license_id stringclasses 14 values | gha_event_created_at timestamp[us]date 2012-06-21 16:39:19 2023-09-14 21:52:42 ⌀ | gha_created_at timestamp[us]date 2008-05-25 01:21:32 2023-06-28 13:19:12 ⌀ | gha_language stringclasses 60 values | src_encoding stringclasses 24 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 7 9.18M | extension stringclasses 20 values | filename stringlengths 1 141 | content stringlengths 7 9.18M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0175e294b1a582292450bbf7c43066491d1bb702 | 9adf0182abcaf2fc8510e3ac4a0a19e0271305c9 | /Scripts/Functions/League Settings.R | 67dbb1bff9c42d3141aa9029fe8aca6692268bc6 | [] | no_license | RandalMorris/Football | 4f9d5a638376a87e847d7f2d5024a3d617dd9bd9 | ba8cd229a4c24df357a009697c9141059a8c1200 | refs/heads/master | 2021-01-10T15:29:31.510124 | 2015-11-05T06:56:02 | 2015-11-05T06:56:02 | 45,361,910 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,202 | r | League Settings.R | #League Settings
#League Ids
LeagueID <- 368495
fft_espnSTD <- 26955
espn_std <- 0
#Misc
DailyFantasy <- F
#Set PPR to T if you have Points Per Reception ELSE set to F
ppr <- T
PassBonus <- 400
RushBonus <- 200
RecydBonus <- 200
#Scoring ####
#Offense
passYdsMultiplier <- 1/25 #1 pt per 25 passing yds
passTdsMultiplier <- 4 #4 pts per passing td
Pbonus <- 3 #bonus for passing yards
passIntMultiplier <- -1 #-1 pts per passing interception
rushYdsMultiplier <- 1/10 #1 pt per 10 rushing yds
rushTdsMultiplier <- 6 #6 pts per rushing touchdown
Rbonus <- 3 #bonus for rushing yards
recMultiplier <- 1 #0 pts per reception
recYdsMultiplier <- 1/10 #1 pt per 10 receiving yds
recTdsMultiplier <- 6 #6 pts per receiving touchdown
Rydbonus <- 3 #bonus for receving yards
returnTdsMultiplier <- 6 #6 pts per return touchdown
twoPtsMultiplier <- 2 #2 pts per 2-point conversion
fumlMultiplier <- -1 #-1 pts per fumble lost
#Defense & Spec Teams
sack <- 1
interception <- -2
fumrec <- 2
returntd <- 6
blkKick <- 2
saftey <- 2
pts0 <- 10
pts6 <- 7
pts13 <- 4
pts20 <- 1
pts27 <- 0
pts34 <- -1
pts35 <- -4
|
89b5a4e1772ce6ae44b84c5a4673534ba2014425 | 75a4cc49add672a29d97c50a967673b209529b10 | /Developing-Data-Products-Assignmet-4/server.R | 4b9db0915717113ae689f2d3eb0290ff87fb368f | [] | no_license | NicholasVitsentzatos/datasciencecoursera | 27a05f807e39aa1ab115e4f4ddeab274721a4a63 | 9fc7f4ec526fcc13726c557dda80dfe829493154 | refs/heads/master | 2023-04-18T00:24:30.600847 | 2021-05-04T19:19:47 | 2021-05-04T19:19:47 | 347,302,030 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,172 | r | server.R | library(shiny)
shinyServer(function(input, output) {
output$plot1 <- renderPlot({
set.seed(2016-05-25)
number_of_points <- input$numeric
minX <- input$sliderX[1]
maxX <- input$sliderX[2]
minY <- input$sliderY[1]
maxY <- input$sliderY[2]
dataX <- rnorm(number_of_points, minX, maxX)
dataY <- rnorm(number_of_points, minY, maxY)
xlab <- ifelse(input$show_xlab, "X Axis", "")
ylab <- ifelse(input$show_ylab, "Y Axis", "")
main <- ifelse(input$show_title, "Graph of the random points :P", "")
df<-data.frame(cbind(dataX,dataY))
model <- reactive({
brushed_data <- brushedPoints(df, input$brush1,
xvar = "dataX", yvar = "dataY")
if(nrow(brushed_data) < 2){
return(NULL)
}
lm(dataY ~ dataX, data = brushed_data)
})
plot(df$dataX, df$dataY, xlab = xlab, ylab = ylab, main = main,
xlim = c(-100, 100), ylim = c(-100, 100))
if(!is.null(model())){
abline(model(), col = "blue", lwd = 2)
}
})
}) |
81edf0c276689c2c6c638a73c182b082d4140ee5 | ea0793eb071ad78b2ac3fe73a6f6d2e1f102b572 | /Regression_Model.R | 2624bfcb89ada499a74f72ffda98e585fa661392 | [] | no_license | mhyland312/hello-world | ca2a3e0ffe497d1722c037ceda17aaf17d928ced | b315e058259a93cd8fd875680114810007754acd | refs/heads/master | 2016-09-13T18:02:30.168024 | 2016-04-21T04:52:52 | 2016-04-21T04:52:52 | 56,742,957 | 0 | 0 | null | 2016-04-21T04:47:50 | 2016-04-21T04:40:42 | null | UTF-8 | R | false | false | 5,994 | r | Regression_Model.R | ################################BNSF Project: Waybill Data ################################
###########################################################################################
mydataAllyears<-read.csv("C:/Users/Mike/OneDrive/Documents/Ongoing Research Projects/BNSF/AllYearsData3.csv",header=T)
########Econometric Model##################
#mydataAllyears$ln_ton_sq = log(mydataAllyears$Bill_weight*mydataAllyears$Bill_weight)
mydataAllyears$ln_ton = log(mydataAllyears$Bill_weight)
mydataAllyears$ln_Freight_rev = log(mydataAllyears$Freight_rev)
mydataAllyears$ln_ton_miles= log(mydataAllyears$Bill_weight*mydataAllyears$Est_SL_mil)
#mydataAllyears$ln_mi_sq = log(mydataAllyears$Est_SL_mil*mydataAllyears$Est_SL_mil)
mydataAllyears$ln_miles = log(mydataAllyears$Est_SL_mil)
mydataAllyears$ln_Rev_ton_mile = log(mydataAllyears$Rev_ton_mile )
UMW_allYears<-subset(mydataAllyears, mydataAllyears$O_BEA==110|mydataAllyears$O_BEA==111
|mydataAllyears$O_BEA==112|mydataAllyears$O_BEA==113)
modela<- lm(ln_Rev_ton_mile ~ ln_ton + I(ln_ton^2)+ ln_ton*ln_miles
+ ln_miles + I(ln_miles^2) + Freight_rev + dummy_Oil + Exact_EF + Theo_EF +
dummy_Railroad_own
+ dummy_Grain*year2013
+ dummy_Oil*year2013
+ dummy_Grain*year2010
+dummy_Export
+ Car_cap + Haz_boxcar_Indicator + Intermodal , data=mydataAllyears)
summary(modela)
modelb<- lm(ln_Rev_ton_mile ~ ln_ton + I(ln_ton^2)+ ln_ton*ln_miles
+ ln_miles + I(ln_miles^2)+ Carl_num + I(Carl_num^2) + Freight_rev + dummy_Oil + Exact_EF + Theo_EF +
dummy_Railroad_own
+ dummy_Grain*year2013
+ dummy_Oil*year2013
+ dummy_Grain*year2010
+ dummy_Grain*year2008
+ dummy_Grain*year2006
+ dummy_Grain*year2004
+dummy_Export
+ Car_cap , data=UMW_allYears)
summary(modelb)
mean(UMW_allYears$ln_Rev_ton_mile)
model2<- lm(ln_Rev_ton_mile ~ ln_ton + I(ln_ton^2)+ ln_ton*ln_miles
+ ln_miles + I(ln_miles^2)+ Carl_num + Freight_rev + dummy_Oil + Exact_EF + Theo_EF +
dummy_Railroad_own + dummy_Export + year2013 + year2010 + year2008 + year2006 + year2004
+ dummy_UMW*dummy_Grain*year2013
+ dummy_UMW*dummy_Oil*year2013
+ dummy_UMW*dummy_Grain*year2010
+ Car_cap + Haz_boxcar_Indicator + Intermodal , data=mydataAllyears)
summary(model2)
model3<- lm(ln_Rev_ton_mile ~ ln_ton
+ ln_miles + Carl_num + Freight_rev + dummy_Oil + Exact_EF + Theo_EF +
dummy_Railroad_own +
+ dummy_UMW*dummy_Grain*year2013*dummy_Export
+ dummy_UMW*dummy_Oil*year2013*dummy_Export
+ dummy_UMW*dummy_Grain*year2010*dummy_Export
+ dummy_UMW*dummy_Grain*year2008*dummy_Export
+ Car_cap + Haz_boxcar_Indicator + Intermodal , data=mydataAllyears)
anova(model2,model3)
coefficients(model2)
anova(model2)
summary(model2)$r.squared
summary(model3)
mean(mydataAllyears$ln_Rev_ton_mile)
plot(lm(mydataAllyears$ln_Rev_ton_mile~ mydataAllyears$Carl_num )
#####use training set to do predictions on withheld set
predict(lm.out4, list(temp=new.temps))
model2<- lm(ln_Rev_ton_mile ~ ln_ton + ln_ton_sq + ln_mi_sq
+ ln_miles + Carl_num + Freight_rev + dummy_Oil + Exact_EF + Theo_EF +
dummy_Grain + dummy_Export + dummy_Railroad_own +
year2013 + year2010 + year2008 + year2006 + year2004
+ dummy_UMW
+ dummy_UMW*dummy_Grain*year2013*dummy_Export
+ dummy_UMW*dummy_Oil*year2013*dummy_Export
+ dummy_UMW*dummy_Grain*year2010*dummy_Export +
dummy_UMW*dummy_Oil*year2010*dummy_Export +
dummy_UMW*dummy_Grain*year2008*dummy_Export +
dummy_UMW*dummy_Oil*year2008*dummy_Export +
dummy_UMW*dummy_Grain*year2006*dummy_Export +
dummy_UMW*dummy_Oil*year2006*dummy_Export +
+ Car_cap + Haz_boxcar_Indicator + Intermodal , data=mydataAllyears)
model2<- lm(ln_Rev_ton_mile ~ ln_ton + ln_ton_sq + ln_mi_sq + ln_Misc_charg + ln_Transit_charg
+ ln_miles + Carl_num + Freight_rev + dummy_Oil +
dummy_Grain + dummy_Export + dummy_Railroad_own +
year2013 + year2010 + year2008 + year2006 + year2004 + dummy_UMW +
dummy_UMW*dummy_Grain*year2013*dummy_Export +
dummy_UMW*dummy_Oil*year2013*dummy_Export +
dummy_UMW*dummy_Grain*year2010*dummy_Export +
dummy_UMW*dummy_Oil*year2010*dummy_Export +
dummy_UMW*dummy_Grain*year2008*dummy_Export +
dummy_UMW*dummy_Oil*year2008*dummy_Export +
dummy_UMW*dummy_Grain*year2006*dummy_Export +
dummy_UMW*dummy_Oil*year2006*dummy_Export +
Car_cap + Haz_boxcar_Indicator + Intermodal , data=mydataAllyears)
model<- lm((Rev_ton_mile) ~ Bill_weight + log(Bill_weight) + Est_SL_mil
+ log(Est_SL_mil) + Carl_num + Freight_rev + dummy_Oil +
dummy_Grain + dummy_Export + dummy_Railroad_own +
year2013 + year2010 + year2008 + year2006 + year2004 , data=mydataAllyears)
coefficients(model)
anova(model)
summary(model)$r.squared
dim(mydataAllyears)
|
20b4be4a4761c3d865a92f791a622788a3a61ccd | 45e79381152047a7777d50271e38c726013be682 | /R/ODATAcleanName.R | db270542336d46c1336a79fc77741d719e6e68a8 | [] | no_license | ceparman/Core5.3 | e13530d3fd7a457ee39935400766badddc5120bd | de8f6e946ca159332979807eba997b5efbf123d4 | refs/heads/master | 2020-03-23T08:08:06.929458 | 2019-02-06T14:24:36 | 2019-02-06T14:24:36 | 141,309,256 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 668 | r | ODATAcleanName.R | #' ODATAcleanName - converts names to ODATA compliant version. Used to clean names in ODATA calls.
#'
#' \code{ODATAcleanName} Clean a name for ODATA.
#' @param name string to clean
#' @export
#' @return Returns name in ODATA compliant form
#' @examples
#'\dontrun{
#' new_name <-CoreAPIV2::ODATAcleanName("384 Well Plate")
#' new_name
#' _384_WELL_PLATE
#' }
#'@author Craig Parman ngsAnalytics, ngsanalytics.com
#'@description \code{ODATAcleanName} - converts names to ODATA compliant version. Used to clean names in ODATA calls.
ODATAcleanName <- function(name)
{
name <- gsub("(^[1-9])", "_\\1", name)
name <- gsub(" ", "_", name)
name
} |
736b98c1da594ba73b8ac64c37486e293cebcd85 | 373f2abd88834acc0d1ab21ba13ce335600ceb0f | /demo/analysisltraj.r | 4ff2986bc0605d5ae1e639b87e6548e6fd5bf9d8 | [] | no_license | ClementCalenge/adehabitat | fa26e43fba432c29a5757fcd4b5f9ffd972bdd44 | 23ba023d5a57eec861fb6d3d07772cb9d2db6968 | refs/heads/master | 2021-01-22T05:20:32.012511 | 2018-01-28T12:27:32 | 2018-01-28T12:27:32 | 81,652,118 | 5 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,949 | r | analysisltraj.r | set.seed(257)
opar <- par(ask = dev.interactive(orNone = TRUE))
cat("******************************************************\n",
"We give here an example on the mouflon. It just \n",
"illustrates the use of the functions to handle trajectories\n",
"with adehabitat",
"\n******************************************************\n")
##************************************************************
##
## First approach on the data
data(mouflon)
mouflon
id(mouflon)
burst(mouflon)
head(mouflon[[1]])
## plot the data
plot(mouflon)
trajdyn(mouflon)
## Constant time lag between relocations ?
is.regular(mouflon)
mouflon
## yes, one relocation every 20 minutes
## There are some missing values in the data
summaryNAltraj(mouflon)
## But only a weak proportion! Only one for the second week-end!
## Note, however, that for the first week-end, the missing values
## are not randomly distributed:
runsNAltraj(mouflon[1])
plotNAltraj(mouflon[1])
## There is a runs of missing values on sunday... to be kept
## in mind for the rest of this analysis (though the weak
## proportion of missing values is here unlikely to affect the
## results of the analysis)
## For the sake of simplicity, we will work only on the first
## week-end:
mouflon <- mouflon[1]
##************************************************************
##
## Comparison with a model:
## A correlated random walk is made of successive "steps"
## independent from the point of view of the step length
## and the relative angles between successive relocations
## Does this model describes the trajectories adequately?
## we test the independence of relative angles between
## successive steps:
testang.ltraj(mouflon, "relative")
## Not significant
## Are the steps length independent?
wawotest(mouflon)
## There is a positive autocorrelation.
## Another way to perform this test:
indmove(mouflon)
## Time series approach:
## The autocorrelation function on
## the distance:
acf(na.omit(mouflon[[1]]$dist))
## A lack of independence with lag = 1
## Look at the periodogram
spectrum(na.omit(mouflon[[1]]$dist), taper=0, log="no")
## No clear pattern emerges: no periodicity
## A time plot of the step length
plotltr(mouflon, "dist")
## This is not white noise! what already indicated the tests...
## There are some periods when the animal is moving more slowly
## than others.
##************************************************************
##
## Segmentation: STILL UNDER RESEARCH!!!!!!!
## We try to partition the trajectory into several types of behaviours
## we will work on the dist, and suppose a chi distribution for
## the distribution of distances, with different scaling factors
## The models will be chi distribution with different scaling
## factors:
## The function foo allows to estimate the scaling factor for a
## chi distribution from a data frame containing the dx, dy and dt
## component of a trajectory (see hbrown).
foo <- function(x)
{
u1 <- x$dx/sqrt(x$dt)
u2 <- x$dy/sqrt(x$dt)
oo <- cbind(u1,u2)
oo <- oo[!apply(oo,1,function(y) any(is.na(y))),]
vc <- crossprod(scale(oo, scale = FALSE))/nrow(oo)
h <- sqrt(mean(diag(vc)))
return(h)
}
## Compute the scaling factor for sliding window
sliwinltr(mouflon, foo, step=5, type="locs")
## OK, we have roughly three types of movements:
scfac <- c(0.5, 1.5, 2.5)
(limod <- as.list(paste("dchi(dist/(sqrt(dt)*",
scfac, "))")))
## Then, build the probability matrix
mod1 <- modpartltraj(mouflon, limod)
mod1
## Computes the optimal number of segments
bestpartmod(mod1, Km=70)
## The partition with 21 segments
par <- partmod.ltraj(mouflon, 21, mod1)
par
plot(par)
## In the case where the periodogram on the distance indicates a
## period in the movements of the animal, it could be of interest
## to study the periodicity of the types of movements (are
## certain types of movements preferably used at certain periods of
## the day?). Indeed, there is no hypothesis of stationarity
## With this partitioning algorithm
## A possible analysis could then be to identify correlates
## between the type of movements and the habitat
##************************************************************
##
## Rediscretization
## Another common way to analyse trajectory is to rediscretize them
## with a constant step length
plot(mouflon)
red <- redisltraj(mouflon, 100)
plot(red)
## ...Note that the trajectory is no longer regular
red
## We do not present this type of analysis here, as a
## more intensively sampled trajectory is needed for this
## type of analysis
cat("*******************************************************\n",
"The deeply commented source for this demo can be found in the file:\n",
file.path(system.file(package = "adehabitat"), "demo", "analysisltraj.r\n"),
"Examples of management of trajectories are given in demo(managltraj)\n",
"******************************************************\n")
|
9286fe673b6ccf6b87c1ee3fdb3ca6f4035cd57f | e7211133b68aa312c8031558d346f81da7c0f691 | /man/dot-mcBalanced.Rd | 5cba5f18cdf3bee2e415f910b0c8b23560c27adb | [
"MIT"
] | permissive | tkimhofer/metabom8 | 542c7effc322db07bfca555ff130732d63caa088 | 37d04910d6a5e47c0e0702d122f345373949d0d4 | refs/heads/master | 2023-07-19T12:31:30.037418 | 2022-11-17T06:56:19 | 2022-11-17T06:56:19 | 262,197,875 | 2 | 7 | NOASSERTION | 2023-07-10T15:09:11 | 2020-05-08T01:32:06 | R | UTF-8 | R | false | true | 964 | rd | dot-mcBalanced.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/AllGenerics.R
\name{.mcBalanced}
\alias{.mcBalanced}
\title{Monte Carlo Cross Validation (MCCV) generation of training sets indices}
\usage{
.mcBalanced(k, split, stratified)
}
\arguments{
\item{k}{int k parameter}
\item{split}{Fraction of samples used to generate training set for class/group-balanced Monte Carlo (MC) CV}
\item{stratified}{list with 3 elements: 1) char: R for regression (Y is numeric), DA for discriminant analysis (Y treated as categorical), prefix '-mY' indicates multi-column Y (see Y) 2) Y matrix (observations times variables), always with ncol = 1 (stratified CV generation for multi-Y to be implemented) and 3) quantile function probabilities for stratification of numberic Y}
}
\value{
list of Y row-indices for each fold
}
\description{
This function creates a list of indices that represent k fold subsets for MCCV
}
\section{}{
NA
}
\keyword{internal}
|
6092e904cd447ab1c089f9091adee40fb2331597 | 11e8dbd018be7ae3d176f513a12cac38185679f3 | /R/is_package.R | 6de71cb0837eb5344e3f021e73aea8acc1277e20 | [] | no_license | etiennebacher/ebmisc | 02b016fcf3578b92a856e7e2214eca458f9aaaf1 | a44a328c7aed028f4ceddc14c1196f4e6843f9c7 | refs/heads/master | 2023-05-04T10:06:03.917871 | 2021-05-31T08:58:57 | 2021-05-31T08:59:21 | 339,828,675 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 460 | r | is_package.R | #' Detect if we are in a package environment
#'
#' @return Boolean
#' @export
#'
is_package <- function() {
if (file.exists("DESCRIPTION")) {
x <- paste(readLines("DESCRIPTION"), collapse = " ")
first_cond <- grepl("Type: Package", x)
second_cond <- grepl("Package:", x)
if (first_cond || second_cond) {
is_package <- TRUE
} else {
is_package <- FALSE
}
} else {
is_package <- FALSE
}
return(is_package)
}
|
3eca5decad8cfa6f590372619969261dd0f3aab0 | 5bf8dd0054f674b3a65c6787d242c792cdb2041a | /man/CloneDeMix.Rd | e62a720c124b59ac3d8e5621dd8267243ae3821e | [
"MIT"
] | permissive | AshTai/CloneDeMix | c2990c53729c98a1a73a610a076244cf5af558c8 | 97630d40a4182fad566451804296e6a6c232fdd2 | refs/heads/master | 2021-07-21T05:04:22.658393 | 2018-11-28T12:58:29 | 2018-11-28T12:58:29 | 108,508,736 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,259 | rd | CloneDeMix.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/CloneDeMix.r
\name{CloneDeMix}
\alias{CloneDeMix}
\title{Decomposing the subclonal structure of tumors with two-way mixture models on copy number aberrations.}
\usage{
CloneDeMix(tumor, normal = NULL, threshold = 10^-5, iterC = 10^3,
CNVstate = c(0:10), method = "aic")
}
\arguments{
\item{tumor}{A G by N count matrix of tumor samples, where G is the gene number and N is the sample size.}
\item{normal}{A vector of length s. It's DNA profile from the paired normal sample. If it's empty, the baseline is calculated from sample mean.}
\item{threshold}{The threhold of convergence. Default is 10^-5.}
\item{CNVstate}{A vector of considered copy number state.}
\item{method}{The criteria for the final clone number.}
\item{iterationC}{Maximum number of iterations. Default is 1000.}
}
\value{
A list is containing an estimated CNV matrix, MCP matrix, and the number of predicted clone number.
}
\description{
A R package for deconvoluting subclonal copy number and mutational cellular prevalence.
}
\examples{
data("ESCC_chr1")
res <- CloneDeMix(tumor=ESCC_chr1$tumor, normal=ESCC_chr1$normal)
head(res$CNV); head(res$MCP)
}
\author{
An-Shun Tai \email{daansh13@gmail.com}
}
|
40ee1db75879293b67cdd122767c7e867f8e3d4e | d05eba7219ecf783f51259ea572b36a89c192b19 | /z_NorthFarmExperimentMicaSenseV3.R | 3d36c4f88dd9cbc7ab106a9a578c3a4fefb99b04 | [] | no_license | ChrisZarzar/phd_research | af01d559cc78ef90b5b5893f0a8c50fb33b1e4f3 | 61b3271b0be341b5e3a927a9f7c25de692fdf785 | refs/heads/master | 2020-04-05T09:34:26.174089 | 2018-11-08T20:27:50 | 2018-11-08T20:27:50 | 156,763,838 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 5,063 | r | z_NorthFarmExperimentMicaSenseV3.R | #Author: Christopher Zarzar
#Created: 19-Sep-2016
#NOTES: This script was createdto test
# whether the atmosphere plays a
# statistically significant role on the
# imagery collected by the UAS.
# This is part of the North Farm experiment
# started April 2016
#EDITED ON 10-18-2016 CZ: Discovered that I had read in the same 06% spreadsheets 3 time. Adjusted and fixed script and results
#EDITED on 10-26-2016 CZ: Worked with Mercer to simplify the scripts using loops
#EDITED on 11-06-2016 CZ: ADjusted script so it outputs individual pngs.
# Read in the data
panel06.data <- read.csv("E:/Research/RWorkspace/datasets/AltitudesCombined06%_MicaSense_adjusted.csv", header = TRUE)
panel22.data <- read.csv("E:/Research/RWorkspace/datasets/AltitudesCombined22%_MicaSense_adjusted.csv", header = TRUE)
panel44.data <- read.csv("E:/Research/RWorkspace/datasets/AltitudesCombined44%_MicaSense_adjusted.csv", header = TRUE)
# Output all returned values to text file
sink("E:/Research/RWorkspace/NorthFarmTest_Mica.txt")
#pdf(file = "E:/Research/RWorkspace/NorthFarmPlots_Mica.pdf")
#png(file = "E:/Research/RWorkspace/NorthFarmPlots_Mica.png")
# Create multipanel image for the plots, Need to work on getting just one axis to plot across and putting on letter labels
#par(mfrow = c(5,3))
#par(mar = c(2, 1, 2, 1), oma = c(1, 1, 0, 0))
# Execute and load libraries and functions that I will need
permutationTestMeans <- function(x,y,B=1000) {
n1 <- length(x)
n2 <- length(y)
delta <- abs(mean(x) - mean(y))
fullset <- c(x,y)
new.delta <- numeric(B)
for (i in 1:B) {
sample.1 <- sample(fullset,n1,replace=T)
sample.2 <- sample(fullset,n2,replace=T)
new.delta[i]<- abs(mean(sample.1) - mean(sample.2))
}
counts <- ifelse(new.delta >= delta,1,0)
p.value <- sum(counts) / B
return(p.value)
}
library("boot")
mean.boot <- function(x,d){
return(mean(x[d]))
}
source('E:/RWorkspace/rcodes/plot.ci.R')
# The analysis for all altitudes and panel
set.seed(100)
tarp <- c('06', '22', '44')
alt <- c('100','200','300','400','500','600','700','800')
band <- c('Blue', 'Green', 'Red', 'rEdge','NIR')
band.col <- c(5:9)
for (k in 1:length(band.col)){
for(j in 1:length(tarp)){
plotmat <- numeric(3)
for (i in 1:length(alt)){
working.cmd <- paste('working.data <- panel',tarp[j],'.data',sep='')
eval(parse(text=working.cmd))
level <- as.double(alt[i])
panel.tmp <- ifelse(working.data[,3]<=level & working.data[,3]>(level-100),working.data[,band.col[k]],NA)
panel.tmp <- panel.tmp[!is.na(panel.tmp)]
if (i==1){
panel.sfc <- panel.tmp
}else{
permtest <- permutationTestMeans(panel.sfc,panel.tmp,B=10000)
print(permtest)
if(permtest < .05){
print(paste('Test is significant. We can state that the dataset for the ',band[k],' band ',tarp[j],' panel at ', alt[i],' feet is different than the ground reference data',sep=''))
}else{
print(paste('Test is not significant. We cannot state that the dataset for the ',band[k],' band ',tarp[j],' panel at ', alt[i],' feet is different than the ground reference data',sep=''))
}
}
# Run bootstrap confidence interval on data for 6% panel
boot.tmp <- boot(panel.tmp,mean.boot,R=1000)
ci.cmd <- paste('ci.',tarp[j],'_',alt[i],'.',band[k],'<- quantile(boot.tmp$t,probs=c(0.025,0.5,0.975))',sep='')
eval(parse(text=ci.cmd))
#Now run a permutation test to determine whether the two dataset samples come from the same population
#Running a two sided permutation test to determine whether mean of the datasets are the same (alpha = 0.05: 2 sided)
plotmat.cmd <- paste('plotmat <- cbind(plotmat,','ci.',tarp[j],'_',alt[i],'.',band[k],')',sep='')
eval(parse(text=plotmat.cmd))
}
# cbind the confidence intervals together and make plots of altitude CI'S
#Plot the CIs
png(file =paste('E:/Research/RWorkspace/NorthFarmPlots_Mica_',band[k],'_',tarp[j], '.png', sep=''))
plotmat <- plotmat[,-1]
xrange <- seq(100,800,by=100)
yrange <- seq(10000,80000,by=10000)
barwidth=0.2
plot.title <- paste(band[k],' Band ',tarp[j], '% Panel', sep='')
n.plots <- length(plotmat[1,])
#plot(plotmat[2,],main=plot.title,xaxt="n",ylim=c(10000,80000), xlab="Altitude AGL (feet)",ylab="Radiance",cex.main=1, cex.axis=.90, cex.lab=.90, pch=16)
plot(plotmat[2,],main=plot.title,xaxt="n",ylim=c(10000,80000), xlab="",ylab="",cex.main=3, cex.axis=2, cex.lab=2, pch=16)
for (i in 1:n.plots) {
lines(c(i-barwidth,i+barwidth),c(plotmat[1,i],plotmat[1,i]))
lines(c(i-barwidth,i+barwidth),c(plotmat[3,i],plotmat[3,i]))
lines(c(i,i),c(plotmat[1,i],plotmat[3,i]))
}
axis(1, at=1:8, labels=xrange, cex.axis=2, las=2)
abline(h=plotmat[2,1], col="blue")
abline(h=plotmat[1,1],lty= 2, col="red")
abline(h=plotmat[3,1],lty= 2, col="red")
dev.off()
}
}
## COMMET THE BELOW BACK IN IF YOU WANT IT IN AN ENTIRE SINGLE FILE.
# dev.off()
closeAllConnections()
#END
|
6a5a0cbdf89e320386eb571232da94b723fe0457 | 3b884af1751c31d641a128304921227d4851bf21 | /R-scripts/AssociationRuleMining.R | ac91adb9b853df571a67d97d57713459b4beed29 | [
"MIT"
] | permissive | hamzeiehsan/Template-for-answering-where-questions | 04de960e565167c9d9de1cb469264f8792e8ded1 | 584c5cd21d204ccdf92fc09136738c9bd36ba31f | refs/heads/main | 2023-02-23T07:57:32.211787 | 2021-01-22T07:09:50 | 2021-01-22T07:09:50 | 323,803,726 | 2 | 0 | null | null | null | null | UTF-8 | R | false | false | 13,407 | r | AssociationRuleMining.R | ####################################################
#Installing the packages
#install.packages("Matrix")
#install.packages("arules")
#install.packages("qlcMatrix")
#install.packages("data.table")
#install.packages("ggplot2")
#install.packages("ggpubr")
#install.packages("gridExtra")
#install.packages("stringr")
#install.packages("RColorBrewer")
####################################################
#set workspace to this folder
setwd("D:/Work/IJGIS/R-scripts")
####################################################
#importing the packages
library(arules)
library(qlcMatrix)
library(data.table)
library(ggplot2)
library(ggpubr)
library(gridExtra)
library(stringr)
library(RColorBrewer)
####################################################
#######################################
#######################################
###############TYPE##############
#######################################
#######################################
type_raw <- read.table(file = "../sequences/type-nf-all.txt", sep = ",")
transpose_type_raw <- t(type_raw)[1, ]
pw <- pwMatrix(transpose_type_raw, sep = " ")
tt <- ttMatrix(pw$rownames)
distr <- (tt$M*1) %*% (pw$M*1)
distr_ngCMat = as (distr, "ngCMatrix")
ttRows <- tt$rownames
td <- as.data.frame(ttRows)
setnames(td, "ttRows", "labels")
trans1 <- new("transactions", data = distr_ngCMat, itemInfo = td)
type_rules <- apriori(trans1, parameter = list(support = 100/trans1@data@Dim[2],
confidence = 0.5, maxlen = 3, maxtime = 15))
type_rules_d <- inspect(head(sort(type_rules, by = "lift"), 100))
#plot(type_rules, jitter = 0)
write.csv(x = type_rules_d, file = "result/type_rules_qa.csv")
#######################################
#######################################
###############SCALE##############
#######################################
#######################################
scale_raw <- read.table("../sequences/scale-nf-all.txt", sep = ",")
transpose_scale_raw <- t(scale_raw)[1, ]
pw_scale <- pwMatrix(transpose_scale_raw, sep = " ")
tt_scale <- ttMatrix(pw_scale$rownames)
distr_scale <- (tt_scale$M*1) %*% (pw_scale$M*1)
distr_ngCMat_scale = as (distr_scale, "ngCMatrix")
ttRows_scale <- tt_scale$rownames
td_scale <- as.data.frame(ttRows_scale)
setnames(td_scale, "ttRows_scale", "labels")
trans_scale <- new("transactions", data = distr_ngCMat_scale, itemInfo = td_scale)
scale_rules <- apriori(trans_scale, parameter = list(support = 100/trans_scale@data@Dim[2],
confidence = 0.5, maxlen = 3, maxtime = 15))
inspect(head(sort(scale_rules, by = "support"), 100))
scale_rules_d <- inspect(head(sort(scale_rules, by = "support"), 100))
#plot(scale_rules, jitter = 0)
write.csv(x = scale_rules_d, file = "result/scale_rules_qa.csv")
#######################################
#######################################
###############PROMINENCE##############
#######################################
#######################################
imp_raw <- read.table("../sequences/prominence-nf-all.txt", sep = ",")
transpose_imp_raw <- t(imp_raw)[1, ]
pw_imp <- pwMatrix(transpose_imp_raw, sep = " ")
tt_imp <- ttMatrix(pw_imp$rownames)
distr_imp <- (tt_imp$M*1) %*% (pw_imp$M*1)
distr_ngCMat_imp = as (distr_imp, "ngCMatrix")
ttRows_imp <- tt_imp$rownames
td_imp <- as.data.frame(ttRows_imp)
setnames(td_imp, "ttRows_imp", "labels")
trans_imp <- new("transactions", data = distr_ngCMat_imp, itemInfo = td_imp)
imp_rules <- apriori(trans_imp, parameter = list(support = 100/trans_imp@data@Dim[2],
confidence = 0.5, maxlen = 3, maxtime = 15))
inspect(head(sort(imp_rules, by = "support"), 100))
imp_rules_d <- inspect(head(sort(imp_rules, by = "support"), 100))
write.csv(x = imp_rules_d, file = "result/prominence_rules_qa.csv")
#######################################################################################################
#######################################################################################################
##############################################FUNCTIONS################################################
fun.extract.ncomplex.ids = function(questions, n) {
validIds = c()
counter = 0
for (i in 1:length(questions[,1])) {
qVals = questions[i, 2:length(questions)]
if (length(qVals[qVals!=""]) == n) {
counter= counter + 1
validIds[counter] = questions[i, 1]
}
}
return (validIds)
}
fun.write.simple.complex = function(all, questions, fileAddressSWQ, fileAddressDWQ) {
swq_ids <- fun.extract.ncomplex.ids(questions, 1)
swq <- all[all$V1 %in% swq_ids, 2:length(all)]
dwq <- all[!all$V1 %in% swq_ids, 2:length(all)]
write.table(row.names = FALSE, file = fileAddressSWQ, x = swq, col.names = FALSE)
write.table(row.names = FALSE, file = fileAddressDWQ, x = dwq, col.names = FALSE)
return (TRUE)
}
fun.extract.rules = function(inputAddress, outputAddress, minconf, minsup, window) {
raw <- read.table(inputAddress, sep = ",")
transpose_raw <- t(raw)[1, ]
pw <- pwMatrix(transpose_raw, sep = " ")
tt <- ttMatrix(pw$rownames)
distr <- (tt$M*1) %*% (pw$M*1)
distr_ngCMat = as (distr, "ngCMatrix")
ttRows <- tt$rownames
td <- as.data.frame(ttRows)
setnames(td, "ttRows", "labels")
trans1 <- new("transactions", data = distr_ngCMat, itemInfo = td)
rules <- apriori(trans1, parameter = list(support = 100/trans1@data@Dim[2],
confidence = 0.5, maxlen = window, maxtime = 15))
rules_d <- inspect(head(sort(rules, by = "support"), 100))
write.csv(x = rules_d, file = outputAddress)
return (rules)
}
################################ReadFiles##################################
prominence_questions <- read.table("../sequences/prominence-nf-Q.txt",
header = FALSE, sep = " ", col.names = paste0("V",seq_len(5)),
fill = TRUE)
prominence_all <- read.table("../sequences/prominence-nf-all.txt",
header = FALSE, sep = " ", col.names = paste0("V",seq_len(20)),
fill = TRUE)
prominence_answers <- read.table("../sequences/prominence-nf-A.txt",
header = FALSE, sep = " ", col.names = paste0("V",seq_len(15)),
fill = TRUE)
scale_questions <- read.table("../sequences/scale-nf-Q.txt",
header = FALSE, sep = " ", col.names = paste0("V",seq_len(4)),
fill = TRUE)
scale_all <- read.table("../sequences/scale-nf-all.txt",
header = FALSE, sep = " ", col.names = paste0("V",seq_len(20)),
fill = TRUE)
scale_answers <- read.table("../sequences/scale-nf-A.txt",
header = FALSE, sep = " ", col.names = paste0("V",seq_len(15)),
fill = TRUE)
type_questions <- read.table("../sequences/type-nf-Q.txt",
header = FALSE, sep = " ", col.names = paste0("V",seq_len(5)),
fill = TRUE)
type_all <- read.table("../sequences/type-nf-all.txt",
header = FALSE, sep = " ", col.names = paste0("V",seq_len(20)),
fill = TRUE)
type_answers <- read.table("../sequences/type-nf-A.txt",
header = FALSE, sep = " ", col.names = paste0("V",seq_len(15)),
fill = TRUE)
################################Differentiating SWQ and DWQ##################################
fun.write.simple.complex(all= prominence_all, questions = prominence_questions,
fileAddressSWQ = "../sequences/prominence-nf-all-SWQ.txt",
fileAddressDWQ = "../sequences/prominence-nf-all-DWQ.txt")
fun.write.simple.complex(all= scale_all, questions = scale_questions,
fileAddressSWQ = "../sequences/scale-nf-all-SWQ.txt",
fileAddressDWQ = "../sequences/scale-nf-all-DWQ.txt")
fun.write.simple.complex(all= type_all, questions = type_questions,
fileAddressSWQ = "../sequences/type-nf-all-SWQ.txt",
fileAddressDWQ = "../sequences/type-nf-all-DWQ.txt")
fun.write.simple.complex(all= type_questions, questions = type_questions,
fileAddressSWQ = "../sequences/type-nf-Q-SWQ.txt",
fileAddressDWQ = "../sequences/type-nf-Q-DWQ.txt")
fun.write.simple.complex(all= type_answers, questions = type_questions,
fileAddressSWQ = "../sequences/type-nf-A-SWQ.txt",
fileAddressDWQ = "../sequences/type-nf-A-DWQ.txt")
#############################################################################################
scale_rules_swq = fun.extract.rules (inputAddress = "../sequences/scale-nf-all-SWQ.txt",
outputAddress = "result/scale_swq_rules_qa.csv",
minsup = 0.0034, minconf = 0.5, window = 3)
scale_rules_dwq = fun.extract.rules (inputAddress = "../sequences/scale-nf-all-DWQ.txt",
outputAddress = "result/scale_dwq_rules_qa.csv",
minsup = 0.0034, minconf = 0.5, window = 3)
scale_rules_all = fun.extract.rules (inputAddress = "../sequences/scale-nf-all.txt",
outputAddress = "result/scale_all_rules_qa.csv",
minsup = 0.0034, minconf = 0.5, window = 3)
prom_rules_swq = fun.extract.rules (inputAddress = "../sequences/prominence-nf-all-SWQ.txt",
outputAddress = "result/prominence_swq_rules_qa.csv",
minsup = 0.0034, minconf = 0.5, window = 3)
prom_rules_dwq = fun.extract.rules (inputAddress = "../sequences/prominence-nf-all-DWQ.txt",
outputAddress = "result/prominence_dwq_rules_qa.csv",
minsup = 0.0034, minconf = 0.5, window = 3)
type_rules_swq = fun.extract.rules (inputAddress = "../sequences/type-nf-all-SWQ.txt",
outputAddress = "result/type_swq_rules_qa.csv",
minsup = 0.0034, minconf = 0.5, window = 3)
type_rules_dwq = fun.extract.rules (inputAddress = "../sequences/type-nf-all-DWQ.txt",
outputAddress = "result/type_dwq_rules_qa.csv",
minsup = 0.0034, minconf = 0.5, window = 3)
t_p = ggplot(type_rules@quality, aes(x=support, y=confidence)) +
geom_point(aes(colour= lift)) +
scale_color_gradient(low = "#ffffff", high = "#000000", limits=c(0.6, 2.2)) +
theme_bw() + theme(legend.position = "top", legend.box = "horizontal") +
coord_cartesian(xlim =c(0.0, 1.0), ylim = c(0.5, 1.0))
ts_p = ggplot(type_rules_swq@quality, aes(x=support, y=confidence)) +
geom_point(aes(colour= lift)) +
scale_color_gradient(low = "#ffffff", high = "#000000", limits=c(0.6, 2.2)) +
theme_bw() + theme(legend.position = "none") +
coord_cartesian(xlim =c(0.0, 1.0), ylim = c(0.5, 1.0))
td_p = ggplot(type_rules_dwq@quality, aes(x=support, y=confidence)) +
geom_point(aes(colour= lift)) +
scale_color_gradient(low = "#ffffff", high = "#000000", limits=c(0.6, 2.2)) +
theme_bw() + theme(legend.position = "none") +
coord_cartesian(xlim =c(0.0, 1.0), ylim = c(0.5, 1.0))
s_p = ggplot(scale_rules@quality, aes(x=support, y=confidence)) +
geom_point(aes(colour= lift)) +
scale_color_gradient(low = "#ffffff", high = "#000000", limits=c(0.6, 2.2)) +
theme_bw() + theme(legend.position = "none") +
coord_cartesian(xlim =c(0.0, 1.0), ylim = c(0.5, 1.0))
ss_p = ggplot(scale_rules_swq@quality, aes(x=support, y=confidence)) +
geom_point(aes(colour= lift)) +
scale_color_gradient(low = "#ffffff", high = "#000000", limits=c(0.6, 2.2)) +
theme_bw() + theme(legend.position = "none") +
coord_cartesian(xlim =c(0.0, 1.0), ylim = c(0.5, 1.0))
sd_p = ggplot(scale_rules_dwq@quality, aes(x=support, y=confidence)) +
geom_point(aes(colour= lift)) +
scale_color_gradient(low = "#ffffff", high = "#000000", limits=c(0.6, 2.2)) +
theme_bw() +theme(legend.position = "none") +
coord_cartesian(xlim =c(0.0, 1.0), ylim = c(0.5, 1.0))
p_p = ggplot(imp_rules@quality, aes(x=support, y=confidence)) +
geom_point(aes(colour= lift)) +
scale_color_gradient(low = "#ffffff", high = "#000000", limits=c(0.6, 2.2)) +
theme_bw() + theme(legend.position = "none") +
coord_cartesian(xlim =c(0.0, 1.0), ylim = c(0.5, 1.0))
ps_p = ggplot(prom_rules_swq@quality, aes(x=support, y=confidence)) +
geom_point(aes(colour= lift)) +
scale_color_gradient(low = "#ffffff", high = "#000000", limits=c(0.6, 2.2)) +
theme_bw() + theme(legend.position = "none") +
coord_cartesian(xlim =c(0.0, 1.0), ylim = c(0.5, 1.0))
pd_p = ggplot(prom_rules_dwq@quality, aes(x=support, y=confidence)) +
geom_point(aes(colour= lift)) +
scale_color_gradient(low = "#ffffff", high = "#000000", limits=c(0.6, 2.2)) +
theme_bw() + theme(legend.position = "none") +
coord_cartesian(xlim =c(0.0, 1.0), ylim = c(0.5, 1.0))
grid.arrange(t_p, ts_p, td_p, s_p, ss_p, sd_p, p_p, ps_p, pd_p, ncol=3, nrow = 3, layout_matrix = rbind(c(1,2,3), c(4,5,6), c(7,8,9)))
|
4969c9481c1474d4df207612c7934c26acae80fb | c459dd32d88158cb064c3af2bc2ea8c7ab77c667 | /dimplot/plot_other_on_umap/plot_genecount_on_umap_by_aliquot_allcells.R | c490b2811845173b716a50ecbc3562e6bc857192 | [] | no_license | ding-lab/ccRCC_snRNA_analysis | d06b8af60717779671debe3632cad744467a9668 | ac852b3209d2479a199aa96eed3096db0b5c66f4 | refs/heads/master | 2023-06-21T15:57:54.088257 | 2023-06-09T20:41:56 | 2023-06-09T20:41:56 | 203,657,413 | 6 | 3 | null | null | null | null | UTF-8 | R | false | false | 3,157 | r | plot_genecount_on_umap_by_aliquot_allcells.R | # Yige Wu @WashU Apr 2020
# set up libraries and output directory -----------------------------------
## set working directory
dir_base = "~/Box/Ding_Lab/Projects_Current/RCC/ccRCC_snRNA/"
setwd(dir_base)
source("./ccRCC_snRNA_analysis/load_pkgs.R")
source("./ccRCC_snRNA_analysis/functions.R")
source("./ccRCC_snRNA_analysis/variables.R")
source("./ccRCC_snRNA_analysis/plotting.R")
## set run id
version_tmp <- 1
run_id <- paste0(format(Sys.Date(), "%Y%m%d") , ".v", version_tmp)
## set output directory
dir_out <- paste0(makeOutDir(), run_id, "/")
dir.create(dir_out)
# input dependencies ------------------------------------------------------
## input cell type per barcode table
barcode2celltype_df <- fread(input = "./Resources/Analysis_Results/annotate_barcode/map_celltype_to_all_cells/20200720.v1/30AliquotIntegration.Barcode2CellType.TumorManualCluster.20200720.v1.tsv", data.table = F)
## input UMAP info per barcode
umap_df <- fread(input = "./Resources/Analysis_Results/data_summary/fetch_data/fetch_data_by_individual_sample/20200717.v1/Barcode2MetaData.20200717.v1.tsv", data.table = F)
# make colors for the discrete ranges ----------------------------------
## make function
number2rangetext = function(x) {
if (x < 10000 & x >= 3000) {
range_low <- floor(x/1000)*1000
range_high <- ceiling((x+1)/1000)*1000
text_range <- paste0("[", range_low, ",", range_high, ")")
} else if (x >= 10000){
text_range <- ">=10000"
} else {
text_range <- "<3000"
}
return(text_range)
}
colors_numbercellrange_vec <- RColorBrewer::brewer.pal(n = 9, name = "PuBuGn")
names(colors_numbercellrange_vec) <- sapply(X = seq(from = 2001, to = 10001, by = 1000), FUN = number2rangetext)
# plot for cell group----------------------------------------------------------
for (id_aliquot_tmp in unique(umap_df$aliquot)) {
plotdata_df <- umap_df %>%
filter(aliquot == id_aliquot_tmp)
plotdata_df <- merge(plotdata_df,
barcode2celltype_df %>%
select(individual_barcode, Cell_group),
by.x = c("individual_barcode"), by.y = c("individual_barcode"), all.x = T)
plotdata_df$range_nCount_RNA <- sapply(X = plotdata_df$nCount_RNA, FUN = number2rangetext)
table(plotdata_df$range_nCount_RNA)
p <- ggplot()
p <- p + geom_point(data = plotdata_df,
mapping = aes(x = UMAP_1, y = UMAP_2, color = range_nCount_RNA),
alpha = 1, size = 0.05)
p <- p + scale_color_manual(values = colors_numbercellrange_vec)
p <- p + guides(colour = guide_legend(override.aes = list(size=5)))
p <- p + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))
p <- p + theme(axis.text.x=element_blank(),
axis.ticks.x=element_blank())
p <- p + theme(axis.text.y=element_blank(),
axis.ticks.y=element_blank())
p
file2write <- paste0(dir_out, id_aliquot_tmp, ".nCount_RNA", ".png")
png(filename = file2write, width = 1100, height = 800, res = 150)
print(p)
dev.off()
}
|
1d9d87f0012564acdc72362fe4d6e3a57c177e0b | 9a44a9d86a61a06b66e6bfaa0e6befde290a2b5b | /man/get_dropv6.Rd | 3d88fcc566e43a32515bbcfab591b58bffb3a476 | [] | no_license | hrbrmstr/hormel | 2c600937b093b06085c626810bb6e1f073a04afe | 7fc8b4212016346b3e385905c15035bed3c91674 | refs/heads/master | 2020-03-17T03:20:19.143680 | 2018-05-13T11:24:43 | 2018-05-13T11:24:43 | 133,230,730 | 2 | 1 | null | null | null | null | UTF-8 | R | false | true | 1,212 | rd | get_dropv6.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/drops.R
\name{get_dropv6}
\alias{get_dropv6}
\title{Spamhaus IPv6 DROP List (DROPv6)}
\usage{
get_dropv6()
}
\description{
Retrieves the Spamhaus IPv6 DROP List (DROPv6)
}
\details{
The DROPv6 list includes IPv6 ranges allocated to spammers or cyber criminals.
DROPv6 will only include IPv6 netblocks allocated directly by an established
Regional Internet Registry (RIR) or National Internet Registry (NIR) such as
ARIN, RIPE, AFRINIC, APNIC, LACNIC or KRNIC or direct RIR allocations.
}
\note{
This function is "memoised" because the DROP list changes quite slowly.
There is \emph{no need} to update cached data \strong{more than once per hour},
in fact once per day is more than enough in most cases. Automated downloads
must be at least one hour apart. Excessive downloads may result in your IP
being firewalled from the Spamhaus website.\cr\cr
If you are using this from
a long-running R session and need to fetch the list, use the \code{\link[=clear_drops]{clear_drops()}}
function to clear the cache of all "DROP" get functions.
}
\references{
\url{https://www.spamhaus.org/drop/}; \url{https://www.spamhaus.org/faq/section/}
}
|
3f42b2af7a46d582e884697ccbf64e3ca17cd39c | 2c9b3d4b67c31d3ab2696c9a0d516907c4639f29 | /man/policiez.Rd | 4674726e4b57638885e982b8f60ba9b4dfdfd8b8 | [] | no_license | ben519/claimz | 2a71e4eac9ee3a5c0fee73b437bfacb466f41d48 | 8100966be399b6f87aa640d43be9c3a3ec52ba9c | refs/heads/master | 2021-04-29T10:14:15.372935 | 2017-08-14T23:34:32 | 2017-08-14T23:34:32 | 77,875,533 | 1 | 0 | null | null | null | null | UTF-8 | R | false | true | 673 | rd | policiez.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{policiez}
\alias{policiez}
\title{Policies sample dataset}
\format{A data.table with 2 rows and 3 variables:
\describe{
\item{PolicyID}{Unique identifier}
\item{EffectiveDate}{Effective date}
\item{ExpirationDate}{Expiration date}
}}
\usage{
policiez
}
\description{
A dataset with sample policies
}
\details{
library(data.table)
policiez <- data.table::data.table(
PolicyID = c(1,2),
EffectiveDate = as.Date(c("2014-1-1", "2014-6-1")),
ExpirationDate = as.Date(c("2015-1-1", "2015-6-1"))
)
save(policiez, file="data/policiez.rda")
}
\keyword{datasets}
|
2d814a8482e58b0fcee5ae2b1c59c3cab5b58b03 | 7d976e0176aaee7a4ca089911e671baaf9597bd7 | /Terekhin_BI-18.r | 0e7cd6b701da326b6b93f5b1657d4aececa1df31 | [] | no_license | ironlocker/KT1 | a1508d8a505e1978aa9b28e2c374a2b4055c26e0 | 9fd4bbd210882b0ffb0cc58b4e4bb02c24870cb5 | refs/heads/main | 2023-09-05T14:59:50.203625 | 2021-11-12T13:34:55 | 2021-11-12T13:34:55 | 427,368,901 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 806 | r | Terekhin_BI-18.r | #Для начала, необходимо установить пакеты и подключить библиотеки
install.packages('ggplot2')
install.packages('tidyverse')
library(ggplot2)
library(tidyverse)
#Затем, подключить данные
table1 <- read.csv("RU_Electricity_Market_PZ_dayahead_price_volume.csv", header = TRUE, sep = ",")
data1 <- read.csv("112.csv", header = TRUE, sep = ",")
#Наименования
names(table1)
#Авторегрессия
set.seed(49)
y <- arima.sim(n = nrow(table1), table1)
plot(y)
#График
ggplot(data = table1)+
geom_point(alpha = 1/2, mapping = aes(x= timestep, y = price_eur, color = consumption_eur))
ggplot(data = table1)+
geom_point(alpha = 1/4, mapping = aes(x= consumption_eur, y = price_eur)) |
73789b4e0403a4cc0e57d4b9511aaf810c49edb7 | 6a6ca838a0b0ac552cfe7745af6946623a648c9e | /bootstrap_proof.R | 2de5a7ab237a86befff0ccf969d4b62914b1a12c | [] | no_license | myforkz/probability | dc7d6277263c68519a9837235b4bd6356c82db1e | c1e28df825076a7416dcbe3911f546bb0523331e | refs/heads/master | 2022-03-02T12:34:44.874788 | 2019-06-28T14:46:48 | 2019-06-28T14:46:48 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 8,341 | r | bootstrap_proof.R | ## Bootstrap Resampling ##
library(ggplot2)
library(latex2exp)
## Plot Theme ##
bootstrap_theme <- theme(
plot.margin = margin(t = 0.75, r = 0.75, b = 0.5, l = 0.75, unit = "cm"),
plot.title = element_text(size = 11, hjust = 0.5,
margin= margin(b = 0.5, unit = "cm")),
plot.subtitle = element_text(size = 10, hjust = 0.5,
margin= margin(b = 0.5, unit = "cm")),
plot.caption = element_text(size = 9, hjust = 1,
margin = margin(t = 0.6, unit = "cm")),
axis.text = element_text(size = 10),
axis.title.x = element_text(size = 13,
margin = margin(t = 0.4, unit = "cm")),
axis.title.y = element_text(size = 13,
margin = margin(r = 0.4, unit = "cm")),
text = element_text(family = "Gill Sans MT"),
plot.background = element_rect(fill = "#f5f5f2", color = NA),
legend.position = "none")
bootstrap_labels <- labs(
title = "What Proportion of Observations will Occur in a Given Bootstrap Sample?",
caption = "Graphic by Ben Andrew | @BenYAndrew")
val <- "$1 - \\,\\frac{1}{\\e}$"
## Probability Plot ##
n <- 1:55
prob_not_chosen <- (1 - (1/n))^n
prob_chosen <- 1 - prob_not_chosen
limit_data <- data.frame(x = n, y = prob_chosen)
limit_plot <-
ggplot(limit_data, aes(x = x, y = y)) +
geom_hline(yintercept = 0.632, linetype = "dashed", color = "black") +
geom_line(color = "#8A0057", lwd = 1) +
geom_point(color = "#8A0057", size = 1.5) +
scale_y_continuous(limits = c(0.56, 1)) +
scale_x_continuous(breaks = c(0, 10, 20, 30, 40, 50), limits = c(0, 60)) +
geom_rect(xmin = 42, xmax = 54, ymin = 0.55, ymax = 0.62,
linetype = 1, color = "black", fill = "grey") +
geom_segment(x = 59, xend = 59, y = 0.585, yend = 0.625,
arrow = arrow(type = "closed", angle = 30,
length = unit(0.05, "inches"))) +
geom_segment(x = 54, xend = 59, y = 0.585, yend = 0.585) +
annotate(geom = "text", label = TeX(val, output = "character"),
parse = TRUE, size = 2.8, x = 45, y = 0.585) +
annotate(geom = "text", label = " = 0.632", size = 2.8, x = 50, y = 0.585) +
xlab("Sample Size") +
ylab("Probability of Inclusion in Bootstrap Sample") +
labs(subtitle = "Theoretical Probability Solution") +
theme_classic() +
bootstrap_theme +
bootstrap_labels
## Sample Size Simulation Plot ##
set.seed(1991)
x <- 1:5000
simulation_data <- data.frame(sample_size = x,
lower_ci = numeric(length = length(x)),
estimate = numeric(length = length(x)),
upper_ci = numeric(length = length(x)))
for (i in x){
test_sample <- 1:i
test_prop <- numeric(length = 1000)
for (iter in 1:1000){
set.seed(11 + iter + i)
bs_sample <- sample(test_sample, size = length(test_sample),
replace = TRUE)
bs_prop <- length(unique(bs_sample)) / length(test_sample)
test_prop[iter] <- bs_prop
}
simulation_data[i, 2:4] <-
as.numeric(quantile(test_prop, probs = c(0.025, 0.5, 0.975),
type = 3))
}
simulation_plot <-
ggplot(simulation_data, aes(x = sample_size, y = estimate)) +
geom_ribbon(aes(ymin = lower_ci, ymax = upper_ci),
fill = "darkred", alpha = 0.65) +
geom_line(lwd = 1) +
annotate(geom = "text", label = "Bootstrap 95% CI",
fontface = "bold", x = 195, y = 0.5, size = 2.8, hjust = 0) +
geom_segment(x = 185, xend = 75, y = 0.5, yend = 0.55,
arrow = arrow(type = "closed", angle = 30,
length = unit(0.02, "inches"))) +
annotate(geom = "text", label = "Bootstrap Estimate",
fontface = "bold", x = 345, y = 0.71, size = 2.8, hjust = 0) +
geom_segment(x = 340, xend = 300, y = 0.7, yend = 0.64,
arrow = arrow(type = "closed", angle = 30,
length = unit(0.02, "inches"))) +
annotate(geom = "text", label = "Stablizes at 0.632",
fontface = "bold", x = 900, y = 0.57, size = 2.8, hjust = 1) +
geom_segment(x = 910, xend = 990, y = 0.57, yend = 0.625,
arrow = arrow(type = "closed", angle = 30,
length = unit(0.02, "inches"))) +
annotate(geom = "text",
label = "Higher probability and more\nvariability in small samples",
fontface = "bold", x = 100, y = 0.93, size = 2.8, hjust = 0) +
geom_segment(x = 100, xend = 25, y = 0.9, yend = 0.8,
arrow = arrow(type = "closed", angle = 30,
length = unit(0.02, "inches"))) +
scale_x_continuous(limits = c(0, 1000)) +
xlab("Sample Size") +
ylab("Proportion of Observations in Bootstrap Sample") +
labs(subtitle = "1,000 Bootstrap Samples for Datasets of Increasing Size (n = 1 to n = 1,000)") +
theme_classic() +
bootstrap_theme +
bootstrap_labels
## Distribution Plots ##
g <- 1:10000
j <- 50000
h <- numeric(length = j)
for (i in 1:j){
set.seed(1991+i)
bs_sample <- sample(g, size = length(g), replace = TRUE)
prop_sample <- length(unique(bs_sample)) / length(g)
h[i] <- prop_sample
}
distribution_data <- data.frame(g = g, h = h, k = "group")
histogram_plot <-
ggplot(distribution_data, aes(x = h)) +
geom_vline(xintercept = 0.632, linetype = "dashed", color = "black") +
geom_histogram(fill = "navyblue", color = "black", binwidth = 0.0005,
alpha = 0.75) +
scale_x_continuous(breaks = c(0.622, 0.627, 0.632, 0.637, 0.642)) +
scale_y_continuous(limits = c(0, 3600)) +
geom_rect(xmin = 0.637, xmax = 0.643, ymin = 3200, ymax = 3600,
linetype = 1, color = "black", fill = "grey") +
geom_segment(x = 0.637, xend = 0.6325, y = 3400, yend = 3400,
arrow = arrow(type = "closed", angle = 30,
length = unit(0.05, "inches"))) +
annotate(geom = "text", label = TeX(val, output = "character"),
parse = TRUE, size = 2.8, x = 0.6385, y = 3400, fontface = "bold") +
annotate(geom = "text", label = " = 0.632", size = 2.8, x = 0.641, y = 3400) +
xlab("Proportion of Observations in Bootstrap Sample") +
ylab("Frequency") +
theme_classic() +
bootstrap_theme +
labs(subtitle = "50,000 Bootstrap Samples of a Large Dataset (n = 10,000)") +
bootstrap_labels
violin_plot <-
ggplot(distribution_data, aes(x = k, y = h)) +
geom_violin(fill = "#74A600", color = "black", alpha = 0.85, width = 0.5) +
geom_hline(yintercept = 0.632, linetype = "dashed") +
geom_boxplot(width = 0.05, outlier.size = 0.7,
fill = "lightgrey", color = "black", lwd = 0.7) +
geom_rect(xmin = 0.55, xmax = 0.75, ymin = 0.626, ymax = 0.629,
linetype = 1, color = "black", fill = "grey") +
geom_segment(x = 0.65, xend = 0.65, y = 0.629, yend = 0.6315,
arrow = arrow(type = "closed", angle = 30,
length = unit(0.05, "inches"))) +
annotate(geom = "text", label = TeX(val, output = "character"),
parse = TRUE, size = 2.8, x = 0.6, y = 0.6275, fontface = "bold") +
annotate(geom = "text", label = " = 0.632", size = 2.8,
x = 0.68, y = 0.6275) +
scale_y_continuous(breaks = c(0.617, 0.622, 0.627, 0.632,
0.637, 0.642, 0.647)) +
ylab("Proportion of Observations in Boostrap Sample") +
xlab("") +
theme_classic() +
bootstrap_theme +
theme(
axis.ticks.x = element_blank(),
axis.title.x = element_blank(),
axis.text.x = element_blank()) +
labs(subtitle = "50,000 Bootstrap Samples of a Large Dataset (n = 10,000)") +
bootstrap_labels
ggsave("/Users/student/Desktop/bootstrap_1.jpeg", plot = limit_plot,
device = "jpeg", width = 6, height = 6, units = "in", dpi = 500)
ggsave("/Users/student/Desktop/bootstrap_2.jpeg", plot = histogram_plot,
device = "jpeg", width = 6, height = 6, units = "in", dpi = 500)
ggsave("/Users/student/Desktop/bootstrap_3.jpeg", plot = violin_plot,
device = "jpeg", width = 6, height = 6, units = "in", dpi = 500)
ggsave("/Users/student/Desktop/bootstrap_4.jpeg", plot = simulation_plot,
device = "jpeg", width = 6, height = 6, units = "in", dpi = 500)
|
e4facca2eca9332a7e444639497a9c71119b821e | a2b5f79a50b23e6a255a22aa8e4f5d4b730921ef | /Datasets/1stdataset_numbeo/numbeo.r | 14cdb4566313f851c18480efef6b089daab859ce | [] | no_license | Sushil8/Data_Warehousing_and_Business_Intelligence | a399c6b831297edc083eb98b33d5b9d51bda33cc | debbdc3fc66836c5d96c7e68bc7801140182a14d | refs/heads/master | 2020-03-31T04:12:55.668795 | 2018-10-07T01:42:27 | 2018-10-07T01:42:27 | 151,895,778 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 719 | r | numbeo.r | library(stringr)
library(rvest)
library(dplyr)
url <- "https://www.numbeo.com/cost-of-living/rankings.jsp"
page <- read_html(url) #Downloads the URLs webpage
table <- html_table(page, fill = TRUE)
typeof(table)
write.csv(table,"city.csv")
mydata <- read.csv(file = "city.csv", header = TRUE, sep = ",")
typeof(mydata)
mydata$X <- NULL
mydata$X1 <- NULL
mydata$X2 <- NULL
mydata$X1.1 <- NULL
mydata$X2.1 <- NULL
mydata$X3 <- NULL
mydata$Rank <- NULL
mydata$City <- gsub(",.*","", mydata$City, ignore.case = TRUE)
mydata$City <- gsub("\\(.*", "", mydata$City)
mydata$City <- gsub("[^a-z]", "" , mydata$City ,ignore.case = TRUE)
mydata <- mydata %>% distinct_("City", .keep_all = TRUE)
write.csv(mydata, "mydata.csv")
|
8b32e9bef051401c768dd0d0b76be9f4fc51a597 | c8c55951ba05801debd62eec39269a06aacf4a8c | /R/05_results.R | 6fd8f1c8fef394b722ce889258ec0774268c0f17 | [] | no_license | fjuniorr/ffeb-2015 | dc2aba254ec43703a78e70040adf816d9978b966 | 03ae2820da04086273d4c29608d581dc8234e638 | refs/heads/master | 2020-05-21T00:27:33.857419 | 2015-09-19T13:03:00 | 2015-09-19T13:03:00 | 35,390,229 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,153 | r | 05_results.R | forecast_plot <- function(state) {
ts.plot(rcl[[state]],
ts(naive_forecast[naive_forecast$ESTADO == state, "PREVISTO"], start = c(2013, 5), frequency = 12),
ts(rw_forecast[naive_forecast$ESTADO == state, "PREVISTO"], start = c(2013, 5), frequency = 12),
ts(ets_forecast[naive_forecast$ESTADO == state, "PREVISTO"], start = c(2013, 5), frequency = 12),
ts(arima_forecast[naive_forecast$ESTADO == state, "PREVISTO"], start = c(2013, 5), frequency = 12),
ts(star_forecast[naive_forecast$ESTADO == state, "PREVISTO"], start = c(2013, 5), frequency = 12),
gpars = list(
col = c("black", "red", "green", "blue", "pink", "yellow"),
lty = c(1, 2, 2, 2, 2, 2)))
legend("bottomright", # places a legend at the appropriate place
c("RCL","NAIVE","RW","ETS","ARIMA","STAR"), # puts text in the legend
lty=c(1, 2, 2, 2, 2, 2), # gives the legend appropriate symbols (lines)
lwd=c(2.5,2.5,2.5,2.5,2.5,2.5),col=c("black","red","green","blue","pink","yellow")) # gives the legend lines the correct color and width
}
|
5d5469d1d0538f57ed36850f4582b99170e12ee3 | 740af1715d12e3cef5443048b647e43c70aac7ed | /20210513/quiz.R | 2a992aedc78a3b395f50f28cf13c33ea69e24e2f | [] | no_license | jaemoonnlee/repo_r | b423e52b989a6119e4e4f8426d537c54738bc420 | 817600af338c1d5f41f52a516d429d193b639444 | refs/heads/main | 2023-07-02T17:12:59.027003 | 2021-07-28T07:00:10 | 2021-07-28T07:00:10 | 390,246,188 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 315 | r | quiz.R | # 뉴욕 대기오염 dataset 사용
# airquality
# 1. 특정 달의 정보를 추출(5 ~ 9)
# 2. x변수, y변수를 사용하여 상관관계 분석
# - 산점도, 상관계수, 결측치 제거
# 3. 변수 4개를 사용하여 상관분석
# - 산점도 행렬
# - R함수, ggplot2, google chart
|
3dbfa91d26c7a116d3268b7b620d83a31204e997 | 2a62f91ee17ef65dc874ff49b23cbdcf650f4474 | /gen_diffndiff_data.R | 24794379747876710de3acb72a9d16221e0347a5 | [] | no_license | DS4PS/pe4ps | cbc445bb6aa6fc9537d8885eea14c83fd570475d | cda4104b98273f87905b3cf049b98054e1a361c3 | refs/heads/master | 2023-07-07T08:58:51.029991 | 2023-06-30T05:33:05 | 2023-06-30T05:33:05 | 193,190,777 | 3 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,925 | r | gen_diffndiff_data.R |
# correlation of A and rA+B when both are rnorm() is m below
#
# see: https://math.stackexchange.com/questions/2865621/correlation-between-two-linear-combinations-of-random-variables
rn1 <- rnorm(100000)
rn2 <- rnorm(100000)
rt <- 0.3 # correlation across time
m <- rt / sqrt( 1 - rt^2 )
rn3 <- m*rn1 + rn2
cor( rn1, rn3 )
for( i in seq(0,0.95,0.05) )
{
print(i)
rt <- i
m <- rt / sqrt( 1 - rt^2 )
rn3 <- m*rn1 + rn2
print( cor( rn1, rn3 ) )
}
# group means:
b0 <- 10 # c1
b1 <- 10 # diff between c1 and t1
b2 <- 20 # diff between c1 and c2
b3 <- 15 # treat effect
# error terms for each group, all standard normals
e0 <- rnorm(10000)
e1 <- rnorm(10000)
e2 <- rnorm(10000)
e3 <- rnorm(10000)
# within-group across-time correlation coefficient
rt <- 0.8
m <- rt / sqrt( 1 - rt^2 )
# truncate these outliers ???
sum( e1 < -3.5 )
sum( e1 > 3.5 )
plot( e1, pch=19, cex=ifelse( abs(e1)>3.5, 2, 0.3), bty="n" )
abline( h=c(3.5,-3.5), lty=2, col="red" )
e1[ e1 > 3.5 ] <- 3.5
e1[ e1 < -3.5 ] <- 3.5
e2[ e2 > 3.5 ] <- 3.5
e2[ e2 < -3.5 ] <- 3.5
#### DEFINE ERROR STRUCTURE FOR POST-TREAT PERIOD
e2.1 <- m*e1 + e2
summary(e1)
summary(e2.1)
sd(e1)
sd(e2.1)
cor(e1,e2)
cor(e1,e2.1)
# maintains std.norm properties and across-time correlation
e2.s <- as.numeric( scale( e2.1 ) )
mean(e2.s)
sd(e2.s)
cor(e1,e2.s)
### GEN DATA PROCESS
c1 <- b0 + e0
sd(c1)
t1 <- b0 + b1 + e1
sd( t1 )
e2.s <- as.numeric( scale( m*e0 + e2 ) )
c2 <- b0 + b2 + e2.s
mean(c2)
sd(c1)
sd(c2)
cor( c1, c2 )
plot( c1, c2, pch=19, col=gray(0.5,0.5), bty="n" )
e3.s <- as.numeric( scale( m*e1 + e3 ) )
t2 <- b0 + b1 + b2 + b3 + e3.s
mean(t2)
sd(t2)
cor( t1, t2 )
plot( t1, t2, pch=19, col=gray(0.5,0.5), bty="n" )
p1 <- c(c1,t1)
p2 <- c(c2,t2)
cor( p1, p2 )
plot( p1, p2, pch=19, col=gray(0.5,0.5), bty="n" )
y <- c(c1,t1,c2,t2)
d.t <- c( rep( c(0,1,0,1), each=10000) )
d.p <- c( rep( c(0,0,1,1), each=10000) )
d.tp <- d.t * d.p
sd(y) # will not be sd(e) because this measures across-group variance
mod <- lm( y ~ d.t + d.p + d.tp )
summary( mod )
# note we can parameterize the model using natural units and the residual standard error
# (the standard deviation of the e's in our model)
# or using a standard normal then scaling the residuals (not the Y's).
#
# If it works our ceiling and floor Y's should
# approximately match the actual data min.y and max.y ?
#
# See: https://feliperego.github.io/blog/2015/10/23/Interpreting-Model-Output-In-R
# for an explanation of residual standard error.
# rescale y after data generation ?
# or rescale( e1, to( -3.5*residual_standard_error, 3.5*residual_standard_error ) )
# repeat for all e's ?
# assumes max and min of all e's will be close to 3.5, valid for large samples
# but maybe use actual min(e) and max(e) ? |
2abedeb1755e6ebf8d07e787732e458ad768077b | 1f5e2b2a709f9e09830f7434cf6a4975caf0f7f5 | /man/dot-to_latex_style.Rd | 1fe524a930918d8aeff013e74609a2fb32e5956d | [] | no_license | cran/sfcr | 4ee3d84e58a1a50e8bbaec2a8bd6d8bffb7f103d | c22e1e4211b33d04b2f73c49f5ac0b1524e3f66f | refs/heads/master | 2023-08-22T09:19:13.415979 | 2021-10-11T07:00:02 | 2021-10-11T07:00:02 | 334,215,974 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 471 | rd | dot-to_latex_style.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sfcr_matrix_display.R
\name{.to_latex_style}
\alias{.to_latex_style}
\title{Transform entries into latex style}
\usage{
.to_latex_style(matrix, nms)
}
\arguments{
\item{matrix}{a balance-sheet or transactions-flow matrix}
\item{nms}{Cleaned names with \code{.find_names()}}
}
\description{
Transform entries into latex style
}
\author{
João Macalós
}
\keyword{internal}
|
0d03de0a11d33c87b7c60a2ddd50067763633066 | d6ea1712e992b089a6d2e0713d1122008ce17fb5 | /src/main/resources/docs/tests/undesirable_operator_linter.R | 5900340cc00308383325d1763a69285fd758baaa | [
"Apache-2.0"
] | permissive | archived-codacy/codacy-lintr | 93bf404b44925b2d84d2f89a39cc5144d4cae929 | 07f854211c0a7ab4d34cfd8cec49092e149ee04b | refs/heads/master | 2023-06-23T03:05:31.047537 | 2020-10-28T17:41:43 | 2020-10-28T17:41:43 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 99 | r | undesirable_operator_linter.R | ##Pattern: undesirable_operator_linter
# Pass
x <- 7
##Warn: undesirable_operator_linter
x <<- 7
|
41a34081886c414bcb93ce6551e2723d754c86b6 | e209592a68ed776f5db0431fa7a4db2acc1a1e76 | /stretch-mediatedskinexpansion/ATAC-seq/rcode.r | f506ad155cc4f97ac97e259e58fb7193c7687228 | [] | no_license | liuzhe93/qualifyreport | 59535005f1b1a51de09a46741ca27811c81b3a5a | 417d622f2e440d8901518da52442c80d3552b408 | refs/heads/main | 2023-06-05T19:58:03.059705 | 2021-05-24T12:30:55 | 2021-05-24T12:30:55 | 370,338,126 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 11,172 | r | rcode.r | library("knitr")
library("rmdformats")
library("dplyr")
library("DT")
library("tidyr")
library("ggplot2")
library("magrittr")
library("Rsamtools")
library("GenomicAlignments")
library("TxDb.Hsapiens.UCSC.hg19.knownGene")
library("TxDb.Mmusculus.UCSC.mm9.knownGene")
library("soGGi")
library("rtracklayer")
library("ChIPQC")
library("ChIPseeker")
library("rGREAT")
library("limma")
library("DESeq2")
library("tracktables")
library("clusterProfiler")
library("org.Mm.eg.db")
library("MotifDb")
library("Biostrings")
library("BSgenome.Hsapiens.UCSC.hg19")
library("BSgenome.Mmusculus.UCSC.mm9")
# # Finally we need development version of soGGi (named here 1.10.4) # not
# version on Bioconductor (1.10.0)
# devtools::install_github('ThomasCarroll/soGGi')
library(Rsubread)
sortedBAM_ctl<-"Ctl_S18.last.bam"
sortedBAM_exp<-"Exp-D2.last.bam"
pmapped_ctl <- propmapped(sortedBAM_ctl)
pmapped_exp <- propmapped(sortedBAM_exp)
save(pmapped_ctl,file="Rdata/pmapped_ctl.RData")
save(pmapped_exp,file="Rdata/pmapped_exp.RData")
library(Rsamtools)
library(ggplot2)
library(magrittr)
pdf("figures/Distributionofmappedreads_ctl.pdf")
idxstatsBam(sortedBAM_ctl) %>% ggplot(aes(seqnames, mapped, fill = seqnames)) +
geom_bar(stat = "identity") + coord_flip()
dev.off()
pdf("figures/Distributionofmappedreads_exp.pdf")
idxstatsBam(sortedBAM_exp) %>% ggplot(aes(seqnames, mapped, fill = seqnames)) +
geom_bar(stat = "identity") + coord_flip()
dev.off()
library(GenomicAlignments)
atacReads_ctl <- readGAlignmentPairs(sortedBAM_ctl, param = ScanBamParam(mapqFilter = 1,
flag = scanBamFlag(isPaired = TRUE, isProperPair = TRUE), what = c("qname",
"mapq", "isize")))
length(atacReads_ctl)
atacReads_ctl
atacReads_exp <- readGAlignmentPairs(sortedBAM_exp, param = ScanBamParam(mapqFilter = 1,
flag = scanBamFlag(isPaired = TRUE, isProperPair = TRUE), what = c("qname",
"mapq", "isize")))
length(atacReads_exp)
atacReads_exp
atacReads_ctl_read1 <- GenomicAlignments::first(atacReads_ctl)
insertSizes <- abs(elementMetadata(atacReads_ctl_read1)$isize)
head(insertSizes)
library(magrittr)
library(dplyr)
library(ggplot2)
pdf("figures/Plottingtinsertsizes_ctl.pdf")
fragLenPlot <- table(insertSizes) %>% data.frame %>% rename(InsertSize = insertSizes,
Count = Freq) %>% mutate(InsertSize = as.numeric(as.vector(InsertSize)),
Count = as.numeric(as.vector(Count))) %>% ggplot(aes(x = InsertSize, y = Count)) +
geom_line()
fragLenPlot + theme_bw()
dev.off()
pdf("figures/PlottingtinsertsizesYlog2_ctl.pdf")
fragLenPlot + scale_y_continuous(trans = "log2") + theme_bw()
dev.off()
pdf("figures/Greenleaf_ctl.pdf")
fragLenPlot + geom_vline(xintercept = c(180, 247), colour = "red") + geom_vline(xintercept = c(315,
437), colour = "darkblue") + geom_vline(xintercept = c(100), colour = "darkgreen") +
theme_bw()
dev.off()
pdf("figures/GreenleafYlog2_ctl.pdf")
fragLenPlot + scale_y_continuous(trans = "log2") + geom_vline(xintercept = c(180,
247), colour = "red") + geom_vline(xintercept = c(315, 437), colour = "darkblue") +
geom_vline(xintercept = c(100), colour = "darkgreen") + theme_bw()
dev.off()
atacReads_exp_read1 <- GenomicAlignments::first(atacReads_exp)
insertSizes <- abs(elementMetadata(atacReads_exp_read1)$isize)
head(insertSizes)
pdf("figures/Plottingtinsertsizes_exp.pdf")
fragLenPlot <- table(insertSizes) %>% data.frame %>% rename(InsertSize = insertSizes,
Count = Freq) %>% mutate(InsertSize = as.numeric(as.vector(InsertSize)),
Count = as.numeric(as.vector(Count))) %>% ggplot(aes(x = InsertSize, y = Count)) +
geom_line()
fragLenPlot + theme_bw()
dev.off()
pdf("figures/PlottingtinsertsizesYlog2_exp.pdf")
fragLenPlot + scale_y_continuous(trans = "log2") + theme_bw()
dev.off()
pdf("figures/Greenleaf_exp.pdf")
fragLenPlot + geom_vline(xintercept = c(180, 247), colour = "red") + geom_vline(xintercept = c(315,
437), colour = "darkblue") + geom_vline(xintercept = c(100), colour = "darkgreen") +
theme_bw()
dev.off()
pdf("figures/GreenleafYlog2_exp.pdf")
fragLenPlot + scale_y_continuous(trans = "log2") + geom_vline(xintercept = c(180,
247), colour = "red") + geom_vline(xintercept = c(315, 437), colour = "darkblue") +
geom_vline(xintercept = c(100), colour = "darkgreen") + theme_bw()
dev.off()
library("TxDb.Mmusculus.UCSC.mm9.knownGene")
TSSs <- resize(genes(TxDb.Mmusculus.UCSC.mm9.knownGene), fix = "start", 1)
TSSs
library(soGGi)
#Plotting ATAC-seq signal of TSSs (Creating open, mono- and di-nucleosome signal profiles)
# Nucleosome free
nucFree_ctl <- regionPlot(bamFile = sortedBAM_ctl, testRanges = TSSs, style = "point",
format = "bam", paired = TRUE, minFragmentLength = 0, maxFragmentLength = 100,
forceFragment = 50)
# Mononucleosome
monoNuc_ctl <- regionPlot(bamFile = sortedBAM_ctl, testRanges = TSSs, style = "point",
format = "bam", paired = TRUE, minFragmentLength = 180, maxFragmentLength = 240,
forceFragment = 80)
# Dinucleosome
diNuc_ctl <- regionPlot(bamFile = sortedBAM_ctl, testRanges = TSSs, style = "point",
format = "bam", paired = TRUE, minFragmentLength = 315, maxFragmentLength = 437,
forceFragment = 160)
save(monoNuc_ctl,nucFree_ctl,diNuc_ctl,file='Rdata/soGGiResults_ctl.RData')
#Plotting ATAC-seq signal of TSSs (Creating open, mono- and di-nucleosome signal profiles)
# Nucleosome free
nucFree_exp <- regionPlot(bamFile = sortedBAM_exp, testRanges = TSSs, style = "point",
format = "bam", paired = TRUE, minFragmentLength = 0, maxFragmentLength = 100,
forceFragment = 50)
# Mononucleosome
monoNuc_exp <- regionPlot(bamFile = sortedBAM_exp, testRanges = TSSs, style = "point",
format = "bam", paired = TRUE, minFragmentLength = 180, maxFragmentLength = 240,
forceFragment = 80)
# Dinucleosome
diNuc_exp <- regionPlot(bamFile = sortedBAM_exp, testRanges = TSSs, style = "point",
format = "bam", paired = TRUE, minFragmentLength = 315, maxFragmentLength = 437,
forceFragment = 160)
save(monoNuc_exp,nucFree_exp,diNuc_exp,file='Rdata/soGGiResults_exp.RData')
library(soGGi)
load(file = "Rdata/soGGiResults_ctl.RData")
#Plotting ATAC-seq signal of TSSs (Plotting open, mono- and di-nucleosome signal profiles)
pdf("figures/PlottingATAC-seqsignalofTSSs_nucFree_ctl.pdf")
plotRegion(nucFree_ctl, outliers = 0.01)
dev.off()
pdf("figures/PlottingATAC-seqsignalofTSSs_monoNuc_ctl.pdf")
plotRegion(monoNuc_ctl, outliers = 0.01)
dev.off()
pdf("figures/PlottingATAC-seqsignalofTSSs_diNuc_ctl.pdf")
plotRegion(diNuc_ctl, outliers = 0.01)
dev.off()
load(file = "Rdata/soGGiResults_exp.RData")
#Plotting ATAC-seq signal of TSSs (Plotting open, mono- and di-nucleosome signal profiles)
pdf("figures/PlottingATAC-seqsignalofTSSs_nucFree_exp.pdf")
plotRegion(nucFree_exp, outliers = 0.01)
dev.off()
pdf("figures/PlottingATAC-seqsignalofTSSs_monoNuc_exp.pdf")
plotRegion(monoNuc_exp, outliers = 0.01)
dev.off()
pdf("figures/PlottingATAC-seqsignalofTSSs_diNuc_exp.pdf")
plotRegion(diNuc_exp, outliers = 0.01)
dev.off()
insertSizes <- abs(elementMetadata(atacReads_ctl_read1)$isize)
atacReads_Open_ctl <- atacReads_ctl[insertSizes < 100, ]
atacReads_MonoNuc_ctl <- atacReads_ctl[insertSizes > 180 & insertSizes < 240, ]
atacReads_diNuc_ctl <- atacReads_ctl[insertSizes > 315 & insertSizes < 437, ]
openRegionBam_ctl <- gsub("\\.bam", "_openRegions\\.bam", sortedBAM_ctl)
monoNucBam_ctl <- gsub("\\.bam", "_monoNuc\\.bam", sortedBAM_ctl)
diNucBam_ctl <- gsub("\\.bam", "_diNuc\\.bam", sortedBAM_ctl)
export(atacReads_Open_ctl, openRegionBam_ctl, format = "bam")
export(atacReads_MonoNuc_ctl, monoNucBam_ctl, format = "bam")
# export(atacReads_Open_ctl,diNucBam_ctl,format = 'bam')
openRegionBigWig_ctl <- gsub("\\.bam", "_openRegions\\.bw", sortedBAM_ctl)
openRegionRPMBigWig_ctl <- gsub("\\.bam", "_openRegionsRPM\\.bw", sortedBAM_ctl)
atacFragments_Open_ctl <- granges(atacReads_Open_ctl)
export.bw(coverage(atacFragments_Open_ctl), openRegionBigWig_ctl)
insertSizes <- abs(elementMetadata(atacReads_exp_read1)$isize)
atacReads_Open_exp <- atacReads_exp[insertSizes < 100, ]
atacReads_MonoNuc_exp <- atacReads_exp[insertSizes > 180 & insertSizes < 240, ]
atacReads_diNuc_exp <- atacReads_exp[insertSizes > 315 & insertSizes < 437, ]
openRegionBam_exp <- gsub("\\.bam", "_openRegions\\.bam", sortedBAM_exp)
monoNucBam_exp <- gsub("\\.bam", "_monoNuc\\.bam", sortedBAM_exp)
diNucBam_exp <- gsub("\\.bam", "_diNuc\\.bam", sortedBAM_exp)
export(atacReads_Open_exp, openRegionBam_exp, format = "bam")
export(atacReads_MonoNuc_exp, monoNucBam_exp, format = "bam")
# export(atacReads_Open_exp,diNucBam_exp,format = 'bam')
openRegionBigWig_exp <- gsub("\\.bam", "_openRegions\\.bw", sortedBAM_exp)
openRegionRPMBigWig_exp <- gsub("\\.bam", "_openRegionsRPM\\.bw", sortedBAM_exp)
atacFragments_Open_exp <- granges(atacReads_Open_exp)
export.bw(coverage(atacFragments_Open_exp), openRegionBigWig_exp)
library(ChIPQC)
library(rtracklayer)
library(DT)
library(dplyr)
library(tidyr)
blkList <- import.bed("ATAC_blacklists/mm9-blacklist.bed")
openRegionPeaks <- "peakcalling/ATAC_openRegions_peaks.narrowPeak"
qcRes <- ChIPQCsample("Exp-D2.last_openRegions.bam",
peaks = openRegionPeaks, annotation = "mm9",
verboseT = FALSE)
QCmetrics(qcRes) %>% t %>% data.frame %>% dplyr:::select(Reads, starts_with(c("Filt")),
starts_with(c("RiP")), starts_with(c("RiBL"))) %>% datatable(rownames = NULL)
flagtagcounts(qcRes) %>% t %>% data.frame %>% mutate(Dup_Percent = (DuplicateByChIPQC/Mapped) *
100) %>% dplyr:::select(Mapped, Dup_Percent) %>% datatable(rownames = NULL)
MacsCalls_chr20 <- granges(qcRes[seqnames(qcRes) %in% "chr20"])
data.frame(Blacklisted = sum(MacsCalls_chr20 %over% blkList), Not_Blacklisted = sum(!MacsCalls_chr20 %over%
blkList))
MacsCalls_chr20_filtered <- MacsCalls_chr20[!MacsCalls_chr20 %over% blkList]
library(ChIPseeker)
MacsCalls_chr20_filteredAnno <- annotatePeak(MacsCalls_chr20_filtered, TxDb = TxDb.Hsapiens.UCSC.hg19.knownGene)
MacsCalls_chr20_filteredAnno
plotAnnoPie(MacsCalls_chr20_filteredAnno)
plotAnnoBar(MacsCalls_chr20_filteredAnno)
upsetplot(MacsCalls_chr20_filteredAnno)
MacsGranges_Anno <- as.GRanges(MacsCalls_chr20_filteredAnno)
TSS_MacsGranges_Anno <- MacsGranges_Anno[abs(MacsGranges_Anno$distanceToTSS) <
500]
TSS_MacsGranges_Anno
library(rGREAT)
seqlevelsStyle(MacsCalls_chr20_filtered) <- "UCSC"
great_Job <- submitGreatJob(MacsCalls_chr20_filtered, species = "hg19")
availableCategories(great_Job)
library(ATACseqQC)
bamfile <- "Ctl_S18.last.bam"
bamfile.labels <- gsub(".bam", "", basename(bamfile))
## generate fragement size distribution
fragSize <- fragSizeDist(bamfile, bamfile.labels)
## shift the coordinates of 5'ends of alignments in the bam file
library(BSgenome.Hsapiens.UCSC.hg19)
Ctl_S18 <- readBamFile(bamfile, asMates=TRUE)
Ctl_S181 <- shiftGAlignmentsList(Ctl_S18)
shiftedBamfile <- file.path(outPath, "shifted.bam")
export(Ctl_S181, shiftedBamfile)
|
ad2d497c187333c08d1c44d42cdb848521755e75 | 7032674deef19f24379711807c9f5e9b12bb4901 | /R/listTargets.R | f886f0c39d1b00969c8924b2e7bbc5325abc372a | [] | no_license | AEBilgrau/DLBCLdata | a325a7981822e8b9de6bab5b9bd34bbef232b3d9 | aa0c4169ba80c7242d81b4cd5cab9817f844de22 | refs/heads/master | 2020-05-29T20:51:19.117652 | 2016-04-06T21:05:33 | 2016-04-06T21:05:33 | 26,138,981 | 5 | 1 | null | null | null | null | UTF-8 | R | false | false | 897 | r | listTargets.R | #' List available targets
#'
#' This function lists available targets for a given \code{cdf} argument.
#' @param cdf A character. Either \code{"affy"} or \code{"brainarray"}.
#' @param version A character giving the brainarray version.
#' See \code{listVersions()}. Ignored if \code{cdf == "affy"}.
#' @return A character vector of the available targets.
#' @examples
#' listTargets("affy")
#' listTargets("brainarray", version = "18.0.0")
#' listTargets("brainarray", version = "17.1.0")
#' listTargets("brainarray", version = "15.0.0")
#' @export
listTargets <- function(cdf, version = getLatestVersion()) {
if (cdf == "affy") {
message("Listing 'affy' targets is not fully implemented yet!")
return(getAffyTargets())
} else if (cdf == "brainarray") {
return(getBrainarrayTargets(version))
} else {
stop("The argument cdf must equal either 'affy' or 'brainrray'.")
}
}
|
419e7eaa6abd96f98f89c6b4c7fd7f8e1a59a88f | 8fb4331790fafde48963dc26a25a589d74b2158d | /man/ivlev_forage.Rd | da60c343e49ed6b30b91ada8d17169319fc7aff8 | [] | no_license | cran/electivity | cf72e93fb337ad503674f6905df2bdf27372b699 | 7b29b57f0a1b7b73e936f89e3aa435eeac2d0320 | refs/heads/master | 2020-12-21T22:49:29.165539 | 2019-08-20T13:50:05 | 2019-08-20T13:50:05 | 236,590,986 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 701 | rd | ivlev_forage.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/exported_funs.R
\name{ivlev_forage}
\alias{ivlev_forage}
\title{Ivlev's forage ratio, E'}
\usage{
ivlev_forage(r, p, log10 = FALSE)
}
\arguments{
\item{r}{(Numeric) Resource utilisation.}
\item{p}{(Numeric) Resource availability.}
\item{log10}{(Logical) If \code{TRUE}, transform the value with \code{log10()}.}
}
\value{
A numeric vector.
}
\description{
Bounded between +0.1 (avoidance), +1.0 (random feeding), and infinity (preference).
}
\examples{
data(moth_distrib)
ivlev_forage(moth_distrib$r, moth_distrib$p, log10 = FALSE)
ivlev_forage(moth_distrib$r, moth_distrib$p, log10 = TRUE)
}
|
feb73417ebd409db4a0ade2c41497013ee3b7200 | 9aafde089eb3d8bba05aec912e61fbd9fb84bd49 | /codeml_files/newick_trees_processed/847_0/rinput.R | b53da7c1f7b74b83f90b85b590af7f1458ae7a5e | [] | no_license | DaniBoo/cyanobacteria_project | 6a816bb0ccf285842b61bfd3612c176f5877a1fb | be08ff723284b0c38f9c758d3e250c664bbfbf3b | refs/heads/master | 2021-01-25T05:28:00.686474 | 2013-03-23T15:09:39 | 2013-03-23T15:09:39 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 133 | r | rinput.R | library(ape)
testtree <- read.tree("847_0.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="847_0_unrooted.txt") |
b3d3ce09ee1c630a42fa4917a341338d4b82c752 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/sparklyr.nested/examples/sdf_schema_json.Rd.R | 62ed144209a1b462b3b785122a21bedb77505439 | [] | no_license | surayaaramli/typeRrh | d257ac8905c49123f4ccd4e377ee3dfc84d1636c | 66e6996f31961bc8b9aafe1a6a6098327b66bf71 | refs/heads/master | 2023-05-05T04:05:31.617869 | 2019-04-25T22:10:06 | 2019-04-25T22:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,639 | r | sdf_schema_json.Rd.R | library(sparklyr.nested)
### Name: sdf_schema_json
### Title: Work with the schema
### Aliases: sdf_schema_json sdf_schema_viewer
### ** Examples
## Not run:
##D library(testthat)
##D library(jsonlite)
##D library(sparklyr)
##D library(sparklyr.nested)
##D sample_json <- paste0(
##D '{"aircraft_id":["string"],"phase_sequence":["string"],"phases (array)":{"start_point (struct)":',
##D '{"segment_phase":["string"],"agl":["double"],"elevation":["double"],"time":["long"],',
##D '"latitude":["double"],"longitude":["double"],"altitude":["double"],"course":["double"],',
##D '"speed":["double"],"source_point_keys (array)":["[string]"],"primary_key":["string"]},',
##D '"end_point (struct)":{"segment_phase":["string"],"agl":["double"],"elevation":["double"],',
##D '"time":["long"],"latitude":["double"],"longitude":["double"],"altitude":["double"],',
##D '"course":["double"],"speed":["double"],"source_point_keys (array)":["[string]"],',
##D '"primary_key":["string"]},"phase":["string"],"primary_key":["string"]},"primary_key":["string"]}'
##D )
##D
##D with_mock(
##D # I am mocking functions so that the example works without a real spark connection
##D spark_read_parquet = function(x, ...){return("this is a spark dataframe")},
##D sdf_schema_json = function(x, ...){return(fromJSON(sample_json))},
##D spark_connect = function(...){return("this is a spark connection")},
##D
##D # the meat of the example is here
##D sc <- spark_connect(),
##D spark_data <- spark_read_parquet(sc, path="path/to/data/*.parquet", name="some_name"),
##D sdf_schema_viewer(spark_data)
##D )
## End(Not run)
|
ad08fefb113dd0bc806b4e9d7539bd88bc33e6f4 | 47dbaf401b3653b17b4003d1e1ea1b6c3289e146 | /regression-models/poisson-regression/poisson-regression-nimble.R | 4eddb61f2f1ad4c24821e635ea53361a2aca2e96 | [] | no_license | dkahle/Bayes-Computational-Methods | a88a3dae8a4b824f515ad357a24eacb7b549da9f | 181bcbbfb3052361dce6af0a40469ebd3601f764 | refs/heads/master | 2023-04-21T00:48:23.463952 | 2021-05-07T18:00:39 | 2021-05-07T18:00:39 | 197,799,614 | 2 | 3 | null | 2019-07-19T15:33:18 | 2019-07-19T15:33:18 | null | UTF-8 | R | false | false | 1,945 | r | poisson-regression-nimble.R | ## load required packages and set basic options
################################################################################
library("tidyverse"); theme_set(theme_minimal())
library("parallel"); options(mc.cores = detectCores())
library("nimble")
library("bench")
## generate/specify data
################################################################################
n <- 20L # sample size
alpha <- 2 # intercept
beta <- 2 # single coefficient
set.seed(1)
(x <- runif(n, 0, 10)) # observed x values
lambda <- alpha + beta * x
(y <- rpois(n,lambda))
nimble_data <- list(
"y" = y,
"x" = x
)
nimble_constants <- list(
"n" = n
)
## specify jags model
################################################################################
nimble_model <- nimbleCode({
for (i in 1:n) {
log(lambda[i]) <- alpha + beta * x[i]
y[i] ~ dpois(lambda[i])
}
alpha ~ dnorm(0, 1 / (100 ^ 2))
beta ~ dnorm(0, 1 / (100 ^ 2))
})
nimble_monitor <- c("alpha", "beta")
## configure model settings
################################################################################
n_chains <- 4L
n_iter <- 1e4L
n_warmup <- 1e3L
nimble_inits <- list(
"alpha" = rnorm(1,0,(1 / 1000^2)),
"beta" = rnorm(1,0,(1 / 1000^2))
)
## fit model
################################################################################
source(here("currently-benchmarking.R"))
if (!currently_benchmarking()) {
nimble_fit <- nimbleMCMC(
"code" = nimble_model, "data" = nimble_data, "constants" = nimble_constants,
"inits" = nimble_inits, "monitors" = nimble_monitor, "nchains" = n_chains,
"niter" = n_iter, "nburnin" = n_warmup, "summary" = TRUE
)
## assess fit
################################################################################
nimble_fit$summary$all.chains
## assess convergence issues
###################################################################################
}
|
51d27250fd639a7232976cbfd94fbf4d03e541b0 | b7aa8147a600210be44a6320c70dfaab4e6d1f56 | /R/optimNLOPTR.R | 5ee9fb33ff3850a8863fe5d910c36e0882467f52 | [] | no_license | bartzbeielstein/SPOT | f60e1be5d264780d0a7092798ec37388834c3e00 | f55efb251dfb51e4393c166443193b7ef44e1350 | refs/heads/master | 2021-08-07T03:38:45.031674 | 2020-06-09T14:04:54 | 2020-06-09T14:04:54 | 187,638,021 | 3 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,199 | r | optimNLOPTR.R |
###################################################################################################
#' Minimization by NLOPT
#'
#' This is a wrapper that employs the \code{nloptr} function from the package of the same name.
#' The \code{nloptr} function itself is an interface to the \code{nlopt} library, which contains a wide selection
#' of different optimization algorithms.
#'
#' @param x optional matrix of points to be included in the evaluation (only first row will be used)
#' @param fun objective function, which receives a matrix x and returns observations y
#' @param lower boundary of the search space
#' @param upper boundary of the search space
#' @param control named list, with the options for \code{nloptr}. These
#' will be passed to \code{nloptr} as arguments. In addition, the following
#' parameter can be used to set the function evaluation budget:
#' \describe{
#' \item{\code{funEvals}}{Budget, number of function evaluations allowed. Default: 100.}
#' }
#' @param ... passed to \code{fun}
#'
#' Note that the arguments
#' \code{x}, \code{fun}, \code{lower} and \code{upper}
#' will be mapped to the corresponding arguments of \code{nloptr}:
#' \code{x0}, \code{eval_f}, \code{lb} and \code{ub}.
#'
#' @return list, with elements
#' \describe{
#' \item{\code{x}}{archive of evaluated solutions}
#' \item{\code{y}}{archive of observations}
#' \item{\code{xbest}}{best solution}
#' \item{\code{ybest}}{best observation}
#' \item{\code{count}}{number of evaluations of \code{fun}}
#' \item{\code{message}}{success message}
#' }
#'
#' @examples
#'\dontrun{
#' ##simple example:
#' res <- optimNLOPTR(,fun = funSphere,lower = c(-10,-20),upper=c(20,8))
#' res
#' ##with an inequality constraint:
#' contr <- list() #control list
#' ##specify constraint
#' contr$eval_g_ineq <- function(x) 1+x[1]-x[2]
#' res <- optimNLOPTR(,fun=funSphere,lower=c(-10,-20),upper=c(20,8),control=contr)
#' res
#'}
#' @export
###################################################################################################
optimNLOPTR<-function(x=NULL,fun,lower,upper,control=list(),...){
#if (length(par)==0) stop("dimension of par is null")
con<-list(funEvals=100)
con[names(control)] <- control
control<-con
#"types" not used here.
control$types <- NULL
#fixing some required arguments
if(!is.null(control$funEvals)){
control$opts$maxeval <- control$funEvals
control$funEvals <- NULL
}
if(is.null(control$opts$algorithm)){
control$opts$algorithm <- "NLOPT_GN_ORIG_DIRECT_L" #"NLOPT_GN_DIRECT_L"#"NLOPT_GN_ORIG_DIRECT_L"
}
#main arguments
control$x0 <- x
if(is.null(control$x0))
control$x0 <- runif(length(lower),lower,upper) #fix start guess if none provided
else
control$x0 <- control$x0[1,]
control$lb <- lower
control$ub <- upper
control$eval_f <- function(xx)fun(matrix(xx,1))
optimizationResult <- do.call(nloptr,control)
ybest <- optimizationResult$objective
xbest <- optimizationResult$solution
count <- optimizationResult$iterations
msg=optimizationResult$message
list(x=NA,y=NA,xbest=matrix(xbest,1),ybest=ybest,count=count,msg=msg)
}
|
9e1ffb65cc0f3223c39f658d1bc583304b71dda0 | 64a5a6704440f0bb6744a41d176b0896b1fd03cb | /PK_PD/Fig4.R | 55dc36a049e5a8f8ff3ee1c235417115b85e33f5 | [] | no_license | vayyappan/TemozolomideModel | 8b8393592d9d682b8ee53732d4019d52e12da9af | 6ad478e89b7a2584d6b3fd6a607dcd25a464a6b1 | refs/heads/master | 2020-05-24T03:33:51.491236 | 2019-05-16T18:05:04 | 2019-05-16T18:05:04 | 187,075,309 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 5,252 | r | Fig4.R | # Vinay, Kayla, and Claire
# April 20, 2019
library(ggplot2)
library(R.matlab)
library(reshape)
library(grid)
library(gridExtra)
# Figure 4 Full PK/PD Variability
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
# MGMT silenced
data_Plasma_TMZ_AUC_MGMT_silenced <- readMat("full_plasT_AUC_silence.mat",header=T,numerals='no.loss') # from mat file
data_Tumor_TMZ_AUC_MGMT_silenced <- readMat("full_tumT_AUC_silence.mat",header=T,numerals='no.loss')
data_Tumor_Adduct_AUC_MGMT_silenced <- readMat("full_tumorAdd_AUC_silence.mat",header=T,numerals='no.loss')
data_Ctrough_MGMT_silenced <- readMat("full_CtroughAdduct_silence.mat",header=T,numerals='no.loss')
data_Tvol_MGMT_silenced <- readMat("full_finalVol_silence.mat",header=T,numerals='no.loss')
# MGMT not silenced
data_Plasma_TMZ_AUC_MGMT <- readMat("full_plasT_AUC_mgmt.mat",header=T,numerals='no.loss')
data_Tumor_TMZ_AUC_MGMT <- readMat("full_tumT_AUC_mgmt.mat",header=T,numerals='no.loss')
data_Tumor_Adduct_AUC_MGMT <- readMat("full_tumorAdd_AUC_mgmt.mat",header=T,numerals='no.loss')
data_Ctrough_MGMT <- readMat("full_CtroughAdduct_mgmt.mat",header=T,numerals='no.loss')
data_Tvol_MGMT <- readMat("full_finalVol_mgmt.mat",header=T,numerals='no.loss')
# Transform into data frames
# MGMT silenced
Plasma_TMZ_AUC_MGMT_silenced <- log10(10e6*abs(as.data.frame(data_Plasma_TMZ_AUC_MGMT_silenced)))
Tumor_TMZ_AUC_MGMT_silenced <- log10(abs(as.data.frame(data_Tumor_TMZ_AUC_MGMT_silenced)))
Tumor_Adduct_AUC_MGMT_silenced <- log10(abs(as.data.frame(data_Tumor_Adduct_AUC_MGMT_silenced)))
Ctrough_MGMT_silenced <- log10(abs(as.data.frame(data_Ctrough_MGMT_silenced)))
Tvol_MGMT_silenced<- as.data.frame(data_Tvol_MGMT_silenced)
# MGMT not silenced
Plasma_TMZ_AUC_MGMT <- log10(abs(as.data.frame(data_Plasma_TMZ_AUC_MGMT)))
Tumor_TMZ_AUC_MGMT <- log10(abs(as.data.frame(data_Tumor_TMZ_AUC_MGMT)))
Tumor_Adduct_AUC_MGMT <- log10(abs(as.data.frame(data_Tumor_Adduct_AUC_MGMT)))
Ctrough_MGMT <- log10(abs(as.data.frame(data_Ctrough_MGMT)))
Tvol_MGMT <- as.data.frame(data_Tvol_MGMT)
# Melt them together
pop_a_Plasma_TMZ_AUC <- data.frame(Plasma_TMZ_AUC_MGMT,Plasma_TMZ_AUC_MGMT_silenced)
colnames(pop_a_Plasma_TMZ_AUC) <- c("Patient","MGMT Expressed","Patient","MGMT Silenced")
pop_a_Plasma_TMZ_AUC <- melt(pop_a_Plasma_TMZ_AUC,id.vars="Patient")
pop_a_Tumor_TMZ_AUC <- data.frame(Tumor_TMZ_AUC_MGMT,Tumor_TMZ_AUC_MGMT_silenced)
colnames(pop_a_Tumor_TMZ_AUC) <- c("Patient","MGMT Expressed","Patient","MGMT Silenced")
pop_a_Tumor_TMZ_AUC <- melt(pop_a_Tumor_TMZ_AUC,id.vars="Patient")
pop_a_Tumor_Adduct_AUC <- data.frame(Tumor_Adduct_AUC_MGMT,Tumor_Adduct_AUC_MGMT_silenced)
colnames(pop_a_Tumor_Adduct_AUC) <- c("Patient","MGMT Expressed","Patient","MGMT Silenced")
pop_a_Tumor_Adduct_AUC <- melt(pop_a_Tumor_Adduct_AUC,id.vars="Patient")
pop_a_Ctrough <- data.frame(Ctrough_MGMT,Ctrough_MGMT_silenced)
colnames(pop_a_Ctrough) <- c("MGMT Expressed","Patient","MGMT Silenced","Patient")
pop_a_Ctrough <- melt(pop_a_Ctrough,id.vars="Patient")
pop_a_Tvol <- data.frame(Tvol_MGMT,Tvol_MGMT_silenced)
colnames(pop_a_Tvol) <- c("MGMT Expressed","Patient","MGMT Silenced","Patient")
pop_a_Tvol <- melt(pop_a_Tvol,id.vars="Patient")
box_4a <- ggplot(pop_a_Plasma_TMZ_AUC,aes(x=variable,y=value,fill=variable)) +
geom_boxplot() +
scale_fill_manual(values=c("indianred2","#CCCCCC")) +
theme(text=element_text(size=8)) +
xlab("") +
ylab("log10(Plasma TMZ Exposure)") +
scale_y_continuous(limits=c(-5.979,-5.974),breaks=c(-5.979,-5.978,-5.977,-5.976,-5.975,-5.974)) +
theme_bw() +
guides(fill=FALSE)
box_4b <- ggplot(pop_a_Tumor_TMZ_AUC,aes(x=variable,y=value,fill=variable)) +
geom_boxplot() +
scale_fill_manual(values=c("indianred2","#CCCCCC")) +
theme(text=element_text(size=8)) +
xlab("") +
ylab("log10(Tumor TMZ Exposure)") +
scale_y_continuous(limits=c(-7.5,-2.0),breaks=c(-7.0,-6.0,-5.0,-4.0,-3.0,-2.0)) +
theme_bw() +
guides(fill=FALSE)
box_4c <- ggplot(pop_a_Tumor_Adduct_AUC,aes(x=variable,y=value,fill=variable)) +
geom_boxplot() +
scale_fill_manual(values=c("indianred2","#CCCCCC")) +
theme(text=element_text(size=8)) +
xlab("") +
ylab("log10(Tumor DNA Adduct Exposure)") +
scale_y_continuous(limits=c(-14.0,-2.0),breaks=c(-14.0,-12.0,-10.0,-8.0,-6.0,-4.0,-2.0)) +
theme_bw() +
guides(fill=FALSE)
box_4d <- ggplot(pop_a_Ctrough,aes(x=variable,y=value,fill=variable)) +
geom_boxplot() +
scale_fill_manual(values=c("indianred2","#CCCCCC")) +
theme(text=element_text(size=8)) +
xlab("") +
ylab("log10(Ctrough of Tumor DNA Adduct)") +
scale_y_continuous(limits=c(-25,-3),breaks=c(-25,-20,-15,-10,-5)) +
theme_bw() +
guides(fill=FALSE)
box_4e <- ggplot(pop_a_Tvol,aes(x=variable,y=value,fill=variable)) +
geom_boxplot() +
scale_fill_manual(values=c("indianred2","#CCCCCC")) +
theme(text=element_text(size=8)) +
xlab("") +
ylab("Final Tumor Volume (mL)") +
scale_y_continuous(limits=c(0,350),breaks=c(0,50,100,150,200,250,300,350)) +
theme_bw() +
guides(fill=FALSE)
out_6 <- grid.arrange(box_4a,box_4b,box_4c,box_4d,box_4e,nrow=2,top=textGrob("Full Parameter Variability",gp=gpar(fontsize=15,font=3)))
ggsave(file="Fig4_FullVariability.pdf",plot=out_6,width=10,height=7) # Save the figure
|
f095bb1fbf643ae564762e329236a3a1282a62a8 | f274e34dfa8fabf2c618809e415e97938b97f558 | /functions/6_apply_cloud_mask.r | caeec12be4b2bb72a2ff96991bba6ae33312148c | [] | no_license | dm00dy/autowater | a5600035d0d532f9eb8182d95ae2f5d1f0b0611b | c05ecf93a3616f07e36273b40e65fd12b1feaefc | refs/heads/master | 2020-06-10T12:11:06.816031 | 2016-12-08T20:47:18 | 2016-12-08T20:47:18 | 75,963,561 | 1 | 1 | null | null | null | null | UTF-8 | R | false | false | 5,744 | r | 6_apply_cloud_mask.r | # Purpose: apply cloud masks to landsat rasters
#
# Created: Apr 2016 (nelliott)
# Last modified: Apr 2016 (nelliott)
# Depends on most other code files in autowater\functions
# Main function for stacking the rasters
applyCloudMasks <- function(baseDir, scenes, dateStart, dateEnd, tempDir = tempdir(),
overwrite = FALSE, logOutLevel = "TRACE", cloudCoverThreshold = 5) {
withConditionLogging({
# Report
raiseCondition(message_debug_enter())
# Check inputs
checkInput(c("baseDir", "scenes", "dateStart", "dateEnd", "tempDir", "logOutLevel"),
classes = c("character", "character", "character", "character", "character", "character"),
lengths = c(1, NA, 1, 1, 1, 1))
# Base directory
checkFile(baseDir)
# Temp directory
checkFile(tempDir)
# Buckets
pvtBkt <- "gs://pointblue-autowater-pvt"
pvtDir <- file.path(baseDir, "pvt")
cloudBkt <- file.path(pvtBkt, "cloud_mask")
bufBkt <- file.path(cloudBkt, "buffered")
bufBktMnt <- file.path(pvtDir, "cloud_mask/buffered")
stkBkt <- file.path(pvtBkt, "stacked")
stkBktMnt <- file.path(pvtDir, "stacked")
outBkt <- file.path(stkBkt, "masked")
outBktMnt <- file.path(stkBktMnt, "masked")
# Check that the drives are mounted, runing mounting script if not
mounted <- gsCheck(condClass = "error", mount = TRUE)
# Check directories
checkFile(c(tempDir, bufBktMnt, stkBktMnt, outBktMnt))
# Raster temp dir
library(raster)
options(rasterTmpDir = tempDir)
# Get matching files
files <- listFilesBySceneDate(stkBktMnt, sceneChars = c(4, 9), scenes = scenes,
dateChars = c(11, 18), dateFormat = "%Y%m%d", dateStart = dateStart, dateEnd = dateEnd,
searchPattern = "stacked.tif$", full.names = TRUE)
# Iterate through files
for (f in files) {
message(message_info(paste0("Checking cloud mask for file ", f, "...")))
# Parse filename
fnDf <- parseFilenamePB(f)
pth <- fnDf$Path
rw <- fnDf$Row
dt <- as.Date(fnDf$Date)
# Get cloud cover of image from metadata
mdDf <- read.csv(file.path(pvtDir, "metadata/landsat_metadata.csv"))
cloudCover <- mdDf$CLOUD_COVER[mdDf$WRS_PATH == pth & mdDf$WRS_ROW == rw & as.Date(mdDf$DATE_ACQUIRED) == dt]
message(message_debug_vector("Cloud cover", cloudCover))
# Check against cloud cover threshold
if (cloudCover < cloudCoverThreshold) {
message(message_info(paste0("Cloud cover of image (", cloudCover,
"%) is less than the minimum specified to apply mask. Moving to next...")))
# Otherwise, apply mask
} else {
message(message_trace(paste0("Cloud cover of image (", cloudCover,
"%) is more than the minimum specified to apply mask.")))
# Out filename
outFn <- gsub("stacked", "masked", basename(f))
outFile <- file.path(tempDir, outFn)
outFileBkt <- file.path(outBkt, outFn)
outFileBktMnt <- file.path(outBktMnt, outFn)
# Check if output file exists
if (file.exists(outFileBktMnt)) {
if (overwrite == TRUE) {
raiseCondition(message_info(paste("Overwriting previous output (overwrite set to TRUE)")))
} else {
raiseCondition(message_info(paste("Image", f, "has already been cloud masked and overwrite = FALSE.",
"Moving to next...")))
next
}
}
# Load rasters
stk <- stack(f)
maskFile <- file.path(bufBktMnt, createFilenamePB(fnDf, newType = "clouds", newVersion = "00"))
checkFile(maskFile)
maskRst <- raster(maskFile)
# Stop if no cloud-free areas
message(paste("Mask Raster min value:", maskRst@data@min))
print(maskRst)
if (maskRst@data@min == 1) {
# Add to metadata
message(message_info("Deleting bad files."))
# Delete later files
toDelete <- c(list.files(outBktMnt, pattern = substr(basename(f), 1, 18), full.names = TRUE),
list.files(file.path(pvtDir, "predicted/continuous"), pattern = substr(basename(f), 1, 18), full.names = TRUE),
list.files(file.path(pvtDir, "predicted/thresholded"), pattern = substr(basename(f), 1, 18), full.names = TRUE),
list.files("/home/blue/pub/single_scenes", pattern = substr(basename(f), 1, 18), full.names = TRUE))
file.remove(toDelete)
# Skip
raiseCondition(raster_cloudmask_failure("No non-clouded areas of image exist. Skipping.", "warning"))
next
} else {
# Mask
raiseCondition(message_trace("Masking..."))
tryCatch({
outRst <- mask(stk, maskRst, maskvalue = 1, filename = outFile, overwrite = TRUE)
writeSemaphore(outFile)
message(message_info("Raster successfully masked."))
})
#}, warning = function(w) {
# invokeRestart("muffleWarning")
#})
# Copy summarized file to cloud, deleting original
gsCopy(outFile, outFileBkt, copySem = TRUE, deleteFrom = TRUE)
}
}
}
}, logOutLevel = logOutLevel, logFileLevel = "FATAL")
}
|
dbe53d17db4ecec64ac19e1f90a0d8fce8c06043 | 01b1302af51d339f7c8827a620c4a5fb26c890f1 | /vfm/pqr_combine_old_new_data.R | 7ff66b2853e11e0c093f00ef9058c0bc26637e50 | [] | no_license | ihmeuw/gf | 64ab90fb5a5c49694bde1596f4b20fcf107a76e3 | 29e0c530b86867d5edd85104f4fe7dcb1ed0f1ee | refs/heads/develop | 2021-08-15T02:16:59.086173 | 2021-08-03T19:52:31 | 2021-08-03T19:52:31 | 109,062,373 | 3 | 6 | null | 2019-03-21T01:48:02 | 2017-10-31T23:17:16 | R | UTF-8 | R | false | false | 7,712 | r | pqr_combine_old_new_data.R | # ----------------------------------------------
# Audrey Batzel
#
# 07/16/19
# Analyze PQR products
# ----------------------------------------------
# --------------------
# Set up R
rm(list=ls())
library(data.table)
library(ggplot2)
library(RColorBrewer)
library(zoo)
library(scales)
library(treemap)
library(treemapify)
library(grid)
library(dplyr)
library(grid)
library(gridExtra)
library(stringr)
library(ggrepel)
library(openxlsx)
# --------------------
# ----------------------------------------------
# Files and directories
# ----------------------------------------------
# switch for cluster
j = ifelse(Sys.info()[1]=='Windows','J:','/home/j')
dir = paste0(j, '/Project/Evaluation/GF/vfm/')
# input files
inFile = paste0(dir, 'unit_cost_data/prepped_data/prepped_full_pqr.rds')
inFile_new_pqr = paste0(dir, 'unit_cost_data/prepped_data/prepped_full_pqr_updated_09_2019.rds')
# output files
outFile = paste0(dir, 'unit_cost_data/prepped_data/prepped_full_pqr_with_sept_download_data.rds')
# ----------------------------------------------
# ----------------------------------------------
# Load/set up data
# ----------------------------------------------
data = readRDS(inFile)
# data = data[iso3codecountry %in% c('COD', 'GTM', 'SEN', 'UGA')]
data = data[, .(country_name, iso3codecountry, grant_name, grant_id, grant_start_date, grant_end_date,
purchase_order_date, scheduled_delivery_date, actual_delivery_date,
product_name_en, product_category, product_pack, description, product_description,
nb_packs_ordered, nb_units_in_pack, total_units_in_order,
total_product_cost_usd, total_cost_order, pack_cost_usd, unit_cost_usd,
po_median_unit_cost, po_international_reference_price,
supplier, pr_name, pr_type_name, primary_key, data_source = 'april_download')]
# add in new data from the most recent download.
data2 = readRDS(inFile_new_pqr)
# data2 = data2[iso3codecountry %in% c('COD', 'GTM', 'SEN', 'UGA')]
data2 = data2[, .(country_name, iso3codecountry, grant_name,
purchase_order_date, scheduled_delivery_date, actual_delivery_date,
'product_name_en'=product_name, product_category, product_pack, description, product_description,
nb_packs_ordered, nb_units_in_pack, total_units_in_order,
total_product_cost_usd, total_cost_order, pack_cost_usd, unit_cost_usd,
supplier, supplier_agent_manufacturer_intermediatry, primary_key, data_source = 'sept_download')]
# ----------------------------------------------
# ----------------------------------------------
# combine data sources
# ----------------------------------------------
# get the orders in the new data that were not in the old data - note some of these are not just after the last date in the
# old data... the oldest new order is from 2014?! so, add in the new orders using priamry key!
rm_from_data2 = unique(data$primary_key)
add_data = data2[ !primary_key %in% rm_from_data2 ]
# add the datasets together with rbind() to get all orders
data = rbindlist(list(data, add_data), use.names = TRUE, fill = TRUE)
# use primary key to add back in the this variable? - it seems to be a more complete version of the supplier/procurement mechanism variable!
data[, supplier_agent_manufacturer_intermediatry := NULL]
supplier_data = unique(data2[, .(primary_key, supplier_agent_manufacturer_intermediatry)])
data = merge(data, supplier_data, by = 'primary_key', all = TRUE)
# ----------------------------------------------
# ----------------------------------------------
# set reference price in the new data where it exists previously
# ----------------------------------------------
# standardize product names:
data[ product_name_en == "Ethambutol+Isoniazid+Pyrazinamide+Rifampicin (RHZE", product_name_en := "Ethambutol+Isoniazid+Pyrazinamide+Rifampicin (RHZE)"]
# the new orders don't have reference price - if there is an order without reference price, lookup if there is a
# reference price for the same product/description/pack size from a previous order - if there is, take the most recent
# reference price to when that order was purchased (max date that is less than the given order's date) and make that the
# reference price. Otherwise, leave it NA.
counter = 1
for (key in unique(data[data_source == 'sept_download', primary_key])) {
date = data[ primary_key == key, purchase_order_date]
prod = data[ primary_key == key, product_name_en]
dose = data[ primary_key == key, description]
pack = data[ primary_key == key, nb_units_in_pack]
all_potential_data = data[ product_name_en == prod & description == dose & nb_units_in_pack == pack, ]
if(nrow(all_potential_data)==1) next
if(all(is.na(all_potential_data$po_international_reference_price))) next
print(key)
max_date = all_potential_data[ !is.na(po_international_reference_price) & purchase_order_date <= date, max(purchase_order_date)]
set_irp = all_potential_data[ purchase_order_date == max_date, po_international_reference_price]
if(length(set_irp) > 1) {
#print(set_irp)
set_irp = set_irp[!is.na(set_irp)]
#print(set_irp)
if(length(unique(set_irp))==1) {
set_irp = set_irp[1] } else {
print('More than 1 unique reference price for this data - something is likely wrong...')
}
}
data[primary_key == key, po_international_reference_price := set_irp]
print(counter)
counter = counter + 1
}
# ----------------------------------------------
# ----------------------------------------------
# other set up for analysis
# ----------------------------------------------
# David said we don't care about specific brand of bednet, so make it so those will sum over product_name here:
data[product_category == 'bednet', product_name_en := 'bednet' ]
# make a separate "product category" for first and second line TB drugs:
first_line = c("Rifampicin" , "Pyrazinamide", "Ethambutol+Isoniazid+Pyrazinamide+Rifampicin (RHZE)", "Isoniazid",
"Ethambutol+Isoniazid+Rifampicin - FDC", "Isoniazid+Pyrazinamide+Rifampicin - FDC", "Isoniazid+Rifampicin - FDC",
"Ethambutol+Isoniazid - FDC", "Ethambutol")
second_line = c("Ofloxacin", "Levofloxacin", "Moxifloxacin", "Cycloserine", "Protionamide", "Amikacin", "Ethionamide", "Kanamycin",
"Capreomycin", "Linezolid", "Bedaquiline", "Meropenem", "Clofazimine", "Amoxicillin+Clavulanate - FDC", "Streptomycin", "PAS Sodium", "Delamanid")
other = c("Water for injection")
data[ product_name_en %in% first_line, sub_product_category := "first_line"]
data[ product_name_en %in% second_line, sub_product_category := "second_line"]
data[ product_name_en %in% other, sub_product_category := "other"]
data[ product_category == 'anti_tb_medicine', product_category := paste(product_category, sub_product_category, sep = "_") ]
# adjust IRPs and unit costs that are wrong:
data[unit_cost_usd == 0, unit_cost_usd := NA]
data[po_international_reference_price == 0, po_international_reference_price := NA ]
data[, diff_from_ref_cost := unit_cost_usd - po_international_reference_price]
data[, unit_cost_over_ref_price := unit_cost_usd / po_international_reference_price]
data[, purchase_order_year := year(purchase_order_date)]
# ----------------------------------------------
# ----------------------------------------------
# save data
# ----------------------------------------------
saveRDS(data, outFile)
#save GTM data as a .csv
dt = readRDS(outFile)
gtm = dt[ iso3codecountry == 'GTM' ]
write.csv(gtm, paste0(dir, 'unit_cost_data/prepped_data/PQR_data_GTM.csv'))
# ---------------------------------------------- |
fa55c603d44dd11b17ba9f62eb721dd5a038deb5 | 0742e586f71a21a34191d6f1faa53627144a500b | /R/issvd.R | da9fbcec56fc8e7f8153a0327fbba5b889715ea3 | [] | no_license | cqli-stat/issvd | 9fe5332126e49a55c090751b12de5a6878358dfd | c8ecd975e58a1e9c642ae2c9b3e7edc26cb6bebb | refs/heads/main | 2022-12-30T00:35:19.738921 | 2020-10-19T02:20:36 | 2020-10-19T02:20:36 | 303,396,791 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 4,086 | r | issvd.R | #' Perform intergative and sparse singular value decomposition analysis
#'
#' Performs intergative and sparse singular value decomposition analysis
#' to multiple data matrix with penalty on the columns and the rows.
#'
#' @param x list with K Data matrices of dimension $n x pk$, which can contain NA for missing
#' values. We are interested in finding sparse singular value decomposition of
#' dimension $pk$.
#' @param ncomp The number of factors in the ISSVD to be returned; default is 1.
#' @param varnumv vectors with K elements. How sparse do you want vk to be in the K data matrices?
#' Each elements of varnumv represents how many variables is left, hence its value must be between 1 and pk.
#' The smaller it is, the sparser v will be.
#' @param varnumu How sparse do you want u to be in the K data matrices?
#' @param type Which kind of penalty is chosen? Possible options are \code{"soft"}, \code{"hard"}, \code{"bic"},
#' and \code{"SCAD"}. Default is \code{"soft"}.
#' @param maxiter How many iterations should be performed. It is best to run at
#' least 100 of so. Default is 100.
#' @param eps convergence threshhold. The default threshhold is 10^(-4).
#' @return \item{U}{The common left singular matrix U.}
#' \item{D}{The individual scale matrices D.}
#' \item{V}{The individual right singular matrices V.}
#' @examples
#' n=100;p1=p2=p3=50;sig1=sig2=sig3=0.1;
#' d1=d2=1;d3=50;
#' simdata=simdata(n,p1,p2,p3,sig1,
#' sig2,sig3,d1,d2,d3)
#' varv_opt=list(c(16,16,16))
#' varu_opt=25
#' issvd_model=issvd(x,1,varv_opt,varu_opt,type='soft')
issvd=function(x,ncomp=1,varnumv,varnumu,type="soft",maxiter=100,eps=10^(-4)){
K=length(x);n=nrow(x[[1]])
Tx=c(); p<-rep(0,K);
V=list();D=list();
for(k in 1:K){
Tx=cbind(Tx,x[[k]])
p[k]<-ncol(x[[k]])
V[[k]]=matrix(0,p[k],ncomp);
D[[k]]=matrix(0,ncomp,ncomp);
}
U=matrix(0,n,ncomp);
for(i in 1:ncomp){
if(varnumu[[i]]>n||varnumu[[i]]<1) stop("The value of varnumu must be between 1 and n")
if(length(varnumv[[i]])!=K) stop("The length of varnumv must be equal with the number of x ")
for(k in 1:K){
if(varnumv[[i]][k]>p[k]||varnumv[[i]][k]<1) stop("Each elements of varnumv must be between 1 and pk")
}
}
for(i in 1:ncomp){
# initialization step
U.old=svd(Tx,ncomp,ncomp)$u[,1]
V.old=list()
for(k in 1:K){
V.old[[k]]=svd(x[[k]],ncomp,ncomp)$v[,1]
}
V.cur=V.old
D.old=list()
for(k in 1:K){
D.old[[k]]=svd(x[[k]],ncomp,ncomp)$d[1]
}
D.cur=D.old
# iteration step
u.d <- v.d <- d.d<-1;iter=1;
while((u.d>eps|v.d>eps|d.d>eps)&&iter<maxiter){
# Updating v
for(k in 1:K){
lambda <- c()
D_old_k_i=as.numeric(D.old[[k]])
f=as.matrix(U.old)%*%D_old_k_i;
lambda[k] <- sort(abs(t(x[[k]])%*%f))[p[k]-varnumv[[i]][k]]
V.cur[[k]]=t(solve(D_old_k_i%*%D_old_k_i)%*%
thresh(t(f)%*%x[[k]],type,lambda[k], a=3.7));
V.cur[[k]] <- V.cur[[k]]/norm(V.cur[[k]],'2')
}
TF=matrix(0,n,1)
for(k in 1: K){
TF=TF+x[[k]]%*%V.cur[[k]]%*%t(D.old[[k]])
}
TV=0
for(k in 1:K){
TV=TV+D.old[[k]]%*%t(D.old[[k]])
}
# Updating u
lambda <- sort(abs(TF))[n-varnumu[[i]]]
TF=thresh(TF,type,lambda,a=3.7)
U.cur=TF%*%solve(TV)
U.cur <-U.cur/norm(U.cur,'2')
# Updating d
for(k in 1:K){
D.cur[[k]]=t(U.cur)%*%x[[k]]%*%V.cur[[k]]
}
u.d <- sqrt(sum((U.cur-U.old)^2))
v.d <- sqrt(sum((unlist(V.cur)-unlist(V.old))^2))
d.d <- sqrt(sum((unlist(D.cur)-unlist(D.old))^2))
D.old=D.cur;V.old=V.cur;U.old=U.cur
iter=iter+1
}
U[,i]=U.cur[,1]
Tx=c();
for(k in 1:K){
V[[k]][,i]=V.cur[[k]]
D[[k]][i,i]=D.cur[[k]]
x[[k]]=x[[k]]-U[,i]%*%D.cur[[k]]%*%t(V.cur[[k]])
Tx=cbind(Tx,x[[k]])
}
}
return(list(U=U,V=V,D=D))
}
|
a828df0861128915c634b7cbac75264ae352fbcf | d392fd5cb7426e78c92c83f9afbf2f55cd98c323 | /sandbox/bnlearn_example.R | e391156585c9275b6af1719db363e2e098b3fce4 | [
"MIT"
] | permissive | Aszdu2021/cics490e_research | 959aacc27e1c2f33c19f600c6cb2727b2b73fc6a | a4208cb465aa6d391b1731844a622e9c24c9625e | refs/heads/main | 2023-08-25T06:48:54.157130 | 2021-10-27T16:31:04 | 2021-10-27T16:31:04 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,989 | r | bnlearn_example.R | # If bnlearn and bnviewer packages are not installed. Install them using below lines
# install.packages(c("bnlearn", "bnviewer"))
library("bnlearn") #load bnlearn package
library("bnviewer") # load package to view bayesian networks
# set base project directory
base <- "~/Projects/cics490e_research"
setwd(base)
# variables for which we want to learn the structure
cols = c("action", "reward", "taxi_x_t", "taxi_y_t", "pass_x_t", "pass_y_t", "pass_in_taxi",
"taxi_x_t1", "taxi_y_t1", "pass_x_t1", "pass_y_t1", "pass_in_taxi_t1")
# variables at time t+1
t2.variables = c("taxi_x_t1", "taxi_y_t1", "pass_x_t1", "pass_y_t1","pass_in_taxi_t1", "reward")
# variables ar time t
t1.variables = c("taxi_x_t", "taxi_y_t", "pass_x_t", "pass_y_t", "pass_in_taxi")
# sample dataset for which we want to learn the structure
data <- read.csv("sample_bayesian_network_data.csv")
# blacklist 1 which restricts arrows from t+1 to t variables (from future to past)
blacklist_1 = tiers2blacklist(list(t1.variables, t2.variables))
# blacklist 2 which restricts arrows from within variables at time t(intra-step variables)
blacklist_2 = set2blacklist(t1.variables)
# blacklist 2 which restricts arrows from within variables at time t + 1 (intra-step variables)
blacklist_3 = set2blacklist(t2.variables)
# exclude action from t variables.
var_excl_action = setdiff(t1.variables, c("action"))
# blacklist 4 which restricts arrow from action variable to variables at time t (excluding action)
blacklist_4 = expand.grid(from = "action", to = var_excl_action)
# exclude reward from t+1 variables.
var_excl_reward = setdiff(t2.variables, c("reward"))
# blaklist 5 which restricts arrows from reward variable to variables at time t+1 (excluding reward)
blacklist_5 = expand.grid(from = "reward", to = var_excl_reward)
# combine all blacklists into 1 list.
bl = rbind(blacklist_1, blacklist_2)
bl = rbind(bl, blacklist_3)
bl = rbind(bl, blacklist_4)
bl = rbind(bl, blacklist_5)
# NOTE: To add constraint about edges which should be in graph, use whitelists.
# https://www.bnlearn.com/examples/whitelist/
# view blacklist which contains constraints about edges which should not be in the graph.
# cross-check id all constraints are included.
print(bl)
# only include columns in cols
df = data[cols]
# convert data type from numeric to factor (catgorical)
df[] <-lapply(df, as.factor)
# learn structure of the bayesian network with given prior knowledge in blacklist
net <- hc(df, blacklist = bl)
# fit parameters for the bayesian network
bn = bn.fit(net, df)
# view the bayesian network structure
viewer(net, bayesianNetwork.width = "100%",
bayesianNetwork.height = "80vh",
bayesianNetwork.layout = "layout_with_sugiyama",
bayesianNetwork.title="Discrete Bayesian Network - Taxi",
bayesianNetwork.subtitle = "Structural Relationships in Taxi Domain using random policy",
bayesianNetwork.footer = "Fig. 1 - Structural Relationships in Taxi Domain")
|
22b9c1fa8401e7380a7e9ed9f68ed16187084a73 | e1f1b00d4fbd43b8cdde939fdfe4a40527391e01 | /2014/Scripts/lingua_estrangeira.R | 92eb1ccb35da75a4337b368bff9e5e017fe73814 | [] | no_license | ghnunes/TRI | 32e6fb0d0c61db61e235841e8f3d73e218cf4fa0 | 5ab35c684dab2c6b42748b2627642229dfb9fb62 | refs/heads/master | 2020-04-08T16:38:56.643164 | 2018-11-28T17:44:57 | 2018-11-28T17:44:57 | 159,528,229 | 0 | 1 | null | null | null | null | MacCentralEurope | R | false | false | 1,039 | r | lingua_estrangeira.R | dados <-read.csv(file="amostra_enem2014_50k.csv", sep =",")
dados$X <- NULL
ingles <- c("X","X","X","X","X")
espanhol <- c("X","X","X","X","X")
codigo_prova_ingles <- 0
codigo_prova_espanhol <- 0
vet_respostas <- c("X","X","X","X","X")
for(i in 1:nrow(dados)){
resposta<-dados[i,11]
#0 significa que o participante fez a prova de inglÍs/1 fez espanhol
if(dados[i,13] == 0){
for(k in 1:5){
vet_respostas[k]<-str_sub(resposta,k,k)
}
ingles <- rbind(ingles,vet_respostas[1:5])
codigo_prova_ingles <- rbind(codigo_prova_ingles,dados[i,7])
}else{
for(k in 1:10){
vet_respostas[k]<-str_sub(resposta,k,k)
}
espanhol <- rbind(espanhol,vet_respostas[1:5])
codigo_prova_espanhol <- rbind(codigo_prova_espanhol,dados[i,7])
}
}
respostas_ingles <- cbind(ingles, codigo_prova_ingles)
respostas_espanhol <- cbind(espanhol, codigo_prova_espanhol)
write.csv(respostas_ingles, file="respostas_ingles.csv")
write.csv(respostas_espanhol, file="respostas_espanhol.csv")
|
51b1613bd095c6393326d5a59603d756a8f5b367 | 0f70d423c62d58444cccba2c0a755441bf93f10e | /R/dasper-package.R | 733accb8e028444be4edd627a7a7187ba2ff9c17 | [] | no_license | dzhang32/dasper | c871edc3179d448a9c09c049490d19371c9ef13e | ec5f82ad8c667215cf976dc701c39be98a993851 | refs/heads/master | 2022-05-19T20:22:22.395656 | 2022-03-26T17:54:08 | 2022-03-26T17:54:08 | 245,168,125 | 15 | 3 | null | 2020-08-26T08:41:53 | 2020-03-05T13:18:19 | R | UTF-8 | R | false | false | 779 | r | dasper-package.R | #' dasper: detecting abberant splicing events from RNA-seq data
#'
#' Placeholder for package description - to be updated
#'
#' @docType package
#' @name dasper
NULL
#' @import S4Vectors
#' @importFrom methods is
#' @importFrom magrittr %>%
#' @importFrom dplyr count
#' @importFrom data.table :=
#' @importFrom data.table .SD
#' @importFrom GenomicRanges seqnames start end strand width
#' @importFrom GenomicRanges start<- end<- strand<-
#' @importFrom GenomicRanges findOverlaps GRanges
#' @importFrom IRanges CharacterList
#' @importFrom SummarizedExperiment colData rowRanges assays
#' @importFrom SummarizedExperiment assays<-
#' @importFrom basilisk BasiliskEnvironment
#' @importFrom reticulate import
#' @importFrom basilisk basiliskStart basiliskRun basiliskStop
NULL
|
54b650368e650582f7f4ab79be56b521073a056f | 1c2fdd9b87babc17722657bcecc7546df3d88dfb | /chickweight.R | f3c8afaa2816a32cd69c076f5a321a482d5ee08d | [] | no_license | sourabh-burnwal/R_programs | df9be507922607b648f3dc2603e6d37efdcec708 | e75aa3f82376cca784f7e0f543ec4ceb6ea5ea0c | refs/heads/master | 2021-08-19T15:31:50.552188 | 2020-09-02T07:49:31 | 2020-09-02T07:49:31 | 218,616,570 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 259 | r | chickweight.R | data("ChickWeight")
c_time <- ChickWeight$Time
c_weight <- ChickWeight$weight
print(c_time)
print(c_weight)
plot(c_time,c_weight,main="time vs weight",xlab="Chicken time",ylab="Chicken weight",pch=20)
print(cor(c_time,c_weight))
hist(c_weight) |
00000c290c36cb755c6d1ec7910671d658189b5b | 1b5c0b76a8bccd3977182b7e40c3cb23e7702650 | /plot3.R | a0d77818c30b7554b11c26c1fd4ba4f6fe507421 | [] | no_license | jessiebao/exploratory-graph-hw1 | 198b76ddf0c2f8f709b3a25bf89eca2797d9fec8 | 4d1eca0b0213386d82bfc39b9c5ea47f0ae93cb3 | refs/heads/master | 2020-05-26T20:07:16.530765 | 2014-07-10T19:25:51 | 2014-07-10T19:25:51 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,322 | r | plot3.R | # Loading the data
filepath<-paste("E:/John Hopkin R Introduction/r data/","household_power_consumption.txt",sep="")
d1<-as.Date("2007-02-01","%Y-%m-%d")
d2<-as.Date("2007-02-02","%Y-%m-%d")
data<-read.table(filepath,na.strings="?",header=T,sep=";") # load all the data
data$Date<-as.Date(data$Date,"%d/%m/%Y") # covert Date variable from character class to Date class
data_sub<-data[(data$Date ==d1 | data$Date ==d2),] # subset the data
data_sub$Time<-strptime(data_sub$Time,"%H:%M:%s") # convert the Time variables to Time classes in R
data_sub$weekday<-weekdays(data_sub$Date)
# Making the plot 3
par(mfcol=c(1,1),mar=c(4,4,2,1))
a<-split(Sub_metering_1,weekday) # split power of data_sub by weekday
plot(c(a$Thursday,a$Friday),type="l",xlab="",
ylab="Energy sub metering",
xaxt="n")
a<-split(Sub_metering_2,weekday)
lines(c(a$Thursday, a$Friday),col="red")
a<-split(Sub_metering_3,weekday)
lines(c(a$Thursday, a$Friday),col="blue")
axis(side=1, at = c(0,1440,2880), labels = c("Thu", "Fri", "Sat")) # I know there are 1440 Thursday
legend("topright",legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),
lty=1,col=c("black","red","blue"))
# Saving the plot 3
setwd("E:/John Hopkin R Introduction/r output")
dev.copy(png,file="plot3.png", width = 480, height = 480, units = "px")
dev.off()
|
479de9f7a7b7b73fc3001201d094aee608b5ea03 | 275e16c54c403273d717877cc4fd3e47507f0e02 | /pmaetzig-msc-thesis-maetzig/ACTRPredictions2016/R/get_data.R | 70f9b344fdd952e7bd7ff61bbd35a84b3219a29f | [] | no_license | vasishth/MaetzigEtAl2018 | 99305efd29ba437106c01534c4a218010b0749e8 | 78fe2eed9185d7acf0b21bcda2ee89849b879c37 | refs/heads/master | 2023-03-11T21:33:31.634372 | 2021-02-25T16:53:25 | 2021-02-25T16:53:25 | 342,311,617 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,759 | r | get_data.R | #' @title Reading data files for ACT-R paramsearch
#'
#' @description Read all fixation files from an ACT-R paramsearch and create a list of
#' data.frames from them.
#'
#' @param path string of the path of the fixation files directory
#' @param paramsearch data.frame containing paramsearch metainformation
#' @return all_fixations \code{list(list(data.frame, data.frame))} with fixations of the ACT-R paramsearch simulations.
#'
#' @details This is currently only fit to output of the ACT-R function
#' \code{run-param-search-em} and the output it generates for experiment 1 of
#' Grodner & Gibson (2005). A more flexible framework will be added later.
#'
#' @seealso \code{\link{get_parameters}} for creating a paramsearch data.frame
#'
#' @export
get_data <- function(path=".", paramsearch) {
column_names <- c("exp", "iter", "condition", "roi", "word", "dur")
cond_levels <- c("OR", "SR")
# create list of fixation files
file_list <- list.files(path=path,
pattern="[[:digit:]{1}]-fixations[[:punct:]{1}]txt")
# pre-allocate the final list
all_fixations <- vector(mode="list", length=length(file_list))
for (i in 1:length(file_list)) {
df_name <- paste(paramsearch$set[i],
paste("fix", paramsearch$params[i], sep="-"), sep="-")
df <- read.table(paste(path, file_list[i], sep="/"))
colnames(df) <- column_names
levels(df$condition) <- cond_levels
current_parameters <- paramsearch[i, 6:ncol(paramsearch)]
tmp_list <- vector(mode="list", length=2)
names(tmp_list) <- c(df_name, "params")
tmp_list[[1]] <- df
tmp_list[[2]] <- current_parameters
all_fixations[[i]] <- tmp_list #the respective pair of data and params
}
return(all_fixations)
}
|
b3f1f99b54174a9e1ebbdd72582691b4e7106da7 | 41e089b009c149e6b44730880f5c5da8eb4b763e | /datasciencecoursera R ProgrammingAssignment2.R | 1c866ee4ca8836dfdac9a3c0b91de0b23b853972 | [] | no_license | elydina/ProgrammingAssignment2 | 4254a957ab4bdba4125f8b94e3931fee7a3ba5c1 | 8a48fb46343723be660f36755f183e8dd1dcb117 | refs/heads/main | 2023-01-24T10:11:20.907539 | 2020-12-10T09:31:59 | 2020-12-10T09:31:59 | 310,839,896 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,022 | r | datasciencecoursera R ProgrammingAssignment2.R | ## makeCacheMatrix: This function creates a special “matrix” object that can cache its inverse.
makeCacheMatrix <- function(x = matrix()) {
## Initialize the inverse property
inv <- NULL
setMatrix <- function(y){
x <<- y
inv <<- NULL
}
getMatrix <- function(){
x
}
## Method to set the inverse of the matrix
setInverse <- function(solveMatrix){
inv <<- solveMatrix
}
## Method to get the inverse of the matrix
getInverse <- function(){
inv
}
list(setMatrix = setMatrix, getMatrix = getMatrix, setInverse = setInverse, getInverse = getInverse)
}
##cacheSolve: This function computes the inverse of the special "matrix" returned by makeCacheMatrix above
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inverse <- x$getInverse()
if(!is.null(inv)){
message("getting cached data")
return(inverse)
}
data <- x$getMatrix()
inv <- solve(data)
x$setInverse(inverse)
inverse
}
|
ae5210794dab3e8e36ee0d94a483ecc9ce5bbf7d | e17906b9f216234a22e4a40c9eb72f645cd5e03c | /survival_analysis.R | 448473ff5997e49aa177f83eddfb8832cb91d7f1 | [] | no_license | abhiachoudhary/DARL_2017 | 8902ab3ce84a1545b4d156b8ab46c90e2f27159d | 7ebfdefd8282a935f4c1ff41d4fd7415eec2c9d6 | refs/heads/master | 2020-04-22T00:47:25.767442 | 2019-02-10T17:26:27 | 2019-02-10T17:26:27 | 169,993,129 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 171 | r | survival_analysis.R | ## Load survival package
library(survival)
## List datasets in survival package
data(package = "survival")
## Load lung data
data(lung)
## Show first 6 rows
head(lung)
|
d42d8107b7593cfa81728fd990b328e4d53cbaec | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/BeviMed/R/RcppExports.R | 36135eb545e9c2bdf55b176292c0aee00ea1dac8 | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | R | false | false | 1,083 | r | RcppExports.R | # Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
bevimed_mc <- function(its, y, var_block_start_index, var_block_stop_index, cases, counts, min_ac, tau_shape1, tau_shape2, pi_shape1, pi_shape2, z_shape1, z_shape2, z0, estimate_logit_z_rate, logit_z_rates, logit_z_rate_proposal_sds, z_weights, estimate_phi, log_phis, log_phi_mean, log_phi_sd, log_phi_proposal_sds, t, swaps, annealing, tandem_variant_updates, y1_case_block_start_index, y1_case_block_stop_index, y1_variants, return_z_trace, return_x_trace) {
.Call('_BeviMed_bevimed_mc', PACKAGE = 'BeviMed', its, y, var_block_start_index, var_block_stop_index, cases, counts, min_ac, tau_shape1, tau_shape2, pi_shape1, pi_shape2, z_shape1, z_shape2, z0, estimate_logit_z_rate, logit_z_rates, logit_z_rate_proposal_sds, z_weights, estimate_phi, log_phis, log_phi_mean, log_phi_sd, log_phi_proposal_sds, t, swaps, annealing, tandem_variant_updates, y1_case_block_start_index, y1_case_block_stop_index, y1_variants, return_z_trace, return_x_trace)
}
|
460ffb2a44be760b05f7b3bf7e87fd8c5450ffed | 5e52aa7a947a2f416806d97ad1e96bf0b678dd1f | /man/rgDataSet-class.Rd | b4038e31d353ae64a8edc0a09106684cd9bfce0f | [] | no_license | xuz1/ENmix | 2428b36d6a25d3539990838b1df9834b1b30c9d8 | 8f5c71e6b756f8ddd729f68cfff014608ac009b8 | refs/heads/master | 2023-08-09T13:03:11.288105 | 2023-07-26T14:30:57 | 2023-07-26T14:30:57 | 33,955,695 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,110 | rd | rgDataSet-class.Rd | \docType{class}
\name{rgDataSet-class}
\alias{rgDataSet-class}
\alias{rgDataSet}
%methods
\alias{show, rgDataSet-method}
\title{Class \code{"rgDataSet"}}
\description{A class for storing Illumina methylation array
raw intensity data of two color channels, and probe annotation
infomation.}
\usage{
rgDataSet(Red = new("matrix"), Green = new("matrix"),
NBeads = new("matrix"),rowData=new("DataFrame"),ictrl= new("DataFrame"),...)
}
\arguments{
\item{Red}{A matrix of Red channel intensity values with row for methylation probes
and column for samples}
\item{Green}{A matrix of Green channel intensity values with row for methylation probes
and column for samples}
\item{NBeads}{A matrix contains the number of beads used to generate intensity values
on the Red and Green channels.}
\item{rowData}{A dataframe contains probe annotation information}
\item{ictrl}{A dataframe contais detailed information for Illumina internal control probes}
\item{...}{other arguments for class SummarizedExperiment}
}
\value{
An object of class \code{rgDataSet}
}
\examples{
showClass("rgDataSet")
}
|
505e81c8994be96d98b7697318e1ae1553fb47c5 | 34b2ba7856c19ea52ba146c76a3246cdf7c54f65 | /risteys/summary.R | e55b15feebecc2ac643c45b33ebae1937e5936df | [
"MIT"
] | permissive | jjmpal/cabg_sex | 2e183064c05867529eaa393db346aa91cdf9b978 | 4643fbc8e75569f178c2019e2c9e4eb6c978ccf8 | refs/heads/main | 2023-04-13T22:09:42.343966 | 2022-02-23T11:56:51 | 2022-02-23T11:56:51 | 371,006,555 | 0 | 1 | MIT | 2022-02-17T14:06:47 | 2021-05-26T11:17:04 | Python | UTF-8 | R | false | false | 564 | r | summary.R | library(dplyr)
library(readr)
library(knitr)
file <- commandArgs(trailingOnly = T)[1]
if (!file.exists(file)) {
message("Usage: summary.R <file>")
quit()
}
dset <- readr::read_csv(file)
dset %>%
#filter(is.na(lag_hr)) %>%
select(prior, outcome, lag_hr, nobservations, nevents, nindivs_prior_outcome, sex_coef, sex_pval, sexprior_pval, prior_coef, prior_pval) %>%
mutate(prior_coef = exp(prior_coef),
prior = strtrim(prior, 10),
outcome = strtrim(outcome, 10)) %>%
#mutate_if(is.numeric, ~sprintf("%.2f", .x)) %>%
arrange(prior_pval) %>%
kable
|
1b5e7339281a70161de1057dba1c60b8f77b9a37 | a3fee29cd8bbde854bc1a3322da7950c068cd896 | /cachematrix.R | b6aded0b60e44e0abc262cc120d5875f1d8eccf4 | [] | no_license | JoeyStats/ProgrammingAssignment2 | 3ec420e8c2f9d6d13b17c8786921793433de2742 | f0ae74734aae82943af095176b7623c338a590ec | refs/heads/master | 2020-04-06T06:15:42.674280 | 2015-04-26T17:52:09 | 2015-04-26T17:52:09 | 34,620,589 | 0 | 0 | null | 2015-04-26T16:37:13 | 2015-04-26T16:37:13 | null | UTF-8 | R | false | false | 761 | r | cachematrix.R |
## The following function cache's the inverse of a matrix, so
## that it can be used in computations without re-computing it.
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setInv <- function(solve) m <<- solve
getInv <- function() m
list(set = set, get = get,
setInv = setInv,
getInv = getInv)
}
## The following function retrieve's the inverse matrix
## that was cache'd in the previous function.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'.
m <- x$getInv()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data, ...)
x$setInv(m)
m
}
|
30e469a9e13fc25b90ddaa2597f45042e96175ad | 6d07bebd60a203ff1471e15621fdb270410e0c6a | /player-comparision.R | 3ffaffe827e0adfd13dc5ca3c8a1540086b98c09 | [] | no_license | codevaam/Football-league-analysis | b31ff22d028729940e25d6597831381f338a7855 | 2ae60f5ab4726001bf6bd4ddf27a615fc0a1390c | refs/heads/master | 2022-12-03T11:02:59.842047 | 2020-08-25T09:02:57 | 2020-08-25T09:02:57 | 240,923,514 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,021 | r | player-comparision.R | datarad = read.csv('data.csv')
head(datarad)
library('plotly')
rad = datarad[c('Name', 'Finishing', 'Dribbling', 'SprintSpeed', 'ShortPassing', 'StandingTackle')]
player1 = "L. Messi"
player2 = "Cristiano Ronaldo"
cmp = rad[(rad$Name==player1), c('Finishing', 'Dribbling', 'SprintSpeed', 'ShortPassing', 'StandingTackle')]
cmp = rbind(cmp, rad[(rad$Name==player2), c('Finishing', 'Dribbling', 'SprintSpeed', 'ShortPassing', 'StandingTackle')])
pc1=c(cmp$Finishing[1], cmp$Dribbling[1], cmp$SprintSpeed[1], cmp$ShortPassing[1], cmp$StandingTackle[1])
pc2=c(cmp$Finishing[2], cmp$Dribbling[2], cmp$SprintSpeed[2], cmp$ShortPassing[2], cmp$StandingTackle[2])
typeof(pc1)
p = plot_ly(type='scatterpolar', fill='toself') %>%
add_trace(r=pc1, theta = c('Shoot', 'Movement', 'Pace', 'Passing', 'Defence'), name=player1) %>%
add_trace(r=pc2, theta = c('Shoot', 'Movement', 'Pace', 'Passing', 'Defence'), name=player2) %>%
layout(polar = list(radialaxis = list(visible = T, range=c(0,100))))
print(p)
|
a2235d6a30138947b119325cf1c245601868968f | 4ae32cabb0fd268f313c4c2a54cecf9daffc9797 | /man/StatLTavg.Rd | c7e26159b8c37a3879b4f3c6d1e1571d13df5abe | [
"Apache-2.0"
] | permissive | InteragencyEcologicalProgram/smonitr | 40d9201f5284100aa34015014eeb94229e722fc2 | 6bb40251473dac065587dc1b40f4f747963d1b73 | refs/heads/master | 2021-02-13T12:33:04.458773 | 2020-10-28T17:10:49 | 2020-10-28T17:10:49 | 244,696,632 | 2 | 2 | NOASSERTION | 2020-10-01T20:54:30 | 2020-03-03T17:16:42 | R | UTF-8 | R | false | true | 355 | rd | StatLTavg.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/plot_geoms.R
\docType{data}
\name{StatLTavg}
\alias{StatLTavg}
\title{StatLTavg ggproto}
\format{
An object of class \code{StatLTavg} (inherits from \code{Stat}, \code{ggproto}, \code{gg}) of length 3.
}
\usage{
StatLTavg
}
\description{
StatLTavg ggproto
}
\keyword{internal}
|
c283b2ca5c832ce0f4c8ff9c03faecea0cd13a7a | 29585dff702209dd446c0ab52ceea046c58e384e | /PopGenReport/R/popgenreport.r | 8f00283cf69064799dcdf8fac38c0504c80d42be | [] | no_license | ingted/R-Examples | 825440ce468ce608c4d73e2af4c0a0213b81c0fe | d0917dbaf698cb8bc0789db0c3ab07453016eab9 | refs/heads/master | 2020-04-14T12:29:22.336088 | 2016-07-21T14:01:14 | 2016-07-21T14:01:14 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 11,204 | r | popgenreport.r | popgenreport <- function(cats=NULL,
mk.counts=TRUE, # this switch is to provide a population overview
mk.map=FALSE, # this switch is for the map
maptype="satellite",
mapdotcolor ="blue",
mapdotsize=1,
mapdotalpha=0.4,
mapdottype=19 ,
mapzoom=NULL,
#c("roadmap",
#"mobile",
#"satellite",
#"terrain",
#"hybrid",
#"mapmaker-roadmap",
#"mapmaker-hybrid")",
#
mk.locihz=FALSE, # this switch is to test for population heterozygosity
mk.hwe=FALSE, # this switch is for population wide HWE
mk.fst=FALSE, # this switch is to run FST tests on the full population
mk.gd.smouse=FALSE, # this switch is to run the Smouse and Peakall genetic distances
mk.gd.kosman=FALSE, # this switch is to run the Kosman and Leonard genetic distances
mk.pcoa=FALSE,
mk.spautocor=FALSE,
mk.allele.dist=FALSE, # this switch it to look at allele distributions by loci and pop
mk.null.all=FALSE,
mk.allel.rich=FALSE,
mk.differ.stats=FALSE , # this switch is to look at population differentiation statistics (Fst, Gst, etc)
mk.custom = FALSE,
fname="PopGenReport",
foldername="results",
path.pgr=NULL,
mk.Rcode=FALSE, # make the code that was ran available as an R file
mk.complete=FALSE, # create a full report)
mk.pdf=TRUE)
{
if (class(cats)!="genind") {cat("You did not provide a valid genind object! Script stopped!\n"); return;}
# Check for combinations of populations and loci with low numbers of individuals and alleles
npops<-length(levels(cats@pop))
nloci<-length(locNames(cats))
# this splits bilby up into loci
loci<-seploc(cats)
# this further subdivides the loci into populations
locipop<-lapply(loci,seppop)
popsizes<-matrix(NA,nrow=nloci,ncol=npops)
for (i in 1:nloci){
for (j in 1:npops){
popsizes[i,j]<-sum(!is.na(apply(locipop[[i]][[j]]@tab,1,sum)))
}
}
for(i in 1:dim(popsizes)[2]){
numlow<-length(which(popsizes[,i]<3))
if(numlow>0) message("Population ",unname(popNames(cats))[i]," has ",numlow," locus/loci with less than 3 genotypes. This may cause errors in some analyses. We advice to combine or drop populations with low numbers of genotypes. ")
}
### adjusting causes error with Adegenet 2.0 and it is controlled for when creating the object!!
#cut down length of loci names to 6 and make sure they are unique
#locNames(cats) <- substr(locNames(cats),1,6)
#if (length(unique(locNames(cats)))!= length(locNames(cats)))
#{locNames(cats) <- paste(1:length(locNames(cats)),"-",substr(locNames(cats),1,4), sep="")
#cat("Loci names were not unique and therefore adjusted.\n")
#}
#levels(cats@loc.fac) <- locNames(cats) #make sure levels and factors are the same
#check if pop.names, indnames are unique!!!!
#adjust if necessary and issue a notification
# if (length(unique(indNames(cats)))!=length(indNames(cats)))
# {indNames(cats) <- paste(1:length(indNames(cats)),"-",substr(indNames(cats),1,8),sep="")
# cat("Individual names were not unique and therefore adjusted.\n")
# }
#
#
#
# if (length(unique(popNames(cats)))!=length(popNames(cats)))
# {
# popNames(cats) <- paste(1:length(popNames(cats)),"-",substr(popNames(cats),1,6),sep="")
# cat("Subpopulation names were not unique and therefore adjusted.\n")
# }
#
#
#set directory where to save a file, defaults to tempdir (follow R policy)
if (is.null(path.pgr))
{
path.pgr <- tempdir()
}
# setwd(path.pgr)
#create a foldername folder if not existing...
dirfiles <- list.dirs(path=path.pgr, recursive=FALSE)
if (!(tolower (file.path(path.pgr,foldername))) %in% tolower(dirfiles)) {
dir.create(file.path(path.pgr,foldername))
cat("There is no ",foldername, " folder. I am trying to create it; \notherwise please create the folder manually. \n")
}
owd <-getwd()
setwd(file.path(path.pgr, foldername))
# conversion of lat longs to google map data (Mercator (dismo) wants to have long lat)
coords=FALSE
if (is.null(cats$other$latlong) & is.null(cats@other$xy)) coords=FALSE else {
if (!is.null(cats@other$latlong)) cats@other$xy <- Mercator(cats@other$latlong[,c(2,1)])
if (!is.null(cats@other$xy)) cats@other$latlong <- Mercator(cats@other$xy, inverse=TRUE)[,c(2,1)]
if ((nrow(cats@other$latlong) == length(indNames(cats))) & (nrow(cats@other$xy) == length(indNames(cats)) )) coords=TRUE
}
# give cats a filename that can be seen in the snw chunks
cats@other$filename<- fname
cats@other$foldername<-foldername
cats@other$path <- path.pgr
#determine the type of map
if ((mk.map==TRUE | mk.complete) & coords)
{
cats@other$maptype=maptype
cats@other$mapdotcolor =mapdotcolor
cats@other$mapdotsize=mapdotsize
cats@other$mapdotalpha=mapdotalpha
cats@other$mapdottype=mapdottype
cats@other$mapzoom=mapzoom
}
###################################
##### create a new environment to run knitr in it
#pgr <- new.env(parent=.GlobalEnv)
pgr <- new.env()
assign("cats",cats,envir=pgr)
#sumcats <- summary(cats, verbose=FALSE)
#assign("sumcats",sumcats, envir=pgr )
###################################
# save the data in a tempfile
# save(cats, file=paste(foldername,"\\","tempcats.rdata",sep=""))
#check path to the snw files
path <- NULL
for(i in seq_along(.libPaths()))
{
if (file.exists(paste(.libPaths()[i],"/PopGenReport/swchunks/header.snw",sep="")))
{
path <- paste(.libPaths()[i],"/PopGenReport/swchunks/", sep="" )
break
}
}
if (is.null(path)) {cat("Could not find snw files in the PopGenReport library folder. Please check if the package is installed correctly (e.g. installed.packages()[\"PopGenReport\",2]). \n"); return;}
#for testing:
#path <- "d:\\bernd\\R\\popgenreport\\inst\\swchunks\\"
#path<- "C:\\Aaron files\\popgenreport098\\PopGenReport_0.98\\PopGenReport\\swchunks\\"
header.file <- readLines(paste(path,"header.snw",sep=""))
required<- readLines(paste(path,"required.snw",sep=""))
compl<-c(header.file,required)
cat("Compiling report...\n")
if(mk.counts | mk.complete){
cat("- General summary...\n")
overview<-readLines(paste(path,"counts.snw",sep=""))
compl<-c(compl,overview)
}
if (coords==FALSE) cat(" - No valid coordinates were provided. \n Be aware you need to provide a coordinate (or NA) for each individual\n and the coordinate heading in slot @other has to be 'latlong' or 'xy'.\n Some of the analyses require coordinates and will be skipped!\n")
if ((mk.map==TRUE | mk.complete) & coords){
cat("- Map of individuals...\n")
mapping<- readLines(paste(path,"map.snw",sep=""))
compl<-c(compl,mapping)
}
if (mk.locihz | mk.complete){
cat("- Statistics on population heterogeneity ...\n")
popheterozygosity <- readLines(paste(path,"locihz.snw",sep=""))
compl<-c(compl,popheterozygosity)
}
if (mk.allele.dist | mk.complete){
cat("- Allelic distances ...\n")
numloci<-length(cats@loc.n.all)
alleledistn <- readLines(paste(path,"allele.dist.snw",sep=""))
compl<-c(compl,alleledistn)
}
if (mk.fst| mk.complete){
cat("- Pairwise Fst ...\n")
popfst<-readLines(paste(path,"fst.snw",sep=""))
compl<-c(compl,popfst)
}
if (mk.null.all | mk.complete){
cat("- Checking for null alleles ...\n")
null.stat<-readLines(paste(path,"null.all.snw",sep=""))
compl<-c(compl,null.stat)
}
if (mk.allel.rich | mk.complete){
cat("- Allelic richness ...\n")
all.stat<-readLines(paste(path,"allel.rich.snw",sep=""))
compl<-c(compl,all.stat)
}
if (mk.differ.stats | mk.complete){
cat("- Pairwise differentiations ...\n")
diff.stat<-readLines(paste(path,"differ.stats.snw",sep=""))
compl<-c(compl,diff.stat)
}
if (mk.hwe | mk.complete){
cat("- Test for Hardy-Weinberg-Equilibrium ...\n")
cat(" !! You may get warnings when running HWE tests, if the test is based\n")
cat(" on an entry in the chi-square table which is less than five.!! \n")
popHWEll<-readLines(paste(path,"hwe.snw",sep=""))
compl<-c(compl,popHWEll)
}
if ((mk.gd.kosman==TRUE | mk.complete) & coords){
cat("- Kosman & Leonard 2005 genetic distances...\n")
kosman<-readLines(paste(path,"gd.kosman.snw",sep=""))
compl<-c(compl,kosman)
}
if ((mk.gd.smouse==TRUE | mk.complete) & coords){
cat("- Smouse & Peakall 1999 genetic distances...\n")
smouse<-readLines(paste(path,"gd.smouse.snw",sep=""))
compl<-c(compl,smouse)
}
if ((mk.spautocor==TRUE | mk.complete) & coords){
cat("- Spatial autocorrelation following Smouse & Peakall 1999 ...\n")
spa<-readLines(paste(path,"spautocor.snw",sep=""))
compl<-c(compl,spa)
}
if (mk.pcoa==TRUE | mk.complete){
cat("- Principal coordinate analysis following Jombart et al. 2009...\n")
pca<-readLines(paste(path,"pcoa.snw",sep=""))
compl<-c(compl,pca)
}
if (mk.custom==TRUE){
cat("- Run customised snw file, custom.snw ...\n")
custom<-readLines(paste(path,"custom.snw",sep=""))
compl<-c(compl,custom)
}
footer.file<-readLines(paste(path,"footer.snw",sep=""))
compl<-c(compl,footer.file)
#compl <- c(header.file, required, loaddata, mapping, popheterozygosity, footer.file)
rnwfile <- paste(fname,".rnw",sep="")
texfile <- paste(fname,".tex",sep="")
zz <- file(file.path(path.pgr,foldername,rnwfile), "w")
writeLines(compl,zz)
close(zz)
#setwd(paste(path.pgr,foldername, sep="/"))
cat(paste("Analysing data ...\n", sep=""))
#Sweave(paste(fname,".rnw",sep=""), output=paste(fname,".tex",sep=""), quiet=FALSE, driver=mydriver)
flush.console()
knit(input=rnwfile, output=texfile, quiet=TRUE, envir=pgr)
if (mk.pdf==TRUE)
{
cat(paste("Creating pdf from: ",rnwfile," ...\n",sep=""))
knit2pdf(texfile, texfile)
cat(paste("Finished.\nCheck ",fname,".pdf for results.\n", sep=""))
}
if (mk.Rcode) {
cat(paste("Creating R code from: ",rnwfile,"...\n"), sep="")
rfile <-paste(fname,".R",sep="")
purl(input=rnwfile, output=rfile)
# Stangle(paste(fname,".rnw",sep=""))
}
cat(paste("All files are available in the folder: \n",file.path(path.pgr, foldername),"\n",sep=""))
#reset working directory to previous
setwd(owd)
return(pgr$allresults)
}
|
4ef4d6590024fdb9030a310ac82af137c6198d71 | 88fc3067d1a45032b32f0f46c2618faac5f6f9cb | /R/StandardHourFactory.R | 3f7f005e9e1798f60682147103a07b08e2f431a2 | [] | no_license | AndoniMartin/eate | 78c500ebc8b3a722e29793992d46d89558438c40 | 42db9fd5d31b1dd4022a6233ebb11735c421e815 | refs/heads/master | 2016-09-01T14:18:49.822447 | 2015-06-02T14:46:01 | 2015-06-02T14:46:01 | 36,525,106 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 30 | r | StandardHourFactory.R | StandardHourFactory<-R6Class() |
9e0f3809e629872e8f264be9cc7b38d87cdd2810 | c685bdc4bebe1624a0fdc9bb956862889a3ec03c | /man/RasterToAmplDat.Rd | 4b5da944e73a3875e42b5765f5083dae33541e14 | [] | no_license | derek-corcoran-barrios/RtoAmpl | dffd0db812d86b74a80847ae0b8db2eb0f1c861c | 62a2f07b87f2b6d11eb3222ade6e7f1ad9b642dd | refs/heads/master | 2020-06-26T04:46:16.622097 | 2017-11-24T17:28:58 | 2017-11-24T17:28:58 | 97,002,573 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,254 | rd | RasterToAmplDat.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/funcs.R
\name{RasterToAmplDat}
\alias{RasterToAmplDat}
\title{Generates an AMPL dat file from a Stack}
\usage{
RasterToAmplDat(Stack, maxalpha = 10, maxbiomass = 2, maxcapacidad = 10,
name = "Stack", Dist = 1e+06, Threshold, costlayer)
}
\arguments{
\item{Stack}{a raster with the space where the species will be inhabiting}
\item{maxalpha}{the maximum rate of change of the population in optimal
coditions, defaults in 10}
\item{maxbiomass}{the maximum initial biomass of the population in optimal
coditions, defaults in 2}
\item{maxcapacidad}{the maximum biomass of the population in optimal coditions,
defaults in 10}
\item{name}{the name of the .dat file that will be exported, defaults in
stack}
\item{Dist}{the maximum dispersal distance of the species modeled in the
stack}
}
\value{
exports a .dat file to feed the AMPL model
}
\description{
Generates an AMPL dat file from a Stack in which each file is the projection
of a species distribution model into a time slice
}
\examples{
data("univariate")
RasterToAmplDat(Stack = univariate, Threshold = 0.5)
}
\author{
Derek Corcoran <derek.corcoran.barrios@gmail.com>
Javier Fajardo <javierfajnolla@gmail.com >
}
|
8009055de8877059965ad38cca02198491152a74 | 2a64af0f612c5fc3ca6fbfc79ecb6b95beccbc51 | /Scripts/1a_pairwise_mediation.R | 5e69d4ee2cf04282e40e278b4269aabd6520f733 | [] | no_license | weidandan123456/environmental_mediation_framework | 44f973df4a55e12d2944f23c2f23742cad579c31 | 9ef240362521cefa44d9035eb65e6e2a2b9500ca | refs/heads/master | 2023-03-17T08:15:28.196065 | 2020-09-20T22:12:36 | 2020-09-20T22:12:36 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,802 | r | 1a_pairwise_mediation.R | library(stats)
library(epicalc)
library(Hmisc)
library(Epi)
library(mediation)
d1<-read.csv("dataset.csv")
d1<-na.omit(d1) #ensure your data is complete with no missing observations
#order your dataset's columns by: exposures, mediators, follwed by covariates and outcome
#transform your exposures and mediators as you see fit/necessary according normality assumptions
nexp<- #define number of exposure analytes in your dataset
nmed<- #define number of mediators in your dataset
ncovars<- #define number of covariates and outcome variable in your dataset
med.results<-as.data.frame(matrix(nrow=(nexp*nmed),ncol=41))
colnames(med.results)<-c('nobs', 'ACME.C','ACME.C.lo','ACME.C.hi','ACME.C.Pval','ACME.T','ACME.T.lo',
'ACME.T.hi','ACME.T.pval','ADE.C','ADE.C.lo','ADE.C.hi','ADE.C.Pval','ADE.T',
'ADE.T.lo','ADE.T.hi','ADE.T.pval','PMed.C','PMed.C.lo','PMed.C.hi','PMed.C.pval',
'PMed.T','PMed.T.lo','PMed.T.hi','PMed.T.pval','TE','TE.lo','TE.hi','TE.pval',
'ACME.avg','ACME.avg.lo','ACME.avg.hi','ACME.avg.pval','ADE.avg','ADE.avg.lo',
'ADE.avg.hi','ADE.avg.pval','PMed.avg','PMed.avg.lo','PMed.avg.hi','PMed.avg.pval')
#Loop to conduct pairwise mediation with multiple exposures and mediators
#Loop repeatedly subsets dataset d1 into d2 for individual pairs of exposures and biomarkers
k=1
for(i in 1:nexp){
for(j in (nexp+1):(nexp+nmed)){
d2<-d1[,c(i,j,((nexp+nmed+1):(nexp+nmed+ncovars)))]
set.seed(111)
#define your covariates as needed
m<-lm(d2[,2]~d2[,1]+d2$covariate1+d2$covariate2+d2$covariate3+factor(d2$covariate4),data=d2)
#define your outcome variable below
y<-lm(d2$outcome~d2[,1]+d2[, 2]+d2$covariate1+d2$covariate2+d2$covariate3+factor(d2$covariate4),data=d2)
med<-mediate(m,y,sims=2000,treat="d2[, 1]",mediator="d2[, 2]")
med.results[k,]<-cbind(nobs(y),med$d0, med$d0.ci[1], med$d0.ci[2], med$d0.p, med$d1, med$d1.ci[1],
med$d1.ci[2], med$d1.p, med$z0, med$z0.ci[1],med$z0.ci[2], med$z0.p, med$z1,
med$z1.ci[1], med$z1.ci[2], med$z1.p, med$n0, med$n0.ci[1], med$n0.ci[2],
med$n0.p, med$n1, med$n1.ci[1], med$n1.ci[2], med$n1.p, med$tau.coef, med$tau.ci[1],
med$tau.ci[2], med$tau.p, med$d.avg, med$d.avg.ci[1], med$d.avg.ci[2], med$d.avg.p,
med$z.avg, med$z.avg.ci[1], med$z.avg.ci[2], med$z.avg.p, med$n.avg, med$n.avg.ci[1],
med$n.avg.ci[2], med$n.avg.p)
rownames(med.results)[k]<-paste(colnames(d2)[1],colnames(d2)[2],sep='.')
print(k)
print(rownames(med.results)[k])
k=k+1
}
}
write.csv(med.results,'med.results.csv')
|
db112d7e492fc577b848075739963d7c59f0618c | 9d940f8b98189cbf465b330c142facaeb22d1552 | /R-batchJob_revision-n10_makeSCEs-nucleiCalling_MNT.R | 74fda549a7fc193d52a5f4c3a913fe3150691f68 | [] | no_license | LieberInstitute/10xPilot_snRNAseq-human | 3166cbe55d956170a7528d9f9929b3f835ef630a | 51d15ef9f5f2c4c53f55e22e3fe467de1a724668 | refs/heads/master | 2023-04-12T06:32:12.228489 | 2022-07-15T23:57:55 | 2022-07-15T23:57:55 | 248,090,643 | 18 | 7 | null | null | null | null | UTF-8 | R | false | false | 3,783 | r | R-batchJob_revision-n10_makeSCEs-nucleiCalling_MNT.R | ################################################################################
### LIBD 10x snRNA-seq [pilot] revision (n=10)
### STEP 01.batchJob: Read in SCEs and perform nuclei calling (`emptyDrops()`)
### Initiated: MNT 25Feb2021
################################################################################
library(SingleCellExperiment)
library(scRNAseq)
library(batchelor)
library(EnsDb.Hsapiens.v86)
library(scater)
library(scran)
library(uwot)
library(DropletUtils)
library(jaffelab)
library(Rtsne)
library(gridExtra)
library(rtracklayer)
#### AS SUBMITTED JOB ====
### Read in (2021) 'samples.manifest' for streamlining
samples.revision <- read.table("/dcs04/lieber/lcolladotor/rawDataTDSC_LIBD001/raw-data/2021-10-15_Tran2021_published/Feb2021/samples.manifest",
sep="\t", header=F)$V1
# Make list of paths
paths.rawCounts <- c(paste0("/dcl01/ajaffe/data/lab/singleCell/10x_pilot/premRNA/Feb2021/",
samples.revision,"/outs/raw_feature_bc_matrix"))
# Simpler names for individual SCEs
names(paths.rawCounts) <- gsub("_",".", tolower(samples.revision))
## Read in raw UMI x barcode matrix - **use pre-mRNA-aligned reads
pilot.data.2 <- lapply(paths.rawCounts, function(x){ read10xCounts(x, col.names=TRUE) })
names(pilot.data.2) <- names(paths.rawCounts)
### Gene annotation (from scater) ===
# Pull in GTF information
gtf = import("/dcl01/ajaffe/data/lab/singleCell/refdata-cellranger-GRCh38-3.0.0/genes/genes.gtf")
gtf = gtf[gtf$type == "gene"]
length(gtf)
names(gtf) = gtf$gene_id
table(names(gtf) == rowData(pilot.data.2[[1]])$ID)
seqlevels(gtf)[1:25] = paste0("chr", seqlevels(gtf)[1:25])
mcols(gtf) = mcols(gtf)[,c(5:9)]
for(i in 1:length(pilot.data.2)){
rowRanges(pilot.data.2[[i]]) <- gtf
# Because some gene names are the same:
rownames(pilot.data.2[[i]]) <- uniquifyFeatureNames(rowData(pilot.data.2[[i]])$gene_id, rowData(pilot.data.2[[i]])$gene_name)
rowData(pilot.data.2[[i]])$Symbol.uniq <- rownames(pilot.data.2[[i]])
}
# Preliminary save
save(pilot.data.2, file="rdas/revision/all-FACS-n10_2021rev_SCEs_processing-QC_MNTMar2021.rda")
### Quality control ============================================================
## - Going to ignore the adaptive NMAD-approach to outlier detection for UMI/feature count
# because this hasn't been as straightforward in past experience (might throw away neurons)
## - Vignette for the 10x PBMC dataset (OSCA Ch.24) only does mito & droplet QC anyhow
# - (mention that for a sample with very heterogeneous cell comp., don't want
# to drop potential cells with low RNA content)
## Cell detection (droplet exclusion, rather)
# Can use UMI count vs barcode rank (knee/inflection plot) to decide threshold, but
# "this unnecessarily discards libraries derived from cell types with low RNA content" (OSCA, Ch. 6)
# -> Instead should prefer this Monte Carlo-simulation-based empty droplet test:
# Additionally:
# For any Sig==FALSE & Limited==TRUE, may need to increase n iterations (default = 10000) with 'niters='
# - this field = whether "the computed p-value for a...barcode is bounded by the number of iterations"
# -> In exploratory phase (preprint), not all samples passed with niters=15000 (default 10,000), so use 20,000
e.out.2 <- list()
for(i in 1:length(pilot.data.2)){
cat(paste0("Simulating empty drops for: ",names(pilot.data.2)[i],"... \n"))
set.seed(109)
e.out.2[[i]] <- emptyDrops(counts(pilot.data.2[[i]]), niters=20000)
cat(paste0("\n\t...Simulations complete. \n\t", date(), "\n\n\n"))
date()
}
names(e.out.2) <- names(pilot.data.2)
save(pilot.data.2, e.out.2, file="rdas/revision/all-FACS-n10_2021rev_SCEs_processing-QC_MNTMar2021.rda")
rm(list=ls())
sessionInfo()
|
70e4e54e6d09ae00a7c7d9d47622e20bb7534f37 | 29fc3cc2d21a2845237323f99c1eb16b98e6101f | /RandomForest.R | 02a5529ee9edd2ed42c94860eadc2a6d5b2b192d | [] | no_license | benchen83/ETCproject | 8848754bb4bf29f0c275c553c0460b511e65f5d6 | 398a83c9caa6bfa87ed5971c40a98f9422902601 | refs/heads/master | 2021-07-11T07:28:58.240064 | 2017-10-15T06:26:44 | 2017-10-15T06:26:44 | 103,204,541 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 5,752 | r | RandomForest.R | library(dplyr)
library(reshape2)
library(randomForest)
library(ggplot2)
dataOringin <- read.csv("D:/vargrant/project/raw312015-16.csv",header = FALSE)
#給欄位名稱
names(dataOringin) <- c("RecordT","start","end","type","time","number")
#建立國定假日向量
holidayc <- c("2015/01/01","2015/01/02","2015/01/03","2015/01/04","2015/02/18","2015/02/19",
"2015/02/20","2015/02/21","2015/02/22","2015/02/23","2015/02/27","2015/02/28",
"2015/03/01","2015/04/03","2015/04/04","2015/04/05","2015/04/06","2015/05/01",
"2015/05/02","2015/05/03","2015/06/19","2015/06/20","2015/06/21","2015/09/26",
"2015/09/27","2015/09/28","2015/10/09","2015/10/10","2015/10/11",
"2016/01/01","2016/01/02","2016/01/03","2016/02/06","2016/02/07","2016/02/08",
"2016/02/09","2016/02/10","2016/02/11","2016/02/12","2016/02/13","2016/02/14",
"2016/02/27","2016/02/28","2016/02/29","2016/04/02","2016/04/03","2016/04/04",
"2016/04/05","2016/06/09","2016/06/10","2016/06/11","2016/06/12","2016/09/15",
"2016/09/16","2016/09/17","2016/09/18","2016/10/09","2016/10/10","2016/10/11")
#新增站名欄位
data <- local({
dataOringin %>%
mutate("F233N" = as.character((dataOringin$end=="01F0233N")),
"F256N" = as.character((dataOringin$end=="01F0256N")),
"F293N" = as.character((dataOringin$end=="01F0293N")),
"F339N" = as.character((dataOringin$end=="01F0339N")),
"F376N" = as.character((dataOringin$end=="01F0376N")),
"F413N" = as.character((dataOringin$end=="01F0413N")),
"F467N" = as.character((dataOringin$end=="01F0467N")),
"F509N" = as.character((dataOringin$end=="01F0509N")),
"F532N" = as.character((dataOringin$end=="01F0532N")),
"F557N" = as.character((dataOringin$end=="01F0557N")),
"F584N" = as.character((dataOringin$end=="01F0584N")),
"F633N" = as.character((dataOringin$end=="01F0633N")),
"F664N" = as.character((dataOringin$end=="01F0664N")),
"F681N" = as.character((dataOringin$end=="01F0681N")),
"F750N" = as.character((dataOringin$end=="01F0750N")),
"F880N" = as.character((dataOringin$end=="01F0880N")))
})
#轉換模式
trans <- local({
trans <- c("1","0")
names(trans) <- c(TRUE,FALSE)
trans
})
#station <- c("F233N","F256N","F293N","F339N","F376N","F413N","F467N","F509N","F532N","F557N","F584N","F633N","F664N","F681N","F750N","F880N","F928N")
#轉換成1 0
data$F233N <- trans[data$F233N]
data$F256N <- trans[data$F256N]
data$F293N <- trans[data$F293N]
data$F339N <- trans[data$F339N]
data$F376N <- trans[data$F376N]
data$F413N <- trans[data$F413N]
data$F467N <- trans[data$F467N]
data$F509N <- trans[data$F509N]
data$F532N <- trans[data$F532N]
data$F557N <- trans[data$F557N]
data$F584N <- trans[data$F584N]
data$F633N <- trans[data$F633N]
data$F664N <- trans[data$F664N]
data$F681N <- trans[data$F681N]
data$F750N <- trans[data$F750N]
data$F880N <- trans[data$F880N]
head(data)
#把30分鐘內變成一群、並把國定練續假日篩掉
minn <- c("00","05","10","15","20","25")
data1 <- local(
data %>%
mutate(hour = substring(data$RecordT,12,13),
miniute = ifelse(substring(data$RecordT,15,16) %in% minn,"00","30"),
date = substring(data$RecordT,1,10),
holiday = ifelse(date %in% holidayc,1,0)) %>%
filter(holiday==0) %>%
select(-RecordT,-start,-end,-type,-holiday) %>%
arrange(date)
)
#日期轉換星期
data1$date <- as.Date(data1$date)
data1$date <- weekdays(data1$date)
#chr轉換成factor
for(i in c(3:21)){
data1[[i]]<-as.factor(data1[[i]])
}
# #檢查
str(data1)
# #匯出
# write.csv(x=data1,file = "D:/vargrant/project/randomforestdataset.csv")
#切割訓練資料與測試資料
smap <- sample(x = 1:nrow(data1),size = nrow(data1)*0.08)
train <- data1[smap,]
test <- data1[-smap,-1]
testans <- data1[-smap,1]
head(train)
#建模
modelrandomfroest <- randomForest(time~.-time,data = train,importance=TRUE, na.action=na.omit)
#帶入測試資料
pred <- predict(object = modelrandomfroest,test)
pred <- as.data.frame(pred)
testans <- as.data.frame(testans)
#測試結果與測試資料答案合併
table <- cbind(testans,pred)
table <- local({
table %>%
mutate(differ = round(abs(pred -testans),2),rat =(differ/testans)*100)
})
View(train)
str(test)
# summarise(table,me=mean(rat))
# nrow(table[table$rat>10,])/nrow(table)
# summarise(table,me=mean(differ*(1/testans)))
g <- ggplot(data1,aes(x=number,y=time))
g+geom_point(aes(colour=holiday))
nrow(data1[data1$holiday=="0",])+nrow(data1[data1$holiday=="1",])
saveRDS(modelrandomfroest, "D:/vargrant/project/model0928.rds")
trymodel <- readRDS("D:/vargrant/project/model.rds")
identical(modelrandomfroest, trymodel, ignore.environment = TRUE)
#
# Call:
# randomForest(formula = time ~ . - time, data = train, mtry = 3, importance = TRUE, na.action = na.omit)
# Type of random forest: regression
# Number of trees: 500
# No. of variables tried at each split: 3
#
# Mean of squared residuals: 5247.288
# % Var explained: 72.35
#
#
#
# Call:
# randomForest(formula = time ~ . - time, data = train, mtry = 3, importance = TRUE, na.action = na.omit)
# Type of random forest: regression
# Number of trees: 500
# No. of variables tried at each split: 3
#
# Mean of squared residuals: 5313.775
# % Var explained: 72.21
#
# Call:
# randomForest(formula = time ~ . - time, data = train, importance = TRUE, na.action = na.omit)
# Type of random forest: regression
# Number of trees: 500
# No. of variables tried at each split: 6
#
# Mean of squared residuals: 4776.164
# % Var explained: 75.3
|
260534476150da67e715a25d304f8bbdfebe5d40 | 446373433355171cdb65266ac3b24d03e884bb5d | /R/saga_diffusivehillslopeevolutionadi.R | 974f30257d583f65b99dde99310fade377cb14ee | [
"MIT"
] | permissive | VB6Hobbyst7/r_package_qgis | 233a49cbdb590ebc5b38d197cd38441888c8a6f3 | 8a5130ad98c4405085a09913b535a94b4a2a4fc3 | refs/heads/master | 2023-06-27T11:52:21.538634 | 2021-08-01T01:05:01 | 2021-08-01T01:05:01 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,358 | r | saga_diffusivehillslopeevolutionadi.R | ##' QGIS Algorithm provided by SAGA Diffusive hillslope evolution (adi) (saga:diffusivehillslopeevolutionadi)
##'
##' @title QGIS algorithm Diffusive hillslope evolution (adi)
##'
##' @param DEM `raster` - Elevation. Path to a raster layer.
##' @param CHANNELS `raster` - Channel Mask. Path to a raster layer.
##' @param UPDATE `boolean` - Update. 1 for true/yes. 0 for false/no.
##' @param KAPPA `number` - Diffusivity (m2/kyr). A numeric value.
##' @param DURATION `number` - Simulation Time (kyr). A numeric value.
##' @param TIMESTEP `enum` of `("[0] user defined", "[1] automatically")` - Time Step. Number of selected option, e.g. '1'. Comma separated list of options, e.g. '1,3'.
##' @param DTIME `number` - Time Step (kyr). A numeric value.
##' @param MODEL `rasterDestination` - Modelled Elevation. Path for new raster layer.
##' @param DIFF `rasterDestination` - Elevation Difference. Path for new raster layer.
##' @param ... further parameters passed to `qgisprocess::qgis_run_algorithm()`
##' @param .complete_output logical specifing if complete out of `qgisprocess::qgis_run_algorithm()` should be used (`TRUE`) or first output (most likely the main) should read (`FALSE`). Default value is `TRUE`.
##'
##' @details
##' ## Outputs description
##' * MODEL - outputRaster - Modelled Elevation
##' * DIFF - outputRaster - Elevation Difference
##'
##'
##' @export
##' @md
##' @importFrom qgisprocess qgis_run_algorithm qgis_default_value
saga_diffusivehillslopeevolutionadi <- function(DEM = qgisprocess::qgis_default_value(), CHANNELS = qgisprocess::qgis_default_value(), UPDATE = qgisprocess::qgis_default_value(), KAPPA = qgisprocess::qgis_default_value(), DURATION = qgisprocess::qgis_default_value(), TIMESTEP = qgisprocess::qgis_default_value(), DTIME = qgisprocess::qgis_default_value(), MODEL = qgisprocess::qgis_default_value(), DIFF = qgisprocess::qgis_default_value(),..., .complete_output = TRUE) {
check_algorithm_necessities("saga:diffusivehillslopeevolutionadi")
output <- qgisprocess::qgis_run_algorithm("saga:diffusivehillslopeevolutionadi", `DEM` = DEM, `CHANNELS` = CHANNELS, `UPDATE` = UPDATE, `KAPPA` = KAPPA, `DURATION` = DURATION, `TIMESTEP` = TIMESTEP, `DTIME` = DTIME, `MODEL` = MODEL, `DIFF` = DIFF,...)
if (.complete_output) {
return(output)
}
else{
qgisprocess::qgis_output(output, "MODEL")
}
} |
914d34b803e08c137cfdad54f0185ac277bf5d94 | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/Eagle/R/OpenGUI.R | 2fd2c2535d75328b42db9128fb37a94a33cbd6f8 | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | R | false | false | 970 | r | OpenGUI.R | #' @title Browser-based Graphical User Interface
#' @description Opens a web browser to act as a user-friendly interface to 'Eagle'
#' @details
#' Once \code{OPenGUI} is run, your default web-browser will open automatically the Eagle GUI. We have written our GUI in html code.
#' The GUI allows users to input data files, analyse data, summarise findings, and view results via interactive plots. We
#' have designed the GUI for users whom may be unfamilar with R and wishing to avoid having to write R code.
#'
#'
#' Note, that even though a web browser is being used as the user interface, everything remains local to the computer.
#' @examples
#'\dontrun{
#'# opens a web browser
#' OpenGUI()
#'}
#'
OpenGUI <- function() {
appDir <- system.file('shiny_app', package = 'Eagle')
if (appDir == "") {
message("Could not find shiny-app directory. Try re-installing `Eagle` package.")
return(NULL)
}
shinyAppDir(appDir, options=list(port = 3838))
}
|
9f3b1f519ea5909436aa9097be854c61d2311c38 | e534f1251b0611b7e44d130fc5ce00e9e8b28916 | /man/body_type.Rd | 0113a21bededa579035022a4269b831f56dd9082 | [
"MIT"
] | permissive | gahoo/ross | 9116c960bd74fcbb68686256fc6787063c429cfb | d613630ecb2819e4be38679d699239fe944e0393 | refs/heads/master | 2021-01-22T19:05:07.001927 | 2017-08-03T09:16:51 | 2017-08-03T09:16:51 | 85,161,274 | 2 | 0 | null | null | null | null | UTF-8 | R | false | true | 206 | rd | body_type.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/helper.R
\name{body_type}
\alias{body_type}
\title{Title}
\usage{
body_type(x)
}
\arguments{
\item{x}{}
}
\description{
Title
}
|
a76680fdc3b2f4b22ef1dca88445e34864597aa7 | 54bf9bc76aaa7e1fec5961efb12bfb636fa90a2e | /Archive/test.code/fsc.testing/fsc test script.R | c4ed6164f57e0436f616a188b85d905bbb142c05 | [] | no_license | christianparobek/skeleSim | 25d63dc3eeee6d8218d19e0f011229cfb843d053 | 0d61409497283ac1db129379b479639261695f83 | refs/heads/master | 2020-03-28T05:36:45.448623 | 2020-02-26T21:55:51 | 2020-02-26T21:55:51 | 32,469,895 | 3 | 9 | null | 2017-11-22T16:30:16 | 2015-03-18T16:16:29 | HTML | UTF-8 | R | false | false | 650 | r | fsc test script.R | rm(list = ls())
source("fsc code.r")
pop.info <- fsc.popInfo(
pop.size = c(20000, 5000, 10000),
sample.size = c(20, 20, 6),
sample.times = c(0, 0, 1500)
)
locus.params <- fsc.locusParams(
locus.type = "snp",
mut.rate = 1e-5,
num.loci = 1000
)
f <- fsc.run(
pop.info,
locus.params,
mig.rates = matrix(
c(0, 0.01, 0.05, 0.025, 0, 0.025, 0.05, 0.01, 0), nrow = 3
),
hist.ev = fsc.histEvMat(
num.gen = c(2000, 2980, 3000, 15000),
source.deme = c(1, 1, 1, 0),
sink.deme = c(2, 1, 0, 2),
prop.migrants = c(0.05, 0, 1, 1),
new.sink.size = c(1, 0.04, 1, 3),
new.sink.growth = 0,
new.mig.mat = 0
)
)
|
999814b14d929f01881449aebe97ecd089884fae | 788bf2c506ac0b8042e3ae1857fc80a629699ecb | /run_analysis.R | 5902f18c35d806a0bd80ce6869163e9c7b86fc9d | [] | no_license | ngerew/getting-and-cleaning-courseProject | 4578f3e8a424a854217a32f9c16fbf904e5ad58a | 9c71bc8c41474e7c72c127248ec339852aea5f5c | refs/heads/master | 2021-01-16T20:55:23.452361 | 2015-01-25T21:22:06 | 2015-01-25T21:22:06 | 29,827,133 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 3,458 | r | run_analysis.R | ## Step 1: Merge the training and test sets to create one data set
## Load the Test and Training files (data, labels, and subjects)
## Add the Test labels and Test subject IDs to the Test data, and
## similarly for the Training data.
X_train <- read.table("UCI HAR Dataset/train/X_train.txt")
X_test <- read.table("UCI HAR Dataset/test/X_test.txt")
subject_train<-read.table("UCI HAR Dataset/train/subject_train.txt")
Y_train <- read.table("UCI HAR Dataset/train/y_train.txt")
Y_test <- read.table("UCI HAR Dataset/test/y_test.txt")
subject_test<-read.table("UCI HAR Dataset/test/subject_test.txt")
Train_data <- cbind(X_train, subject_train, Y_train)
Test_data <- cbind(X_test, subject_test, Y_test)
## Append the Test data to the Train data to make one data set
Combined_data <- rbind(Train_data, Test_data)
## Step 2: Extract only the measurements on the mean and sd for each measurement
## Load the features labels and identify the elements of the features vector that
## should be extracted (those providing the means and standard deviations for
## each measurement)
features <- read.table("UCI HAR Dataset/features.txt", stringsAsFactors = FALSE)
features$Mean <- grepl("mean()", features[, 2], fixed = TRUE)
features$SD <- grepl("std()", features[, 2], fixed = TRUE)
features$MeanOrSD <- (features$Mean | features$SD)
## Create the extract with only these means and sd's of measurements,
## along with the the subject and Activity IDs (the last two variables in the frame)
keep_indicator <- features[features$MeanOrSD, 1]
data_extract <- Combined_data[, c(keep_indicator, 562, 563)]
## Step 3: Use descriptive activity names to name the activities in the data set
## Replace the Y_test and Y_train IDs with the corresponding activity description
## from the activity_labels.txt file
activity_labels <- read.table("UCI HAR Dataset/activity_labels.txt", stringsAsFactors = FALSE)
for (i in 1:6) {
data_extract[data_extract[ , 68] == i, 68] <- activity_labels[i, 2]
}
## Step 4: Appropriately label the data set with descriptive variable names
## Variable names are based on the descriptive names in the features.txt file,
## with some necessary and helpful modifications (removing parentheses and hyphens).
## Means are indicated by .mean and SD's by .sd. Additional detail is available
## in the codebook.
features$V2 <- gsub("-mean()-", ".mean.", features$V2, fixed = TRUE)
features$V2 <- gsub("-std()-", ".sd.", features$V2, fixed = TRUE)
features$V2 <- gsub("-mean()", ".mean", features$V2, fixed = TRUE)
features$V2 <- gsub("-std()", ".sd", features$V2, fixed = TRUE)
features$V2 <- gsub("BodyBody", "Body", features$V2, fixed = TRUE)
clean_names <- features[features$MeanOrSD, 2]
## Add these cleaned descriptive names to the data set extract, including names
## for the Subject and Activity IDs
colnames(data_extract) <- c(clean_names, "subject", "activity")
## Step 5: From this data set in Step 4, create a second, independent tidy data set
## with the average of each variable for each activity and each subject
## This tidy data set will be a wide data set with the average value for
## each of the 66 measurements in the data extract for each subject and activity.
## This uses melt and cast from the reshape library.
library(reshape)
melted <- melt(data_extract, id = c("subject", "activity"))
tidy_data <- cast(melted, fun.aggregate = mean)
write.table(tidy_data, file ="tidy_data.txt", row.names = FALSE)
|
d4251613889d74bc6f7f12b724c79d89539a3c4c | 11394cd22cea3b4e644d20564ff4b500018d943e | /scripts/separateAnalysis/scTransform.R | d188579ecbbf287c0a29f3a3db7ce595c0c940db | [
"MIT"
] | permissive | shunsunsun/single_cell_rna_seq_snakemake | 3d153c9cb7db9988917aff38991217a35940aa64 | f275546eb3bd63d5d535a13407ce47ee36e94cae | refs/heads/master | 2023-04-17T08:44:13.954986 | 2021-04-27T08:13:50 | 2021-04-27T08:13:50 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,675 | r | scTransform.R | suppressPackageStartupMessages(library(Seurat))
suppressPackageStartupMessages(library(future))
args <- commandArgs(trailingOnly=T)
infile <- args[1]
outfile <- args[2]
outdir <- dirname(outfile)
if(!dir.exists(outdir)){
dir.create(outdir,recursive=T)
}
regVars=c('mitoCountRatio', 'nFeature_RNA', 'nCount_RNA', 'percent_mito', 'percent.mt')
nworker <- min(as.numeric(args[3]),length(availableWorkers()))
#cat(sprintf("Use %d workders\n",nworker))
## Read input
flted_se <- readRDS(infile)
regVars=intersect(regVars,colnames(flted_se[[]]))
## Load cell cycle markers
load(file="/gpfs2/gaog_pkuhpc/users/liny/GEJ_singleCell/resources/cycle.rda")
plan("multiprocess", workers = nworker)
options(future.globals.maxSize = 20*1024^3) #20G
set.seed(1129L)
# https://github.com/immunogenomics/harmony/issues/41#issuecomment-633885490
# if samples from different technical platforms, try https://github.com/immunogenomics/harmony/issues/41#issuecomment-642862186
tryCatch({
tmp <- SCTransform(flted_se, assay = 'RNA', new.assay.name = 'SCT', vars.to.regress = regVars)
tmp <- CellCycleScoring(tmp, s.features = s_genes, g2m.features = g2m_genes, assay = 'SCT', set.ident = TRUE)
tmp$cc_difference <- tmp$S.Score - tmp$G2M.Score
normed_se <- SCTransform(tmp, assay = 'RNA', new.assay.name = 'SCT', variable.features.n=5000, vars.to.regress = c(regVars, 'cc_difference'))
}, error=function(cond){
cat(sprintf("No cell cycle scoring due to %s",cond))
normed_se <- SCTransform(flted_se, variable.features.n=5000, vars.to.regress = regVars)
})
saveRDS(normed_se, file=outfile)
options(future.globals.maxSize = 500*1024^2) #500M
plan(sequential)
|
b354e2cc8c5491811a8b6a6f35153323ded3ae41 | 8deecae4652ec0500c9d92aef9a3f63e9a8290b2 | /RHESSysPreprocessing/R/build_meta.R | b72c96b05d90063741259c1c5af8081e9b2c5823 | [] | no_license | ejhanan/RHESSys | 617853cbc33999f6f04bcd1b743d154aacec5568 | 8f4e77bebc266d8ac7381a0baa643a10537f1075 | refs/heads/mpi | 2022-03-10T19:32:19.282644 | 2019-09-17T18:36:37 | 2019-09-17T18:36:37 | 29,102,137 | 5 | 7 | null | 2020-05-20T18:13:31 | 2015-01-11T18:58:35 | C++ | UTF-8 | R | false | false | 3,196 | r | build_meta.R | #' build_meta
#'
#' Create documentation/metadata for RHESSys Preprocessing. 2/27/18
#' @param name Name and path for metadata. ".meta" will be appended automatically.
#' @return Writes metadata with name and path indicated in name
#' @author Will Burke
#'
# Include: spatial data used for each input, original source? , author, computer used, date time, worldfile and flownet produced
build_meta = function(name,
world = NULL,
flow = NULL,
template,
type,
typepars,
cf_maps,
streams = NULL,
roads = NULL,
impervious = NULL,
roofs = NULL,
asp_rule = NULL) {
#---------- Build table ----------
table_name = paste(name,".meta",sep="")
template_list = template_read(template)
vars = c(
"Project Name",
"Template",
"Worldfile",
"Flowtable",
"Author",
"Computer",
"Datetime",
"GIS Type",
"Map Path",
"gisBase",
"home",
"gisDbase",
"location",
"mapset",
"world",
"basin",
"zone",
"hillslope",
"patch",
"strata",
"streams",
"roads",
"impervious",
"roofs",
"asp_rule",
"z",
"slope",
"aspect",
"e_horizon",
"w_horizon",
"gw.storage",
"veg_parm_ID",
"soil_parm_ID",
"landuse_parm_ID"
)
meta_out = matrix(ncol = 2, nrow = length(vars))
meta_out[,1] = vars
colnames(meta_out) = c("varname", "value")
rownames(meta_out) = vars
#----------- System info ----------
get_sys = Sys.info()
meta_out["Author", 2] = get_sys["user"]
meta_out["Computer", 2] = get_sys["nodename"]
meta_out["Datetime", 2] = as.character(Sys.time())
#---------- Map info ----------
meta_out["Project Name",2] = basename(name)
meta_out["Worldfile",2] = world
meta_out["Template",2] = template
meta_out["Flowtable",2] = flow
if (type == "Raster" | type == "raster" | type == "RASTER") {
meta_out["GIS Type", 2] = "Raster"
meta_out["Map Path", 2] = paste(getwd(),typepars,sep="")
} else{
meta_out["GIS Type", 2] = type
meta_out["gisBase", 2] = typepars[1]
meta_out["home", 2] = typepars[2]
meta_out["gisDbase", 2] = typepars[3]
meta_out["location", 2] = typepars[4]
meta_out["mapset", 2] = typepars[5]
}
if(!is.null(roads)){meta_out["roads",2] = roads}
if(!is.null(impervious)){meta_out["impervious",2] = impervious}
if(!is.null(roofs)){meta_out["roofs",2] = roofs}
if(!is.null(streams)){meta_out["streams",2] = streams}
if(!is.null(asp_rule)){meta_out["asp_rule",2] = asp_rule}
for (i in which(meta_out[,1] =="z"):length(meta_out[,1])) {
if(meta_out[i,1] %in% template_list[[5]][,1]){
meta_out[i,2] = template_list[[5]][template_list[[5]][,1]==meta_out[i,1],2]
} else if(sum(meta_out[i,1] == template_list[[2]])==1) {
meta_out[i,2] = template_list[[1]][[which(meta_out[i,1] == template_list[[2]])]][3]
}
}
write.table(meta_out,file = table_name,row.names = FALSE)
print(paste("Created metadata:",table_name),quote=FALSE)
}
|
e116151c67ce83aca68778ca776945e056ce69cc | 2f226e35b564eb8e90a284cead44d95c2e711947 | /tests/testthat/test-comparison.R | 1854dada7215cf6fabf9f665442eb0fd86c6837f | [] | no_license | cran/sistec | 90e6646e817144f3ae803856966093308cf8554c | c38b2558ed97d7285a90b40d106a2b418bd11c26 | refs/heads/master | 2023-01-05T05:09:36.435285 | 2020-10-26T21:20:02 | 2020-10-26T21:20:02 | 263,170,067 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 528 | r | test-comparison.R | context("sistec compare")
test_that("compare_sistec works", {
skip_on_cran()
sistec_path <- system.file("extdata/test_datasets/sistec", package = "sistec")
qacademico_path <- system.file("extdata/test_datasets/qacademico", package = "sistec")
linked_courses_path <- system.file("extdata/examples/linked_courses", package = "sistec")
qacademico <- read_rfept(qacademico_path)
sistec <- read_sistec(sistec_path)
comparison <- compare_sistec(sistec, qacademico)
check_comparison(comparison)
})
|
b4d451ea9c6ead1d9ada510c457bcaf50e0fa23d | 1e0f0108e38347b556782aeeb9f13c62fdaf0fd1 | /run_analysis.R | b615fa524bc7bbffad6c36e67681b6b55adb00fe | [] | no_license | aanjaneyam/getdata-010-project | 27e175a71f73fb6c7ee77928f19aae364028c01d | 35161bbb5b39ea12060b87db39488cf372e031e9 | refs/heads/master | 2016-09-10T22:45:05.929892 | 2015-01-25T23:00:00 | 2015-01-25T23:00:00 | 29,300,051 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 5,774 | r | run_analysis.R | ##################################################################
# Download the project file into folder named project_data
##################################################################
# if folder project_data does not exist creat it.
if(!file.exists("./project_data")){
dir.create("./project_data")
}
# Download the project file getdata-projectfile_UCI HAR Dataset.zip
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
destfile <- "./project_data/getdata-projectfile_UCI_HAR_Dataset.zip"
download.file(fileUrl, destfile, method = "curl")
dateDownloaded <- date()
dateDownloaded
##################################################################
# Unzip the file downloaded file and place all its content in UCI HAR Dataset directory
##################################################################
unzip(destfile, exdir="./project_data")
##################################################################
#### To complete the project we just need the the following files from the data (files in the "Inertial Signals" directory are not needed as they do not have mean and std measurements)
#UCI HAR Dataset/test/subject_test.txt
#UCI HAR Dataset/test/X_test.txt
#UCI HAR Dataset/test/y_test.txt
#UCI HAR Dataset/train/subject_train.txt
#UCI HAR Dataset/train/X_train.txt
#UCI HAR Dataset/train/y_train.txt
#UCI HAR Dataset/features.txt
#UCI HAR Dataset/activity_labels.txt
##################################################################
message("### reading and processing data, please wait...")
##################################################################
# Load data
##################################################################
# read test dataset's activity, features and subjects
test_data_activity <- read.table("./project_data/UCI HAR Dataset/test/y_test.txt")
test_data_features <- read.table("./project_data/UCI HAR Dataset/test/X_test.txt")
test_data_subject <- read.table("./project_data/UCI HAR Dataset/test/subject_test.txt")
# read train dataset's activity, features and subjects
train_data_activity <- read.table("./project_data/UCI HAR Dataset/train/y_train.txt")
train_data_features <- read.table("./project_data/UCI HAR Dataset/train/X_train.txt")
train_data_subject <- read.table("./project_data/UCI HAR Dataset/train/subject_train.txt")
# read activity lables and feature names
activity_labels <- read.table("./project_data/UCI HAR Dataset/activity_labels.txt")
feature_names <- read.table("./project_data/UCI HAR Dataset/features.txt")
##################################################################
# Merges the training and the test sets to create one data set.
##################################################################
# set names to variables
names(test_data_activity) <- c("activity")
names(test_data_features) <- feature_names$V2
names(test_data_subject) <- c("subject")
names(train_data_activity) <- c("activity")
names(train_data_features) <- feature_names$V2
names(train_data_subject) <- c("subject")
names(activity_labels) <- c("activity", "activityname")
# Merge the data to create one data set
test_data <- cbind(cbind(test_data_features, test_data_subject), test_data_activity)
train_data <- cbind(cbind(train_data_features, train_data_subject), train_data_activity)
big_data <- rbind(test_data, train_data)
############################################################################################
# Extracts only the measurements on the mean and standard deviation for each measurement.
############################################################################################
big_data_mean_std <- big_data[,grepl("mean\\(\\)|std\\(\\)|subject|activity", names(big_data))]
###########################################################################
# Uses descriptive activity names to name the activities in the data set
###########################################################################
big_data_mean_std <- merge(big_data_mean_std, activity_labels, by = "activity")
big_data_mean_std <- big_data_mean_std[,-1]
##############################################################
# Appropriately labels the data set with descriptive names.
##############################################################
# Remove hyphens and parenthesis
names(big_data_mean_std) <- gsub("\\-mean\\(\\)\\-", "Mean", names(big_data_mean_std))
names(big_data_mean_std) <- gsub("\\-std\\(\\)\\-", "Std", names(big_data_mean_std))
names(big_data_mean_std) <- gsub("\\-mean\\(\\)", "Mean", names(big_data_mean_std))
names(big_data_mean_std) <- gsub("\\-std\\(\\)", "Std", names(big_data_mean_std))
# Add descriptive names
names(big_data_mean_std)<-gsub("Acc", "Accelerometer", names(big_data_mean_std))
names(big_data_mean_std)<-gsub("Gyro", "Gyroscope", names(big_data_mean_std))
names(big_data_mean_std)<-gsub("^t", "time", names(big_data_mean_std))
names(big_data_mean_std)<-gsub("^f", "frequency", names(big_data_mean_std))
names(big_data_mean_std)<-gsub("BodyBody", "Body", names(big_data_mean_std))
names(big_data_mean_std)<-gsub("Mag", "Magnitude", names(big_data_mean_std))
######################################################################################################################
# Create a second, independent tidy data set with the average of each variable for each activity and each subject.
######################################################################################################################
tidy_data <- aggregate(. ~ subject + activityname, big_data_mean_std, mean)
tidy_data <- tidy_data[order(tidy_data$subject, tidy_data$activityname),]
write.table(tidy_data, file = "tidy_data.txt", row.names = FALSE, quote = FALSE)
message("### run_analysis.R complete!")
|
ac5e95da43399dd7d9ea0c7265b803c053fee927 | fe4cd16ffb13b2f29c12ffd520c81cee0c23f7f0 | /man/export_env_file.Rd | 313f5724c025866e335f308a6797919e559446dd | [] | no_license | xinchoubiology/phyloseq | 64648ee089fe42bb94a934bb559ce1c307e371b0 | 6eeb569025d330c5b1b709c103075b37b2feeaff | refs/heads/master | 2020-05-20T19:24:22.015998 | 2015-06-18T17:24:38 | 2015-06-18T17:24:38 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,303 | rd | export_env_file.Rd | \name{export_env_file}
\alias{export_env_file}
\title{Export environment (ENV) file for UniFrac Server.}
\usage{
export_env_file(physeq, file = "", writeTree = TRUE,
return = FALSE)
}
\arguments{
\item{physeq}{(Required). Experiment-level
(\code{\link{phyloseq-class}}) object. Ideally this also
contains the phylogenetic tree, which is also exported by
default.}
\item{file}{(Optional). The file path for export. If
not-provided, the expectation is that you will want to
set \code{return} to \code{TRUE}, and manipulate the ENV
table on your own. Default is \code{""}, skipping the ENV
file from being written to a file.}
\item{writeTree}{(Optional). Write the phylogenetic tree
as well as the the ENV table. Default is \code{TRUE}.}
\item{return}{(Optional). Should the ENV table be
returned to the R workspace? Default is \code{FALSE}.}
}
\description{
Creates the environment table that is needed for the
original UniFrac algorithm. Useful for cross-checking, or
if want to use UniFrac server. Optionally the
ENV-formatted table can be returned to the \code{R}
workspace, and the tree component can be exported as
Nexus format (Recommended).
}
\examples{
# # Load example data
# data(esophagus)
# export_env_file(esophagus, "~/Desktop/esophagus.txt")
}
|
e106bea99aa708b5970a8e08af5c5dcf5c8fdb05 | 3643239f66f3082fa08c7cb2cb6b8f4ec2247ede | /heatmap.R | 5af968e8b76c8e332534cc69ac28a70a519a42f0 | [] | no_license | n-mouse/R-templates | fc5a2f8c6be3cd34d76862e13dcb1cb49ba0d9c1 | 6314b3c182adb981914ffdad4985099e4b955847 | refs/heads/master | 2021-07-05T20:31:51.100022 | 2018-06-18T11:05:20 | 2018-06-18T11:05:20 | 94,525,114 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,260 | r | heatmap.R | salary.w = gather(salary, level, salary, rek:prof)
salary.w$level = as.factor(salary.w$level)
salary.w$level =factor(salary.w$level, levels=c("rek", "dek", "zav", "prof"))
ggplot(salary.w, aes(level, uni)) + geom_tile(aes(fill = salary), colour = "white")+
scale_fill_gradient(low = "white", high = "steelblue")+theme_bw()+
ggtitle("Зарплата в університетах")+
labs(caption="Дані від Стадного")+
guides(fill=guide_legend(title="грн"))+
theme(
plot.title = element_text(size=18, family="Roboto", face="bold", colour = "#515151", hjust=-0.3, vjust=2),
plot.caption = element_text(size=12, family="Roboto", color="#515151", face="italic", vjust=-2),
panel.border=element_blank(),
panel.background = element_rect(fill = "#ffffff"),
plot.background = element_rect(fill = "#ffffff"),
axis.title=element_blank(),
axis.ticks=element_blank(),
axis.text=element_text(size=10, family="Roboto", colour = "#515151"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.margin = unit(c(20, 20, 20, 20), "points")
)+scale_x_discrete(labels=c("ректори", "декани", "завкафи", "професори, \nстарші викладачі"))
|
cfd396390695d74462d441e6037609fb1886fa70 | be575dacc3f4f3ae8627f55d8a974e4d900e7d16 | /R_files/sample_plot.R | 1cd567bc24a94903671903cdaacabdc1a4002008 | [] | no_license | denohora/MTWorkshop | 1c0715a53154d79d620b223aa18b310731695b0f | a94ecddeb7efff3db247c488a076814d67054584 | refs/heads/master | 2021-01-22T04:53:29.432928 | 2014-03-19T10:47:54 | 2014-03-19T10:47:54 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,561 | r | sample_plot.R | # Test plotting Mousetracker csvs at Swansea Uni Feb 2014
# for more R functions for mousetracking analyses check out
# https://github.com/denohora/mtR
# for a useful guide to R download this
# http://webcom.upmf-grenoble.fr/LIP/Perso/DMuller/M2R/R_et_Mixed/documents/Baayen-Livre-Draft.pdf
print("First, we need to tell R where we are working")
print("click any file in your R files folder")
setwd(dirname(file.choose())) #click any file in your R files folder
# use "source" to import functions from other R files
source("mt_import.R") # this is a general purpose mt csv importer (based on read.csv)
source("mt_plot.R") # this is a simple plotting function that will plot the mean traj in data frame
# we will subset data frames to use this function
# import the data using mt.import and store it in sampledata
sampledata = mt.import("sampledata.csv", prepVar = T)
# use str to look at the first 30 columns of sampledata
str(sampledata[,1:30])
# get the names of the conditions
unique(sampledata$code)
# first rough usage of mt.plot
mt.plot(sampledata[sampledata$code == "model_h",]) # uses "plot"s defaults
# average trajectory for the model_h condition
# let's compare model_h with model_m
mt.plot(sampledata[sampledata$code == "model_h",],
xlim = c(-1,1), ylim = c(0,1.2), type = "l", col = "red" )
mt.plot(sampledata[sampledata$code == "model_m",], NewPlot = F,
xlim = c(-1,1), ylim = c(0,1.2), type = "l", col = "green" ) # uses "plot"s defaults
# average trajectory for the model_m condition
|
b233380d0693e20af8b8bffe7a289398b73eb5ac | c60f09b5b1b301046ad472e809248dea7c9320fa | /r/fit_democracy_model.R | b5a700a9c2ed580a3fa2dc8ee4ebe1de6b7cdc1f | [] | no_license | ximenacontla/democracy-measurement-model | d36a009759d35dacd445a2bc10114c6801d02604 | 9e21de5bf5745e8abfaafffaa1f58e18b3fdeed3 | refs/heads/master | 2020-06-16T16:36:13.159407 | 2015-05-12T06:47:49 | 2015-05-12T06:47:49 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,729 | r | fit_democracy_model.R | library(rstan)
library(data.table)
library(dplyr)
library(reshape2)
library(ggplot2)
library(optparse)
option_list <- list(
## data
make_option(c("--infile"), type="character", action="store",
default='democracies.csv',
dest="infile")
## posteriors
,make_option(c("--outfile"), type="character", action="store",
default='democracies_output.csv',
dest="outfile")
## expert posteriors
,make_option(c("--hyperparams"), type="character", action="store",
default='experts_output.csv',
dest="hyperparams")
,make_option(c("--model"), type="character", action="store",
dest="model")
## HMC
,make_option(c("--draws"), type="integer", default=2000,
dest="draws")
,make_option(c("--chains"), type="integer", default=4,
dest="chains")
,make_option(c("--example"), action="store_true", default=FALSE)
)
opt <- parse_args(OptionParser(option_list=option_list))
D <- fread(opt$infile)
## ALlows us to run a quick version for testing on just a few countries.
if(opt$example) {
D <- D %>%
filter(sftgcode %in% unlist(strsplit('UKR,GRG,RUS,KYR,ARM,BLR,MLD', ',')))
}
melted <- melt(D, c('country', 'sftgcode', 'year')) %>%
filter(!is.na(value)) %>%
mutate(sftgcode = factor(sftgcode),
year = factor(year),
expert = factor(variable))
expert_dat <- with(melted, list(
country = as.integer(sftgcode),
year = as.integer(year),
expert = as.integer(expert),
labels = as.integer(value),
num_obs = nrow(melted)
))
expert_dat[['num_countries']] <- max(expert_dat[['country']])
expert_dat[['num_years']] <- max(expert_dat[['year']])
expert_dat[['num_experts']] <- max(expert_dat[['expert']])
fn <- paste('stan/', opt$model, '.stan', sep='')
if (opt$model == 'autocorr4') {
mypars <- c('expert_bias', 'expert_var',
'democracy', 'time_var')
} else if (opt$model == 'autocorr5') {
mypars <- c('expert_bias', 'democracy', 'time_var')
} else {
## keep them all
mypars <- NA
}
fit <- stan(fn,
data = expert_dat,
iter = opt$draws,
chains = opt$chains,
pars = mypars)
## ## hyper parameters
## ## country.var <- extract(fit, 'country_var')[['country_var']]
## ## time.var <- extract(fit, 'time_var')[['time_var']]
save(fit, file = paste('cache/', opt$model, '_fit.RData', sep=''))
## expert parameters
expert.biases <- melt(extract(fit, 'expert_bias')[['expert_bias']]) %>%
select(rep = iterations, expert = Var2, value) %>%
mutate(expert = factor(expert, labels = levels(melted$expert))) %>%
group_by(expert) %>%
summarise(mean = mean(value), se = sd(value)) %>%
mutate(value = 'bias')
if (opt$model != 'autocorr5') {
expert.vars <- melt(extract(fit, 'expert_var')[['expert_var']]) %>%
select(rep = iterations, expert = Var2, value) %>%
mutate(expert = factor(expert, labels = levels(melted$expert))) %>%
group_by(expert) %>%
summarise(mean = mean(value), se = sd(value)) %>%
mutate(value = 'variance')
write.csv(rbind(expert.biases, expert.vars), opt$hyperparams)
} else {
write.csv(expert.biases, opt$hyperparams)
}
## country democracy time series
democracy <- melt(extract(fit, 'democracy')[['democracy']]) %>%
select(rep = iterations, year = Var3, country = Var2, value) %>%
mutate(year = as.numeric(as.character(factor(year, labels = levels(melted$year)))),
country = factor(country, labels = levels(melted$sftgcode))) %>%
group_by(year, country) %>%
summarise(demo = 1 / (1 + exp(-mean(value))),
lcl = 1 / (1 + exp(-(mean(value) - 1.96*sd(value)))),
ucl = 1 / (1 + exp(-(mean(value) + 1.96*sd(value)))))
write.csv(democracy, opt$outfile)
|
b743f37c0cd8b0f6673d2456fc8540d6a4a9f460 | 7f3afd70fd41c3dc6be2cb15b19199272d85c05c | /tests/testsuite/test_FLMatrixRREF.R | b5682d6f41b927defa3e97bff0b0f14b67a0c4bd | [] | no_license | gkappler/AdapteR | e79cea82f6e8ecb7662bec1c7e5bee12dff184e1 | 380f0ecd7fc860b2b8d76fe131f30ff13f5dedbf | refs/heads/master | 2020-04-05T00:20:09.132663 | 2016-07-03T22:09:26 | 2016-07-03T22:09:26 | 30,557,830 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 270 | r | test_FLMatrixRREF.R | #Function not in R
#FLMatrixRREF
test_that( "testing the example written in FLMatrixRREF",{
flmatrix <- FLMatrix("FL_DEMO", "tblMatrixMulti", 5,"MATRIX_ID","ROW_ID","COL_ID","CELL_VAL")
resultFLMatrix <- FLMatrixRREF(flmatrix)
print(resultFLMatrix)
}) |
c702ff6aa9f4830c74559e92bbd113630a309084 | b594559381882de514fcb9997421dfad59897c18 | /man/target.Rd | 44728808f21321a7c1e9420b990a3ec6a05e9caa | [] | no_license | jeffreypullin/rgreta | d11e7105604d2dc4414b58652cd64312ff308f0b | e976698778c397ca8c0714f9017cc8b0981bf9d7 | refs/heads/master | 2020-04-23T14:31:18.940857 | 2019-02-18T07:37:42 | 2019-02-18T07:37:42 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 353 | rd | target.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utils.R
\name{target}
\alias{target}
\title{get the target node of a greta disitbution node}
\usage{
target(dist_node)
}
\arguments{
\item{dist_node}{a greta distribution node}
}
\value{
a greta variable node
}
\description{
get the target node of a greta disitbution node
}
|
6ab209c64e4defc720c6911fda472164705b465b | db0839dbb14ba0264347762c34361f3ef2feb822 | /fetch_section_titles.R | 9392009c5ccf3a61dab31f1c0a967dc3cd49e19c | [] | no_license | apoorv74/IKreporteR | 6f5682d32591c516cdfe9da5161e83432634f637 | 6b168725a1b24119db0d4a863cdf59b005d98935 | refs/heads/master | 2020-05-01T17:06:38.315368 | 2019-07-13T09:08:57 | 2019-07-13T09:08:57 | 177,591,339 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,589 | r | fetch_section_titles.R | ik_act_url <- glue::glue('https://indiankanoon.org/doc/{1733066}/')
print('Fetching links to sections and sub sections')
all_sections_of_act_link <- ik_act_url %>%
read_html() %>%
html_nodes(css = ".article a") %>%
html_attr('href') %>%
unlist()
section_id <- all_sections_of_act_link %>%
stringr::str_replace_all(pattern = "\\/doc\\/",replacement = "") %>%
stringr::str_trim() %>%
stringr::str_replace_all(pattern = "\\/",replacement = "")
section_id <- unique(section_id)
# Get section headings
get_section_title <- function(citedby){
Sys.sleep(1)
section_link <- glue::glue('https://indiankanoon.org/doc/{citedby}')
tryCatch({
all_sections_title <- section_link %>%
read_html() %>%
html_nodes(css = ".acts .doc_title") %>%
html_text() %>% unlist()
act_title <- stringr::str_replace_all(string = stringr::str_to_lower(all_sections_title),
pattern = "section [\\S]+ in the ",
replacement = ""
)
if(is.na(all_sections_title)){
all_sections_title <- NA_character_
act_title <- NA_character_
}
}, error = function(e){
all_sections_title <- NA_character_
act_title <- NA_character_
})
return(data.frame('citedby'=citedby, 'section_title'=all_sections_title, 'act_title' = act_title))
close.connection(section_link)
}
cited_by <- '1724893'
# get_section_title(1724893)
all_titles <- lapply(section_id, get_section_title)
all_titles_df <- dplyr::bind_rows(all_titles)
|
6ed6d41e0af56252ad1fdd16fa1876a4ced5caec | 5c5c74d66420841d0521de62bece90488ba2ce7a | /Test Functions/SSAGA_LS_CO.R | 358ba838a170e533cb6dbfc3a15eb2190f5923ce | [
"MIT"
] | permissive | Adam-Diehl/Machine-Learning | 022289a98af84bd91e8deccf6e5f20aa916cb6f1 | 35e39fd5e26a62e244b1457f2b91a48b986ea116 | refs/heads/master | 2021-09-12T05:06:35.708899 | 2018-04-14T22:23:40 | 2018-04-14T22:23:40 | 113,077,706 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 6,710 | r | SSAGA_LS_CO.R | SSAGA = function(fitness_func, max_iterations, max_runtime, max_stagnation, input_width) {
################ TOP LEVEL DOCUMENTATION ################
#Input documentation
#Fitness function: objective function (READ IN THE INPUTS)
#Max iterations: maximum number of generations to allow
#Max runtime: number of seconds the algorithm can run (runtime will exceed this by the amount it takes to finish the current loop)
#Max stagnation: number of sequential generations without an improvement in fitness
#Sample input: SSAGA(fitness_func, 1000, 30, 500, 10)
#input_width: how many inputs/dims the input takes
#Genetic operators
#Elistism (E) - preserve best solutions across generations
#Cross-Over/Cross-Breeding (CO) - mix the best solutions
#Mutation (M) - randomly change the best solutions
#Random Immigrants (RI) - generate totally new solutions
################ CODE SETUP ################
#Capture the entry time
CodeEnterTime = Sys.time()
#Set algorithm parameters
PopulationSize = 64
GeneticOperator_Primary = (1/2)
GeneticOperator_Secondary = (1/4)
GeneticOperator_Tertiary = (3/16)
GeneticOperator_Quaternary = (1/16)
#Set states as vector - position 1 = E, position 2 = CO, position 3 = M, position 4 = RI
StateBias_Elitism = c(PopulationSize*GeneticOperator_Primary, PopulationSize*GeneticOperator_Tertiary, PopulationSize*GeneticOperator_Secondary, PopulationSize*GeneticOperator_Quaternary)
StateBias_CrossOver = c(PopulationSize*GeneticOperator_Quaternary, PopulationSize*GeneticOperator_Primary, PopulationSize*GeneticOperator_Secondary, PopulationSize*GeneticOperator_Tertiary)
StateBias_Mutation = c(PopulationSize*GeneticOperator_Quaternary, PopulationSize*GeneticOperator_Secondary, PopulationSize*GeneticOperator_Primary, PopulationSize*GeneticOperator_Tertiary)
StateBias_RandomImmigrants = c(PopulationSize*GeneticOperator_Quaternary, PopulationSize*GeneticOperator_Secondary, PopulationSize*GeneticOperator_Tertiary, PopulationSize*GeneticOperator_Primary)
################ ALGORITHM INTERFACE ################
#Define parameters
BurnInPeriod = 100 #Number of iterations to allow before checking stagnation
MutationRate = 1 #Number of genes to mutate per chromosome
#Initialize the algorithm
#Create initial population
OldPopulation = apply(matrix(0, input_width, PopulationSize), MARGIN = 1, runif)
#Normalize the population
OldPopulation = sweep(OldPopulation, 1, rowSums(OldPopulation), "/")
#Instantiate a blank matrix to hold the new solutions
NewPopulation = matrix(0, PopulationSize, input_width)
#Create a blank list to store the best solutions
SolutionFitness = c(0)
#Record the time entering the optimization procedure
CurrentTime = Sys.time()
#Initialize iterations count
iterations = 0
#Initialize population stagnation index
populationStagnationIndex = 0
#Set initial state
CurrentState = StateBias_CrossOver
#Algorithm iteration
#STEPS CORRESPOND TO THE ORDER THE NEW MATRIX IS FILLED
#Step 1: Elitism
#Step 2: Cross-Over
#Step 3: Mutation
#Step 4: Random Immigrants (totally new solutions)
#Alert user to entrance
print("Beginning optimization...")
while(iterations < max_iterations && (CurrentTime - CodeEnterTime) < max_runtime && populationStagnationIndex < max_stagnation) {
#Create a score vector
scoreVect = matrix(0, PopulationSize, 1)
#Score the entries
for(i in 1:PopulationSize) {
scoreVect[i] = fitness_func(OldPopulation[i,])
}
#Bind the score column to the solutions matrix
OldPopulation = cbind(OldPopulation, scoreVect)
#Sort by score
OldPopulation = OldPopulation[order(OldPopulation[,input_width+1]),]
#Record the best score
SolutionFitness = append(SolutionFitness, log(1 + 1/OldPopulation[1, input_width+1]))
#Delete the scores
OldPopulation = OldPopulation[,-(input_width+1)]
#Carry over the top individuals to the next population
for(i in 1:CurrentState[1]) {
NewPopulation[i,] = OldPopulation[i,]
}
#Cross-Breed the top solutions using two-point cross-over
for(i in seq(1, CurrentState[2], 2)) {
points = sample(1:input_width,2)
#Set new genes for Chromosome i
NewPopulation[(i+CurrentState[1]),] = OldPopulation[i,]
NewPopulation[(i+CurrentState[1]), points[1]:points[2]] = OldPopulation[i+1,points[1]:points[2]]
#Set new genes for Chromosome i+1
NewPopulation[(i+CurrentState[1]+1),] = OldPopulation[i+1,]
NewPopulation[(i+CurrentState[1]+1), points[1]:points[2]] = OldPopulation[i,points[1]:points[2]]
}
#Mutate the top half of solutions
for(i in 1:CurrentState[3]) {
mutationIndex = sample(1:input_width, MutationRate) #Randomly select the gene(s) which will be mutated
OldPopulation[i,mutationIndex] = runif(1,-1,1)
NewPopulation[(i + CurrentState[1] + CurrentState[2]),] = OldPopulation[i,]
}
#Receive random immigrants
for(i in 1:CurrentState[4]) {
NewPopulation[(i + CurrentState[1] + CurrentState[2] + CurrentState[3]),] = runif(input_width, -1, 1)
}
#Assign new matrix to the old matrix
OldPopulation = NewPopulation
#Update exit conditions
iterations = iterations + 1
CurrentTime = Sys.time()
if(iterations > BurnInPeriod && SolutionFitness[iterations] == SolutionFitness[iterations-1]) {
populationStagnationIndex = populationStagnationIndex + 1
} else {
populationStagnationIndex = 0
}
}
#Delete the dummy entry from the solution matrix
SolutionFitness = SolutionFitness[-1]
#Algorithm wrap up
CodeExitTime = Sys.time()
print("Solution convergence.")
#plot(SolutionFitness, main = "Solution Fitness", xlab = "Generation", ylab = "Relative Fitness", type = "l", ylim = c(0,25), col = "black")
#plot(diff(SolutionFitness), main = "Solution Growth", xlab = "Generation", ylab = "Growth in Relative Fitness", type = "l", col = "black")
print(paste("Fitness:", fitness_func(OldPopulation[1,])))
print("Best solution:")
print(OldPopulation[1,])
print(paste("Iterations: ", iterations))
print(paste("Time elapsed: ", CodeExitTime - CodeEnterTime))
#Algorithm output
ReturnObject = c(0)
ReturnObject$Solution = OldPopulation[1,]
ReturnObject$FinalFitness = fitness_func(OldPopulation[1,])
ReturnObject$Iterations = iterations
ReturnObject$RunTime = CodeExitTime - CodeEnterTime
ReturnObject$FitnessHistory = SolutionFitness
ReturnObject$FitnessGrowth = diff(SolutionFitness)
ReturnObject = ReturnObject[-1]
return(ReturnObject)
} |
2e3838defd9bc5739303833fef8f4bc8e67730d9 | d6bf6a4b78bfd9f362973cae96cac7e32aa04a9c | /Plot2.R | 560242a5907ebb98fa9916b30a65ac7044316dbf | [] | no_license | iabalki/ExData_Plotting1 | 6f8d8cb362911e515d2f6713835b919b2adf2044 | aac930fd587754613ec02b351db8f5fcaca99888 | refs/heads/master | 2021-01-20T11:01:20.826596 | 2015-07-10T01:19:07 | 2015-07-10T01:19:07 | 38,405,371 | 0 | 0 | null | 2015-07-02T01:57:47 | 2015-07-02T01:57:47 | null | UTF-8 | R | false | false | 1,034 | r | Plot2.R |
## Step 1: Load the data, subsetting for the desired period and format for plotting
## note: change the location if your source file is stored in a diff location
setwd ("D:/Users/Milla/Documents/Data Science Classes/Course 4 Project 1")
## read the full dataset
data <- read.table ("household_power_consumption.txt", header = TRUE, sep =";", dec =".", na.strings = "?", stringsAsFactors = FALSE)
## convert the dates so that we can lookup which rows are within the desired period
data$Date <- as.Date(data$Date, format = "%d/%m/%Y")
## subset the desired period
mydata <- subset (data, Date == as.Date("2007-02-01") |
Date == as.Date("2007-02-02"))
## Merge Date and Time so that you can plot all elements in the right sequence
mydata$DateTime <- strptime (paste(as.character(mydata$Date), mydata$Time), "%Y-%m-%d %H:%M:%S")
## Step 2: Plot onto files
### plot 2
png(file="plot2.png")
plot (mydata$DateTime, mydata$Global_active_power, xlab = "", ylab = "Global Active Power (Kilowatts)", type = "l")
dev.off
|
57384c3bf5e8ed825dc64a341c7e9b6a425cc350 | fddc3385f84d3415435ef93b877c642a76442b95 | /KenyaComparisonRaster.R | a8a03550ed02d93d487c8e3379be7d1b81a973e4 | [] | no_license | caosmax/AFrica_LAC | 35b69212cc42d4d78278fda43e8d186fcaa20643 | ac14d98ea6d9e83da5c2df47ec6e982f7855b7f0 | refs/heads/master | 2021-07-04T00:13:56.339789 | 2017-09-26T19:00:47 | 2017-09-26T19:00:47 | 103,179,111 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 9,798 | r | KenyaComparisonRaster.R | ## Kenya raster
g=gc;rm(list = ls())
#Load libraries---
library(dplyr)
library(tidyr)
library(Hmisc)
library(raster)
library(ggplot2)
library(reshape)
library(RColorBrewer)
library(maptools)
library(gridExtra)
library(sp)
library(maps)
library(raster)
library(rgdal)
#directories---
dir<-"C:/Users/CEGONZALEZ/Documents/GFSF"
#cargamos shape ALC
# Kenya <- shapefile(paste0(dir,"/","Kenya.shp"))
fpu<- shapefile("C:/Users/CEGONZALEZ/Desktop/BID/BID/newBID/ImpactResults/Shapefiles mundo/fpu_shp/fpu_shp/fpu.shp")
atest <- raster(paste0(dir,"/","spam2005v2r0_yield_bean_total.tiff"))
# filter FPU kenya
fpu <- fpu[fpu@data$Region_Nam=="Kenya",]
# crop using Extent
crs(atest)<- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
crs(fpu)<-"+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
#Recorte primero por extent y luego mascara
cr <- crop(atest, extent(fpu))
rr <- raster::mask(cr,fpu)
# ploting easier
plot(rr)
plot(fpu,add=T)
# To convert your RasterLayer to a data.frame, you need to convert it to
# a SpatialPixelsDataFrame first
r.spdf <- as(rr, "SpatialPixelsDataFrame")
r.df <- as.data.frame(r.spdf)
head(r.df)
colnames(r.df)[1]<- "Val"
r.df<- filter(r.df, Val!=0)
# g <- ggplot(r.df, aes(x=x, y=y)) + geom_tile(aes(fill = Val)) + coord_equal()
#fortify fpu
fpu<- fortify(fpu)
color_scale = colorRampPalette(c('red','gold2','forestgreen'), space="rgb")(25)
# labs2 = 'Harvest Area\n(ha)'
png(filename = paste(dir,"KenyaArea.png", sep=""),
width = 20, height = 12, units = 'in', res = 100)
y <- ggplot() +
geom_polygon(data=fpu, aes(x=long, y=lat, group = group),colour="white", fill="white")+
geom_path(data=fpu, aes(x=long, y=lat, group=group), colour="black", size=0.25)+
geom_raster(data= r.df, aes(x=x, y=y, fill=Val))+
theme(strip.text.x = element_text(angle = 0,size = 18),strip.background = element_rect(colour="white", fill="white")) +
theme_bw()+ coord_equal() + theme(aspect.ratio = 1) +
scale_fill_gradientn(colours=color_scale,na.value = "grey50")+
# labs(fill=labs2)+
theme(strip.text.x = element_text(angle = 0,size = 16, face = "bold.italic"))+
theme(strip.text.y = element_text(angle = 0,size = 16, face = "bold.italic"))+
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
legend.text = element_text(size=14),
legend.title = element_text(face="bold",size=14),
legend.background = element_blank(),
legend.key = element_blank(),
strip.text.y = element_text(size=16, face="bold"),
plot.title = element_text(face="bold", size=22),
panel.border = element_blank(),
axis.ticks = element_blank(),
strip.background = element_rect(colour="white", fill="white"))
plot(y)
dev.off()
############### Data for extract information for built allocation matrix cultivation
g<- "//dapadfs/workspace_cluster_6/Socioeconomia/GF_and_SF/CASE_Jamleck"
sp<- c("rainfed", "irrigated")
i=1
# for(i in 1:length(sp)){
r <- raster(paste(g,"/","spam2005v2r0_harvested-area_bean_","rainfed.tiff",sep = "")) # load
crs(r)<- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0" # reproyect
fpu<- shapefile("C:/Users/CEGONZALEZ/Desktop/BID/BID/newBID/ImpactResults/Shapefiles mundo/fpu_shp/fpu_shp/fpu.shp")
fpu <- fpu[fpu@data$Region_Nam=="Kenya",]
cr <- crop(r, extent(fpu))
rr <- raster::mask(cr,fpu)
r.spdf <- as(rr, "SpatialPixelsDataFrame")
r.df <- as.data.frame(r.spdf)
head(r.df)
colnames(r.df)[1]<- "Area"
r.df<- filter(r.df, Area!=0)
r.df$New_FPU<- "HOA_KEN"
r.df$Coincidencias<- row.names(r.df)
r.df<- r.df[c("x","y","Area","New_FPU","Coincidencias" )]
# Distribution areas
hist(r.df$Area)
summary(r.df$Area)
#Fortify fpu
fpu<- fortify(fpu)
labs2 = 'Harvest Area\n(ha)'
color_scale = colorRampPalette(c('red','gold2','forestgreen'), space="rgb")(25)
png(filename = paste(g,"/","KenyaArea_rainfed.png", sep=""),
width = 20, height = 12, units = 'in', res = 100)
#Creating graph
y<-ggplot() +
geom_polygon(data=fpu, aes(x=long, y=lat, group = group),colour="white", fill="white")+
geom_path(data=fpu, aes(x=long, y=lat, group=group), colour="black", size=0.25)+
geom_raster(data= r.df, aes(x=x, y=y, fill=Area))+
theme(strip.text.x = element_text(angle = 0,size = 18),strip.background = element_rect(colour="white", fill="white")) +
theme_bw()+ coord_equal() + theme(aspect.ratio = 1) +
scale_fill_gradientn(colours=color_scale,na.value = "grey50")+
labs(fill=labs2)+
theme(strip.text.x = element_text(angle = 0,size = 16, face = "bold.italic"))+
theme(strip.text.y = element_text(angle = 0,size = 16, face = "bold.italic"))+
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
legend.text = element_text(size=14),
legend.title = element_text(face="bold",size=14),
legend.background = element_blank(),
legend.key = element_blank(),
strip.text.y = element_text(size=16, face="bold"),
plot.title = element_text(face="bold", size=22),
panel.border = element_blank(),
axis.ticks = element_blank(),
strip.background = element_rect(colour="white", fill="white"))
plot(y)
dev.off()
# export to CSV
write.csv(r.df,paste(g,"/","KenyaAreaCoordinates_rainfed.csv", sep=""))
# export as raster
r.df<- r.df[,c("x", "y", "Area")]
rd<- rasterFromXYZ(r.df)
plot(rd)
writeRaster(rd, filename= paste(g,"/","Raster_Beans_",sp[i],"_.tif",sep=""), format="GTiff", overwrite=TRUE)
#### processing to get the same resolution -----------
## Spatial management Data---------------
# mask by kenya
fpu<- shapefile("C:/Users/CEGONZALEZ/Desktop/BID/BID/newBID/ImpactResults/Shapefiles mundo/fpu_shp/fpu_shp/fpu.shp")
# filter FPU kenya
fpu <- fpu[fpu@data$Region_Nam=="Kenya",]
require(ncdf4)
# data of planting date
da <- stack(x =paste(g,"/","Pulses_rf_growing_season_dates_v1.25.nc4", sep = ""),varname= "planting day")
cr <- crop(da, extent(fpu))
dake <- raster::mask(cr,fpu)
pdata <- as(dake, "SpatialPixelsDataFrame")
pdata <- as.data.frame(pdata)
head(pdata)
colnames(pdata)[1]<- "plant_day"
pdata<- pdata[,c("x","y","plant_day")]
pdata$coord <- paste(pdata$x,pdata$y)
# data climate
pre <- raster(paste(g,"/","prec_1971_2000_01_avg.nc", sep = ""))
crs(pre)<- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0" # reproyect
# Resample raster a 50km * 50km
preR <- resample(pre, dake, method = 'ngb') # precipitation
# load raster location
# data localizacion cultivos
r <- raster(paste(g,"/","spam2005v2r0_harvested-area_bean_","rainfed.tiff",sep = "")) # load
crs(r)<- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0" # reproyect
cr <- crop(r, extent(fpu))
rr <- raster::mask(cr,fpu)
# convierto en dataframe
r.spdf <- as(rr, "SpatialPixelsDataFrame")
r.df <- as.data.frame(r.spdf)
head(r.df)
colnames(r.df)[1]<- "Area"
r.df<- filter(r.df, Area!=0)
# r.df$New_FPU<- "HOA_KEN"
# r.df$Coincidencias<- row.names(r.df)
# r.df<- r.df[c("x","y","Area","New_FPU","Coincidencias" )]
r.df<- r.df[,c("x", "y", "Area")]
q1<- quantile(r.df$Area,c(0.25))
r.df<- filter(r.df, Area>q1)
rd<- rasterFromXYZ(r.df)
crs(rd)<- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0" # reproyect
loc <- resample(rd, dake, method = 'ngb') # localization crops
matrix_mag<- as(loc, "SpatialPixelsDataFrame")
matrix_mag <- as.data.frame(matrix_mag)
matrix_mag$New_FPU<- "HOA_KEN"
matrix_mag$Coincidencias<- row.names(matrix_mag)
matrix_mag<- matrix_mag[c("x","y","Area","New_FPU","Coincidencias" )]
matrix_mag<- pdata[,c("x","y","plant_day")]
matrix_mag$coord <- paste(matrix_mag$x,matrix_mag$y)
# join planting data and local
ma<-left_join(matrix_mag, pdata, by=c("coord","x","y"))
ma<- na.omit(ma)
rownames(ma)<- 1:nrow(ma)
write.csv(ma,paste(g,"/","KenyaMatrixCrop_rainfed.csv", sep=""))
# Extraction coordinates for runing
jj<-preR # precipitation
jj[jj>0]<-1
sum(jj[jj])
bean<- loc # Area
bean[bean>0]<-1
sum(bean[bean])
ff<- dake # planting date
ff[ff>0]<-1
test<- bean+jj+ff
test[test==3]<-1
sum(test[test])
writeRaster(test, filename= paste(g,"/","rasterSpots_Rainfed.tif",sep=""), format="GTiff", overwrite=TRUE)
plot(test)
plot(fpu,add=T)
# obtener coordenadas
ltest <- as(test, "SpatialPixelsDataFrame")
pix<- as.data.frame(ltest@coords)
write.csv(x = pix,paste(g,"/","coordenadas.csv",sep=""))
### tabla manejo agronomico
head(r.df)
fp <- as(ff, "SpatialPixelsDataFrame")
r.df <- as.data.frame(r.spdf)
|
6d8520e157a26bd1b103ebdf56cbe1aba4083876 | 5e16efbfd051bb517527df48815622b9b227e216 | /man/coo_up.Rd | 0abfbb6eb90dbf7abfcc2a8208d29f4b20cce3c6 | [] | no_license | yuting27/Momocs | ac41fb817a689c90be97788c4cf4dbdc769b7ff5 | d4cb2a504e7f78a0d39e3e741620a9d4364b9437 | refs/heads/master | 2020-12-29T03:18:50.753927 | 2016-02-10T19:44:48 | 2016-02-10T19:44:48 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,235 | rd | coo_up.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/coo-utilities.R
\name{coo_up}
\alias{coo_up}
\title{Retains coordinates with positive y-coordinates}
\usage{
coo_up(coo, slidegap = FALSE)
}
\arguments{
\item{coo}{a \code{matrix} of (x; y) coordinates or a \code{list}, or any \link{Coo} object.}
\item{slidegap}{\code{logical} whether to apply \link{coo_slidegap} after coo_down}
}
\value{
a \code{matrix} of (x; y) coordinates or a \link{Coo} object (\link{Out} are returned as \link{Opn})
}
\description{
Useful when shapes are aligned along the x-axis (e.g. because of a
bilateral symmetry) and when one wants to retain just the upper side.
}
\note{
When shapes are "sliced" along the x-axis, it usually results on open curves and thus to huge/artefactual
gaps between points neighboring this axis. This is usually solved with \link{coo_slidegap}. See examples there.
Also, when apply a coo_left/right/up/down on an \link{Out} object, you then obtain an \link{Opn} object, which is done
automatically.
}
\examples{
b <- coo_alignxax(bot[1])
coo_plot(b)
coo_draw(coo_up(b), border='red')
}
\seealso{
Other opening functions: \code{\link{coo_down}},
\code{\link{coo_left}}, \code{\link{coo_right}}
}
|
576dfe4e9cfbc4bcf12a0b0320fe7a958a129d70 | 8dd70b7b96930653812210f6e3a660ba8ea50b0d | /plot1.R | 3a8714405c53bf3053786281976be2d269cfd826 | [] | no_license | krondor/ExData_Plotting1 | ee063f58dddfb5cf3ae840569121aaac84f164a4 | 4c13489c4f6f91cab483e553a7e32458dcd604b5 | refs/heads/master | 2021-01-17T22:07:01.681565 | 2014-09-07T17:47:56 | 2014-09-07T17:47:56 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 951 | r | plot1.R | # Parse Data Set into Data Table
hpc <- read.csv("household_power_consumption.txt",
sep=";",
na.strings="?",
stringsAsFactors=F)
# Reduce Dataset to Valid Dates Only
hpc <- hpc[hpc$Date %in% c("1/2/2007", "2/2/2007"),]
# Add Date Time formatted COlumn
hpc$DateTime <- strptime(paste(hpc$Date, hpc$Time), "%d/%m/%Y %T")
# Names of Numeric Data Columns
numCols <- c("Global_active_power", "Global_reactive_power", "Voltage",
"Global_intensity", "Sub_metering_1", "Sub_metering_2",
"Sub_metering_3")
# Convert Numeric Data Columns to Numeric from Character
for (i in numCols) {
hpc[,i] <- as.numeric(hpc[,i])
}
# Histogram for Plot 1
hist(hpc$Global_active_power, col="red", main="Global Active Power",
xlab="Global Active Power (kilowatts)", ylab="Frequency", breaks=15)
# Save Resulting Image
dev.copy(png, file="plot1.png", width=480, height=480, units="px")
dev.off() |
9018b77864630c108f5aeb272975ffdf322d99eb | ac507e24073717f0f2f43480101be5db0213c2c4 | /pwiz_tools/Skyline/Executables/Tools/SProCoP/QCplotsRgui2.R | ddaa1b32ba6df8dec8976c4a309692fe494e2f0e | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | permissive | ProteoWizard/pwiz | 7adbd5a276b49d5f0271eb8cfddbd6d21ee31318 | f708f62d098c33ef60a76d92b038fde74361570a | refs/heads/master | 2023-08-27T20:42:37.708268 | 2023-08-25T18:30:50 | 2023-08-25T18:30:50 | 124,952,577 | 185 | 92 | Apache-2.0 | 2023-09-14T20:39:46 | 2018-03-12T21:16:01 | C# | WINDOWS-1252 | R | false | false | 12,254 | r | QCplotsRgui2.R | # Produces Shewhart Control Charts and Pareto Analysis for Evaulating Proteomic Experiments
# for Rv2.13 or later must be installed along with the qcc library from R and Skyline
# (https://skyline.gs.washington.edu/labkey/project/home/software/Skyline/begin.view)
options (echo = FALSE)
debug <- FALSE
# Retention Time Reproducibility, Peak Asymmetry (a+b/2a), fwhm, and Peak Areas are monitored for 2-9 selected peptides and at least 3 QC replicates
##
## Command line processing and other functions to support GenePattern
##
parse.cmdline <- function () {
# set up for command line processing (if needed)
# arguments are specified positionally (since there are no optional arguments) and ...
arguments <- commandArgs(trailingOnly=TRUE)
if ( length (arguments) != 5)
# expected arguments not present -- error
stop ("USAGE: R --slave --no-save --args '<number> <highres.ms> <save.meta> <mma.value>' < QCplotsRgui2.R\n") #<libdir>
for (z in 1:5) {
arg <- arguments [z]
# remove leading and trailing blanks
arg <- gsub ("^ *", "", arg)
arg <- gsub (" *$", "", arg)
# remove any embedded quotation marks
arg <- gsub ("['\'\"]", "", arg)
if (z==1) filename <<- arg
if (z==2) Q1 <<- as.numeric (arg)
if (z==3) Q6 <<- as.numeric (arg)
if (z==4) Q4 <<- as.numeric (arg)
if (z==5) Q8 <<- as.numeric (arg)
}
windows(15,15)
##filename<-commandArgs(trailingOnly = TRUE)[1];
mydata=read.table(filename,sep=",",header=TRUE); # reads files in
PA=mydata[,3] # takes third column of skyline files PAs
RT=mydata[,4] # takes 4 column RTs
pep=mydata[,2] # takes 2 peptide names
QC=mydata[,1] # takes QC replicate names
fwhm=mydata[,5]
minstart=mydata[,6] # takes start integration values for all peptides and runs
maxend=mydata[,7] # End integration values for all peptides
MA=mydata[,8]
#M_abs_dev=function(x) # Defines function to take the median absolute deviation center around the mean
#mad(x,center=mean(x))
L=length(unique(QC)) # Determines number of QC replicates RAN
L2=length(unique(pep)) # Determines Number of Peptides used in QC run
dim(PA)=c(L,L2) # reshapes PA a peptide per column
dim(RT)=c(L,L2) # reshapes RT a peptide per column
dim(pep)=c(L,L2) # reshapes pep names per column
dim(fwhm)=c(L,L2)
dim(minstart)=c(L,L2)
dim(maxend)=c(L,L2)
dim(MA)=c(L,L2)
PApm=colMeans(PA[1:Q1,])
PApm.all=colMeans(PA) # Calculates means and SD of Peak areas per peptide
paline=rep(PApm,each=L)
dim(paline)=c(L,L2)
PAsd=apply(PA[1:Q1,],2,sd)
PAsd.all=apply(PA,2,sd)
# Calculates means and SD of RT per peptide
RTm=colMeans(RT[1:Q1,])
RTm.all=colMeans(RT)
RTline=rep(RTm,each=L)
dim(RTline)=c(L,L2)
RTsd=apply(RT[1:Q1,],2,sd)
RTsd.all=apply(RT,2,sd)
# Calculates means and SD of FWHM per peptide
fwhmM=colMeans(fwhm[1:Q1,])
fwhmM.all=colMeans(fwhm)
fwhmline=rep(fwhmM,each=L)
dim(fwhmline)=c(L,L2)
fwhmsd=apply(fwhm[1:Q1,],2,sd)
fwhmsd.all=apply(fwhm,2,sd)
A1=RT-minstart # Calculates means and SD of Peak symmetry
B1=maxend-RT
Psym=(A1+B1)/(2*A1)
PsymM=colMeans(Psym[1:Q1,],)
PsymM.all=colMeans(Psym)
PsymMline=rep(PsymM,each=L)
dim(PsymMline)=c(L,L2)
Psymsd=apply(Psym[1:Q1,],2,sd)
Psymsd.all=apply(Psym,2,sd)
pepCL1p=PApm+PAsd #calculates +1 SD from PA mean
pepCL2p=PApm+2*PAsd #+2 SD from PA mean
pepCL3p=PApm+3*PAsd
pepCL1m=PApm-PAsd #-1 SD from PA mean
pepCL2m=PApm-2*PAsd #-2 SD from PA mean
pepCL3m=PApm-3*PAsd
RTCL1p=RTm+RTsd #same as above but for RT
RTCL2p=RTm+2*RTsd
RTCL3p=RTm+3*RTsd
RTCL1m=RTm-RTsd
RTCL2m=RTm-2*RTsd
RTCL3m=RTm-3*RTsd
fwhmCL1p=fwhmM+fwhmsd #same as above but for FWHM
fwhmCL2p=fwhmM+2*fwhmsd
fwhmCL3p=fwhmM+3*fwhmsd
fwhmCL1m=fwhmM-fwhmsd
fwhmCL2m=fwhmM-2*fwhmsd
fwhmCL3m=fwhmM-3*fwhmsd
PsymCL1p=PsymM+Psymsd #same as above but for Peak asymetry
PsymCL2p=PsymM+2*Psymsd
PsymCL3p=PsymM+3*Psymsd
PsymCL1m=PsymM-Psymsd
PsymCL2m=PsymM-2*Psymsd
PsymCL3m=PsymM-3*Psymsd
RT1p=rep(RTCL1p,each=L) #making the confidence lines for RT
dim(RT1p)=c(L,L2)
RT2p=rep(RTCL2p,each=L)
dim(RT2p)=c(L,L2)
RT1m=rep(RTCL1m,each=L)
dim(RT1m)=c(L,L2)
RT2m=rep(RTCL2m,each=L)
dim(RT2m)=c(L,L2)
RT3p=rep(RTCL3p,each=L)
dim(RT3p)=c(L,L2)
RT3m=rep(RTCL3m,each=L)
dim(RT3m)=c(L,L2)
pep1p=rep(pepCL1p,each=L) #making the confidence lines for peak areas
dim(pep1p)=c(L,L2)
pep2p=rep(pepCL2p,each=L)
dim(pep2p)=c(L,L2)
pep1m=rep(pepCL1m,each=L)
dim(pep1m)=c(L,L2)
pep2m=rep(pepCL2m,each=L)
dim(pep2m)=c(L,L2)
pep3p=rep(pepCL3p,each=L)
dim(pep3p)=c(L,L2)
pep3m=rep(pepCL3m,each=L)
dim(pep3m)=c(L,L2)
fwhm1p=rep(fwhmCL1p,each=L) #making the confidence lines for fwhm
dim(fwhm1p)=c(L,L2)
fwhm2p=rep(fwhmCL2p,each=L)
dim(fwhm2p)=c(L,L2)
fwhm1m=rep(fwhmCL1m,each=L)
dim(fwhm1m)=c(L,L2)
fwhm2m=rep(fwhmCL2m,each=L)
dim(fwhm2m)=c(L,L2)
fwhm3p=rep(fwhmCL3p,each=L)
dim(fwhm3p)=c(L,L2)
fwhm3m=rep(fwhmCL3m,each=L)
dim(fwhm3m)=c(L,L2)
Psym1p=rep(PsymCL1p, each=L) #making the confidence lines for Peak Asymetry
dim(Psym1p)=c(L,L2)
Psym2p=rep(PsymCL2p, each=L)
dim(Psym2p)=c(L,L2)
Psym1m=rep(PsymCL1m, each=L)
dim(Psym1m)=c(L,L2)
Psym2m=rep(PsymCL2m, each=L)
dim(Psym2m)=c(L,L2)
Psym3p=rep(PsymCL3p,each=L)
dim(Psym3p)=c(L,L2)
Psym3m=rep(PsymCL3m,each=L)
dim(Psym3m)=c(L,L2)
par(mfrow=c(4,L2))
QCnum=1:L
a=rep(0,L2) #for making the loop Number of Peptides Used
b=rep(0,L2)
c=rep(0,L2)
d=rep(0,L2)
E=rep(0,L2)
F=rep(0,L2)
G=rep(0,L2)
H=rep(0,L2)
M=rep(0,L2)
for (i in 1:L2) { #calculates PA RSDs
RSDpa=(PAsd.all[i]/PApm.all[i])*100
a[i]=RSDpa
}
for (j in 1:L2) { #calculates RT RSDS
RSDrt=(RTsd.all[j]/RTm.all[j])*100
b[j]=RSDrt
}
for (k in 1:L2) {
RSDfwhm=(fwhmsd.all[k]/fwhmM.all[k])*100
c[k]=RSDfwhm
}
for (n in 1:L2) {
RSDpsym=(Psymsd.all[n]/PsymM.all[k])*100
d[n]=RSDpsym
}
for (i in 1:L2) { #plots peak areas and CI lines
plot(QCnum,PA[,i],type='o',ylab="peak area",pch=22,lty=2,ylim=c(min(PA[,i]),max(PA[,i])))
title(c(paste(main=pep[L*i], "\n", "CV%=", round(a[i],2))))
title(ylab="peak area")
lines(QCnum,pep1m[,i],col="green")
lines(QCnum,pep1p[,i],col="green")
lines(QCnum,pep2m[,i],col="brown")
lines(QCnum,pep2p[,i],col="brown")
lines(QCnum,pep3p[,i],lwd=2.0,col="red")
lines(QCnum,pep3m[,i],lwd=2.0,col="red")
lines(QCnum,paline[,i],col="blue")
#legend("topright", legend = c(paste("CV=",round(a[i],2))),bty="n")
}
for (i in 1:L2) { #plots RT and CI lines
plot(QCnum,RT[,i],type='o',ylab="RT (min)",pch=22,lty=2,ylim=c(min(RT[,i]),max(RT[,i])))
title(c(paste(main=pep[L*i], "\n", "CV%=", round(b[i],2))))
lines(QCnum,RT1m[,i],col="green")
lines(QCnum,RT1p[,i],col="green")
lines(QCnum,RT2p[,i],col="brown")
lines(QCnum,RT2m[,i],col="brown")
lines(QCnum,RT3p[,i],lwd=2.0,col="red")
lines(QCnum,RT3m[,i],lwd=2.0,col="red")
lines(QCnum,RTline[,i],col="blue")
#legend("topright", legend = c(paste("CV=",round(b[i],2))),bty="n")
}
for (i in 1:L2) { #plots fwhm and CI lines
plot(QCnum,fwhm[,i],type='o',ylab="fwhm (min)",pch=22,lty=2,ylim=c(min(fwhm[,i]),max(fwhm[,i])))
title(c(paste(main=pep[L*i], "\n", "CV%=", round(c[i],2))))
lines(QCnum,fwhm1m[,i],col="green")
lines(QCnum,fwhm1p[,i],col="green")
lines(QCnum,fwhm2p[,i],col="brown")
lines(QCnum,fwhm2m[,i],col="brown")
lines(QCnum,fwhm3p[,i],lwd=2.0,col="red")
lines(QCnum,fwhm3m[,i],lwd=2.0,col="red")
lines(QCnum,fwhmline[,i],col="blue")
#legend("topright", legend = c(paste("CV=",round(c[i],2))),bty="n")
}
for (i in 1:L2) { #plots Peak Symmetry and CI lines
plot(QCnum,Psym[,i],type='o',ylab="Peak Symmetry",pch=22,lty=2,ylim=c(min(Psym[,i]),max(Psym[,i])))
title(c(paste(main=pep[L*i], "\n", "CV%=", round(d[i],2))))
lines(QCnum,Psym1p[,i],col="green")
lines(QCnum,Psym1m[,i],col="green")
lines(QCnum,Psym2p[,i],col="brown")
lines(QCnum,Psym2m[,i],col="brown")
lines(QCnum,Psym3m[,i],lwd=2.0,col="red")
lines(QCnum,Psym3p[,i],lwd=2.0,col="red")
lines(QCnum,PsymMline[,i],col="blue")
#legend("topright", legend = c(paste("CV=",round(c[i],2))),bty="n")
}
windows(5,5)
if (Q4==1)
{
pdf('QC.pdf')
for (i in 1:L2) {
plot(QCnum,PA[,i],type='o',ylab="peak area",pch=22,lty=2,ylim=c(min(PA[,i]),max(PA[,i])))
title(c(paste(main=pep[L*i], "\n", "CV%=", round(a[i],2))))
title(ylab="peak area")
lines(QCnum,pep1m[,i],col="green")
lines(QCnum,pep1p[,i],col="green")
lines(QCnum,pep2m[,i],col="brown")
lines(QCnum,pep2p[,i],col="brown")
lines(QCnum,pep3p[,i],lwd=2.0,col="red")
lines(QCnum,pep3m[,i],lwd=2.0,col="red")
lines(QCnum,paline[,i],col="blue")
#legend("topright", legend = c(paste("CV=",round(a[i],2))),bty="n")
}
for (i in 1:L2) {
plot(QCnum,RT[,i],type='o',ylab="RT (min)",pch=22,lty=2,ylim=c(min(RT[,i]),max(RT[,i])))
title(c(paste(main=pep[L*i], "\n", "CV%=", round(b[i],2))))
lines(QCnum,RT1m[,i],col="green")
lines(QCnum,RT1p[,i],col="green")
lines(QCnum,RT2p[,i],col="brown")
lines(QCnum,RT2m[,i],col="brown")
lines(QCnum,RT3p[,i],lwd=2.0,col="red")
lines(QCnum,RT3m[,i],lwd=2.0,col="red")
lines(QCnum,RTline[,i],col="blue")
#legend("topright", legend = c(paste("CV=",round(b[i],2))),bty="n")
}
for (i in 1:L2) {
plot(QCnum,fwhm[,i],type='o',ylab="fwhm (min)",pch=22,lty=2,ylim=c(min(fwhm[,i]),max(fwhm[,i])))
title(c(paste(main=pep[L*i], "\n", "CV%=", round(c[i],2))))
lines(QCnum,fwhm1m[,i],col="green")
lines(QCnum,fwhm1p[,i],col="green")
lines(QCnum,fwhm2p[,i],col="brown")
lines(QCnum,fwhm2m[,i],col="brown")
lines(QCnum,fwhm3p[,i],lwd=2.0,col="red")
lines(QCnum,fwhm3m[,i],lwd=2.0,col="red")
lines(QCnum,fwhmline[,i],col="blue")
#legend("topright", legend = c(paste("CV=",round(c[i],2))),bty="n")
}
for (i in 1:L2) {
plot(QCnum,Psym[,i],type='o',ylab="Peak Symmetry",pch=22,lty=2,ylim=c(min(Psym[,i]),max(Psym[,i])))
title(c(paste(main=pep[L*i], "\n", "CV%=", round(d[i],2))))
lines(QCnum,Psym1p[,i],col="green")
lines(QCnum,Psym1m[,i],col="green")
lines(QCnum,Psym2p[,i],col="brown")
lines(QCnum,Psym2m[,i],col="brown")
lines(QCnum,Psym3m[,i],lwd=2.0,col="red")
lines(QCnum,Psym3p[,i],lwd=2.0,col="red")
lines(QCnum,PsymMline[,i],col="blue")
#legend("topright", legend = c(paste("CV=",round(c[i],2))),bty="n")
}
dev.off()
}
for (i in 1:L2) { # Finding the number of NonConformers +/- 3s for PAs
NCpa=length(which(PA[,i]>pepCL3p[i]))
NCpa2=length(which(PA[,i]<pepCL3m[i]))
sum=NCpa+NCpa2
E[i]=sum
}
for (i in 1:L2) { # Finding the number of NonConformers +/- 3s for RT
NCrt=length(which(RT[,i]>RTCL3p[i]))
NCrt2=length(which(RT[,i]<RTCL3m[i]))
sumrt=NCrt+NCrt2
F[i]=sumrt
}
for (i in 1:L2) {
NCfwhm=length(which(fwhm[,i]>fwhmCL3p[i])) # Finding the number of NonConformers +/- 3s for fwhm
NCfwhm2=length(which(fwhm[,i]<fwhmCL3m[i]))
sumfwhm=NCfwhm+NCfwhm2
G[i]=sumfwhm
}
for (i in 1:L2) {
NCps=length(which(Psym[,i]>PsymCL3p[i])) # Finding the number of NonConformers +/- 3s for Psym
NCps2=length(which(Psym[,i]<PsymCL3m[i]))
sumPS=NCps+NCps2
H[i]=sumPS
}
if (Q6==1)
{
for (i in 1:L2) {
MAhigh=length(which(MA[,i]> Q8)) # Finding the number of NonConformers +/- 3s for MMA User defined
MAlow=length(which(MA[,i]< -Q8))
MAtotal=MAhigh+MAlow
M[i]=MAtotal
}}
dev.set(3)
library(qcc)
if (Q6==1){
Exp=c(sum(E),sum(F),sum(G),sum(H),sum(M))
metrics=c("peak area", "RT", "fwhm", "Peak Symmetry", "MMA")
names(Exp)=metrics
PChart=pareto.chart(Exp,ylab="# of NonConformers ±3s")
dev.set(2)
}
if (Q6==0){
Exp=c(sum(E),sum(F),sum(G),sum(H))
metrics=c("peak area", "RT", "fwhm", "Peak Symmetry")
names(Exp)=metrics
PChart=pareto.chart(Exp,ylab="# of NonConformers ±3s")
dev.set(2)
}
if (Q6==1)
{
windows(5,5)
MA=t(MA)
boxplot(MA,main="Mass Measurement Accuracy (MMA)",pars=list(boxwex=0.5,staplewex=0.2,outwex=0.2), col="red",xlab="QC Run Num", ylab="MMA (ppm)")
}
identify(QCnum,fwhm[,1])
}
tryCatch({parse.cmdline()},
finally = {
cat("Finished!")
})
|
9c685addb689e29f35734ce51da5e0a1e045915c | 0500ba15e741ce1c84bfd397f0f3b43af8cb5ffb | /cran/paws.developer.tools/man/codebuild_invalidate_project_cache.Rd | 11fda53b2310ae9575b4b5fb078c8e56ff096d69 | [
"Apache-2.0"
] | permissive | paws-r/paws | 196d42a2b9aca0e551a51ea5e6f34daca739591b | a689da2aee079391e100060524f6b973130f4e40 | refs/heads/main | 2023-08-18T00:33:48.538539 | 2023-08-09T09:31:24 | 2023-08-09T09:31:24 | 154,419,943 | 293 | 45 | NOASSERTION | 2023-09-14T15:31:32 | 2018-10-24T01:28:47 | R | UTF-8 | R | false | true | 567 | rd | codebuild_invalidate_project_cache.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/codebuild_operations.R
\name{codebuild_invalidate_project_cache}
\alias{codebuild_invalidate_project_cache}
\title{Resets the cache for a project}
\usage{
codebuild_invalidate_project_cache(projectName)
}
\arguments{
\item{projectName}{[required] The name of the CodeBuild build project that the cache is reset for.}
}
\description{
Resets the cache for a project.
See \url{https://www.paws-r-sdk.com/docs/codebuild_invalidate_project_cache/} for full documentation.
}
\keyword{internal}
|
2587a2c665c7c849c863368d9a7a3ee0319f961c | a0c105298b6ce5c0b62c76ca42f558b2fd3350fc | /R/scimeetr_options.R | fc4bed15067cc3cda92e2b839915adfc4e0b50ee | [
"MIT"
] | permissive | lizlaw/LitDeepDiving | f3b2104aafd10e74e52aea6451ad6935c77e5af5 | 83b8b2d916c62210698d96d1153ca131b1aaec3d | refs/heads/main | 2023-01-11T07:24:55.592689 | 2020-11-19T15:32:57 | 2020-11-19T15:32:57 | 311,380,421 | 0 | 0 | MIT | 2020-11-10T14:12:30 | 2020-11-09T15:23:34 | null | UTF-8 | R | false | false | 7,350 | r | scimeetr_options.R | # scimeetr options example
# Example: Mapping the evidence for impacts of managed bees on wild bees
# Search terms:
# *Managed*: (African* NEAR bee) OR Apis OR Bombus OR "bumble bee"
# OR bumblebee* OR "honey bee" OR honeybee OR ((introduc* OR inva* OR non-native
# OR nonnative OR commercial OR exotic OR feral OR managed) NEAR (bee OR
# pollin*))
# *Native*: (((cavity OR ground) NEAR nesting) OR (native OR solitary
# OR wild)) NEAR (bee OR pollin*)
# *Interaction*: pollinat* OR network* OR “niche
# overlap” OR “partitioning” OR interact* OR competit* OR facilitat* OR
# mutualis* OR “resource limitation” OR hybridization OR introgression OR
# dependence OR assemblag* OR overlap OR spillover OR impact*
# Search Web of Science: TOPIC searches Title, Abstract, Keywords (supplied by the author),
# and Keywords Plus (algorithm extraction of expanded terms stemming from the
# cited references)
#
# TOPIC: ((African* NEAR bee) OR Apis OR Bombus OR "bumble bee" OR
# bumblebee* OR "honey bee" OR honeybee OR ((introduc* OR inva* OR
# non-native OR nonnative OR commercial OR exotic OR feral OR managed)
# NEAR (bee OR pollin* ))) AND TOPIC: ((((cavity OR ground) NEAR nesting) OR
# (native OR solitary OR wild)) NEAR (bee OR pollin* )) AND TOPIC:
# (pollinat* OR network* OR “niche overlap” OR “partitioning” OR interact*
# OR competit* OR facilitat* OR mutualis* OR “resource limitation” OR
# hybridization OR introgression OR dependence OR assemblag* OR overlap OR
# spillover OR impact*)
# Timespan: All years. Indexes: SCI-EXPANDED, SSCI,A&HCI, ESCI.
# Search date: 05.Nov.2020
# Results: 2,400 Export full record and cited references in Tab-delimited (Win, UTF-8) format (for scimeetr)
# --------------------------------------------------------------------------------------------------------------------------------------------------------
# # install required packages
# remotes::install_github("MaximeRivest/scimeetr")
# load packages
library(tidyverse) # programming
library(scimeetr) # bibiometric analysis and determination of sub-communities
# import to scimeetr object -----------------------------------------------
dd <- "./data/raw_WoS_20201105/as_txt/"
scimeetr_list <- import_wos_files(dd)
scimeetr_list
summary(scimeetr_list)
# In the dfsci, the 68 variables imported from WoS and their frequency of non NA data:
fieldtags <- read_csv("wos_fieldtags.csv")
indf <- summarise_all(scimeetr_list$com1$dfsci, function(x) sum(!is.na(x))) %>%
t() %>%
as_tibble(rownames = "TAG") %>%
select(TAG, "is_not_NA" = V1) %>%
right_join(., fieldtags) %>%
filter(is_not_NA > 0)
indf %>% print(n = nrow(indf))
# # Use scimeetr to define sub-communities -----------------------------------------------
# create nested sub-communities - we'll do this twice to start, using the recommended bickecticjoc method.
sci_bktj30 <- scimap(scimeetr_list, coupling_by = 'bickecticjoc', community_algorithm = 'louvain', min_com_size = 30)
scisub_bktj30 <- scimap(sci_bktj30, coupling_by = 'bickecticjoc', community_algorithm = 'louvain', min_com_size = 30)
saveRDS(scisub_bktj30, "data/raw_WoS_20201105/scisub_bktj30.RDS")
scisub_bktj30 <- readRDS("data/raw_WoS_20201105/scisub_bktj30.RDS")
summary(scisub_bktj30)
plot(summary(scisub_bktj30, com_size = 30))
# define a custom 'deepdive' function ---------------------------------------------------------
deep_dive <- function(object, kw = 10, kr = 10, mr = 3, ...){
out <- list()
out$Overview <- list(
str_c("Number of papers: ", nrow(object[[1]]$dfsci)),
str_c("Number of communities: ", length(object)),
object %>% map_dbl(function(x) nrow(x$dfsci)) %>% .[order(names(.))]
)
out$Word_frequencies <- list(
tags = object[[1]]$tag,
keywords = data.frame(
"key_words" = object[[1]]$kw$ID[1:kw],
"key_words_de" = object[[1]]$de$ID[1:kw],
"title_words" = object[[1]]$ti$ID[1:kw],
"abstract_words" = object[[1]]$ab$ID[1:kw],
"authors" = object[[1]]$au$ID[1:kw],
"cited_refs" = object[[1]]$cr$ID[1:kw],
stringsAsFactors = F)
)
# prepare function for ranking papers
get_pubs <- function(rlist){
.kr <- ifelse(rlist %in% "by_expert_LC", ceiling(kr/mr), kr)
scilist(object, k = .kr, m = mr, reading_list = rlist) %>%
.[[1]] %>%
select(publication) %>%
add_column(type = rlist)
}
title_tab <- object[[1]]$dfsci %>%
select(RECID, Title = TI) %>%
mutate(publication = map_chr(RECID, function(x) x %>%
stringr::str_replace_all(', DOI.*', '') %>%
stringr::str_replace_all('V(?=[0-9]{1,6})', '') %>%
stringr::str_replace_all('P(?=[0-9]{1,6})', ''))) %>%
select(-RECID)
cited_tab <- object[[1]]$dfsci %>%
select(RECID, TimesCited = Z9, Title = TI, PY, EA) %>%
mutate(Year = pmap_dbl(list(PY, EA), function(py,ea) ifelse(!is.na(py), py, ea %>% str_extract('[0-9]{4}') %>% as.numeric()))) %>%
select(-PY, -EA)
cited_tab <- cited_tab %>%
add_column(residuals = mgcv::gam(TimesCited ~ Year, data = cited_tab, family = "poisson")$residuals)
cited_most <- bind_rows(
top_n(cited_tab, kr, TimesCited) %>% add_column("cited_most" = 1, "cited_resid" = 0),
top_n(cited_tab, kr, TimesCited) %>% add_column("cited_most" = 0, "cited_resid" = 1)
) %>%
group_by(RECID, Title, Year, TimesCited, residuals) %>%
summarise_at(vars(cited_most:cited_resid), sum) %>%
arrange(desc(residuals), desc(TimesCited))
out$Articles_highcited_in <- list(
description = str_c("Highest cited papers in the group"),
publist = cited_most
)
out$Articles_highcited_by <- list(
description = str_c("Highest cited papers by the group"),
publist = map(c("core_papers", "core_residual"), get_pubs) %>%
bind_rows() %>%
with(., table(publication, type)) %>%
as_tibble() %>%
pivot_wider(names_from = "type", values_from ="n") %>%
arrange(desc(core_papers), desc(core_residual)) %>%
left_join(title_tab, by = "publication")
)
out$Articles_experts <- list(
description = str_c("Highest cited papers by highly cited authors"),
publist = map(c("by_expert_LC"), get_pubs) %>%
bind_rows() %>%
with(., table(publication, type)) %>%
as_tibble() %>%
pivot_wider(names_from = "type", values_from ="n") %>%
arrange(desc(by_expert_LC)) %>%
left_join(title_tab, by = "publication")
)
out$Aricles_review <- list(
description = str_c("Papers likely to provide a good overview of the category"),
publist = map(c("cite_most_others", "connectness"), get_pubs) %>%
bind_rows() %>%
with(., table(publication, type)) %>%
as_tibble() %>%
pivot_wider(names_from = "type", values_from ="n") %>%
arrange(desc(cite_most_others), desc(connectness)) %>%
left_join(title_tab, by = "publication")
)
return(out)
}
# apply function -----------------------------------------------
comlist <- sort(names(scisub_bktj30))
deep_dive_results <- tibble(
community = comlist,
dd_results = map(comlist, function(x) deep_dive(dive_to(scisub_bktj30, aim_at = x)))
)
deep_dive_results$dd_results[[1]]
|
d9d75d0dd2446221697924fb1350c761904abb20 | 640f292949b3090b556ebbf4ba08128e7ebfa5b7 | /R/LDtL.R | e7b71fef92fa02ba530b3c1931a7b47800bf8257 | [] | no_license | DuyDN/nadiv | 2ccf2f676cb56cc961334dfa75148e0693e7b9df | e4cabffcd92ddc88a2f8971d405a20325002529d | refs/heads/master | 2021-01-17T21:51:30.746207 | 2015-08-20T15:20:19 | 2015-08-20T15:20:19 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 118 | r | LDtL.R | LDtL <- function(A){
ch <- chol(A)
dd <- diag(ch)
return(list(tL = ch / dd, D = Diagonal(nrow(A), dd^2)))
}
|
6fabb5a5ed7b804e791a4640d461485076013f45 | e7f52fdab339ab543118145d2ffe71d558fb6be8 | /exhibits.R | 7b11c7921a93170961bdbd980dcb293cbc4b96a2 | [] | no_license | JesusRQP96/lda-survey-exp | 705e40abac602271932f15caa8c63d28b60eb263 | fe1de9365a493c748cd917347848c096b0fd6cfe | refs/heads/master | 2022-12-08T04:57:39.986775 | 2020-09-05T17:00:42 | 2020-09-05T17:00:42 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,207 | r | exhibits.R | library(stargazer)
library(kableExtra)
source("plot_utils.R")
#load Card data and drop individuals with missing rotter scale variables
load("data/card/card_data.RData")
card.groups <- paste(card.data$LIBCRD14, card.data$SINMOM14,sep="")
card.groups <- as.numeric(factor(card.groups))
card.data <- card.data[!card.data$NOROTTER, ]
card.aux <- c("rotter_A", "rotter_B", "rotter_C","rotter_D", "rotter_E", "rotter_F",
"rotter_G", "rotter_H", "rotter_I", "rotter_J", "rotter_K",
"subj_liked", "subj_dislik", "attitude_hs")
#Load Michigan Data
mich.aux <- c("PAGO", "PEXP","RINC","BAGO","BEXP","BUS12","BUS5","UNEMP","GOVT",
"RATEX","PX1Q1","DUR","HOM","CAR")
mich.data <- read.csv("data/michigan/mich_raw.csv")
###########################################################################
## Figure 3 - LDA-DE Indices for Michigan Consumer Survey Data
###########################################################################
load(file="posteriors/mich_estimate.RData")
dates <- paste(unique(mich.data$YYYYMM),"01",sep="")
dates <- as.Date(dates,"%Y%m%d")
umcsent <- read.csv("data/michigan/UMCSENT.csv")
umcsent <- (umcsent$UMCSENT - min(umcsent$UMCSENT))/(max(umcsent$UMCSENT)- min(umcsent$UMCSENT))*max(post.ev$pi[,1])
data.plot1 <- data.frame(dates = dates, index_1=post.ev$pi[, 1], ics =umcsent )
unrate <- read.csv("data/michigan/UNRATE.csv")
epu <- read.csv("data/michigan/epu.csv")
epu <- epu$epu
pi3.short <- post.ev$pi[1:length(epu), 3]
pi4.short <- post.ev$pi[1:length(epu), 4]
dates.short <- dates[1:length(epu)]
unrate <- unrate$UNRATE[1:length(epu)]
unrate <- 0.6*(unrate - min(unrate))/(max(unrate)- min(unrate))
epu <- (epu - mean(epu))/sd(epu)*sd(pi4.short)+mean(pi4.short)
data.plot2 <- data.frame(dates=dates.short, index_4 = pi4.short, epu=epu)
data.plot3 <- data.frame(dates=dates.short, index_3 = pi3.short, unemp=unrate)
plotPis(data.plot1, T, path="exhibits/mich1_")
plotPis(data.plot2, T, path="exhibits/mich4_")
plotPis(data.plot3, T, path="exhibits/mich3_")
###########################################################################
## Figure 4 - Belief Types in Michigan Data
###########################################################################
plotBetas(post.ev$beta, path="exhibits/", questions=mich.aux)
###########################################################################
## Figure 5 - Belief Types in NLSYM Data
###########################################################################
load(file="posteriors/card_estimate.RData")
plotBetas(post.ev$beta, questions=card.aux, path="exhibits/")
###########################################################################
## Table 1 - Returns to Education Estimates
###########################################################################
K=3
base0 = "LWAGE76~BLACK+EXP76 +EXP762+SMSA76R+REG76R+ED76"
addCoefs=""
for (k in 1:(K-1)){
name = paste("Z",k,sep="")
card.data[,name] = post.ev$z_prob[,k]
addCoefs = paste(addCoefs,"+",name,"*","ED76",sep="")
}
base0 = "LWAGE76~BLACK+EXP76 +EXP762+SMSA76R+REG76R+ED76"
base = lm(base0, data=card.data)
het = lm(paste(base0, addCoefs, sep=""),data=card.data)
stargazer(base, het) %>% write("exhibits/table1.txt")
|
3ad3d6430fa156673f953c430cd8d9536ae57cf7 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/ade4/examples/rhone.Rd.R | 4934cdcf51a5b6dd4267501ddda14f1bc4139af7 | [] | no_license | surayaaramli/typeRrh | d257ac8905c49123f4ccd4e377ee3dfc84d1636c | 66e6996f31961bc8b9aafe1a6a6098327b66bf71 | refs/heads/master | 2023-05-05T04:05:31.617869 | 2019-04-25T22:10:06 | 2019-04-25T22:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 500 | r | rhone.Rd.R | library(ade4)
### Name: rhone
### Title: Physico-Chemistry Data
### Aliases: rhone
### Keywords: datasets
### ** Examples
data(rhone)
pca1 <- dudi.pca(rhone$tab, nf = 2, scann = FALSE)
rh1 <- reconst(pca1, 1)
rh2 <- reconst(pca1, 2)
par(mfrow = c(4,4))
par(mar = c(2.6,2.6,1.1,1.1))
for (i in 1:15) {
plot(rhone$date, rhone$tab[,i])
lines(rhone$date, rh1[,i], lwd = 2)
lines(rhone$date, rh2[,i])
ade4:::scatterutil.sub(names(rhone$tab)[i], 2, "topright")
}
par(mfrow = c(1,1))
|
1d25a511bff111d064019279a79e63eef9192806 | 94cad0e251ee9050a15db658bee277c6759a13f4 | /code/predictive_analytics_toeplitz.R | cf460a6e7c0d82252ddf82cbfc7b40ece54939ee | [] | no_license | kkdey/Robocov-pages | e4ea2b64f1bf98351b8e00c724845ecd5da3eedf | 154403167d5c539ece634f438643a606d7b9edff | refs/heads/master | 2021-03-02T06:43:07.146231 | 2020-06-30T14:18:44 | 2020-06-30T14:18:44 | 245,844,053 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,169 | r | predictive_analytics_toeplitz.R | options(echo=TRUE) # if you want see commands in output file
args <- commandArgs(trailingOnly = TRUE)
print(args)
N <- as.numeric(toString(args[1]))
P <- as.numeric(toString(args[2]))
count_missing <- as.numeric(toString(args[3]))
prop_missing = count_missing/100
library(Matrix)
library(CVXR)
library(Robocov)
library(CorShrink)
N=500
P=50
count_missing=0
prop_missing = count_missing/100
DM_toeplitz = function(n,P){
library("MASS")
index1=sort(sample(seq(1:n),(n/2)))
index2=seq(1:n)[-index1]
Sigmatp=function(P){
a=array(0,dim=c(P,P))
for(i in 1:P){
for(j in 1:P){
a[i,j]=max(1-0.1*(abs(i-j)),0)
}
}
return(a)
}
Sigma = Sigmatp(P)
data = mvrnorm(n,rep(0,P),Sigma)
Xtest = data[index2,]
Xtrain = data[index1,]
Omega = solve(Sigma)
return(list(Xtrain = Xtrain, Xtest = Xtest, Sigma = Sigma))
}
toeplitz_sim = function(N, P){
ll <- DM_toeplitz(n=N, P=P)
data <- rbind(ll$Xtrain, ll$Xtest)
Sigma <- ll$Sigma
corSigma <- cov2cor(Sigma)
ll = list("dat" = data, "cor" = corSigma)
return(ll)
}
data = toeplitz_sim(N, P)$dat
####################### Turn some of the entries to NA (missing) ###################################
data_missing = t(apply(data, 1, function(x){
if(prop_missing > 0){
rand = sample(1:length(x), floor(prop_missing*length(x)), replace = F)
y = x
y[rand] = NA
return(y)
}else{
return(x)
}}))
gene_data = data_missing
measure = c()
measure2 = c()
for(num_iter in 1:5){
train_sample_id = sample(1:nrow(gene_data), floor(nrow(gene_data)/2), replace = FALSE)
predict_sample_id = setdiff(1:nrow(gene_data), train_sample_id)
train_datamat = gene_data[train_sample_id,]
empirical_cor = cor(train_datamat, method = "pearson", use = "pairwise.complete.obs")
empirical_cor[is.na(empirical_cor)] = 0
corshrink_out = CorShrinkData(train_datamat, sd_boot = FALSE, image = "null",
image.control = list(tl.cex = 0.2))
corshrink_cor = corshrink_out$cor
robocov_box_cor = Robocov_box(data_with_missing = train_datamat, loss = "lasso")
predict_datamat = gene_data[predict_sample_id,]
cormat2 = cor(predict_datamat, method = "pearson", use = "pairwise.complete.obs")
cormat2[is.na(cormat2)] = 0
measure = rbind(measure, c(mean(abs(cormat2 - empirical_cor)),
mean(abs(cormat2 - corshrink_cor)),
mean(abs(cormat2 - robocov_box_cor)))
)
measure2 = rbind(measure2, c(sqrt(mean((cormat2 - empirical_cor)^2)),
sqrt(mean((cormat2 - corshrink_cor)^2)),
sqrt(mean((cormat2 - robocov_box_cor)^2))))
cat("We finished iteration:", num_iter)
}
df = cbind(apply(measure, 2, mean),
apply(measure, 2, sd),
apply(measure2, 2, mean),
apply(measure2, 2, sd))
colnames(df) = c("L1", "se(L1)", "L2", "se(L2")
rownames(df) = c("Sample-Est", "CorShrink", "Robocov")
ll = list("L1" = measure, "L2" = measure2)
save(ll, file = paste0("/n/groups/price/kushal/Robocov/output/Predictive/toeplitz_N_",N,
"_P_", P, "_pi_",count_missing, ".rda"))
|
1e146ad7703f6a5a53dfd34502082a7c5f3990ae | ba2c1f89c217693f4a93940ac10ec143d292f9fb | /demo/shapes.R | b8a8245d073660da7eccf66cbd9b0c63703481b4 | [] | no_license | cran/shapes | 462b82c907c14cda27ec1811a7682300b2ddc67c | 450a6306f3516703147c784b6e3d63aa66c6c5fb | refs/heads/master | 2023-02-19T05:10:54.176823 | 2023-02-03T20:50:01 | 2023-02-03T20:50:01 | 17,699,641 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,769 | r | shapes.R | #2D example : female and male Gorillas (cf. Dryden and Mardia, 1998)
data(gorf.dat)
data(gorm.dat)
n1<-dim(gorf.dat)[3]
n2<-dim(gorm.dat)[3]
k<-dim(gorf.dat)[1]
m<-dim(gorf.dat)[2]
gor.dat<-array(0,c(k,2,n1+n2))
gor.dat[,,1:n1]<-gorf.dat
gor.dat[,,(n1+1):(n1+n2)]<-gorm.dat
plotshapes(gorf.dat,gorm.dat)
gorf<-procGPA(gorf.dat)
gorm<-procGPA(gorm.dat)
plotshapes(gorf$rotated,gorm$rotated)
gor<-procGPA(gor.dat)
shapepca(gor,type="r",mag=3)
cat("First 3 PCs for pooled gorilla data")
for (ii in 1:1000000){a<-1}
shapepca(gor,type="v",mag=3)
cat("First 3 PCs for pooled gorilla data")
for (ii in 1:1000000){a<-1}
gor.gp<-c(rep("f",times=30),rep("m",times=29))
x<-cbind(gor$size,gor$rho,gor$scores[,1:3])
pairs(x,panel=function(x,y) text(x,y,gor.gp),
label=c("s","rho","score 1","score 2","score 3"))
#Some tests
test1<-testmeanshapes(gorf.dat,gorm.dat)
print(test1)
cat("Highly significant difference in mean shape")
gorf<-procGPA(gorf.dat)
gorm<-procGPA(gorm.dat)
mag<-2
TT<-gorf$mshape
YY<-gorm$mshape
par(mfrow=c(1,2))
YY<-TT+(YY-TT)*mag
tpsgrid(TT,YY,-150,-150,300,2,0.1,22)
title("TPS grid: Female mean (left) to Male mean (right)")
cat("##########################################################\n")
cat("#3D example\n#")
cat("##########################################################\n")
# Male macaques data (Dryden/Mardia 1998)
data(macm.dat)
out<-procGPA(macm.dat)
par(mfrow=c(2,2))
plot(out$rawscores[,1],out$rawscores[,2],xlab="PC1",ylab="PC2")
title("PC scores")
plot(out$rawscores[,2],out$rawscores[,3],xlab="PC2",ylab="PC3")
plot(out$rawscores[,1],out$rawscores[,3],xlab="PC1",ylab="PC3")
plot(out$size,out$rho,xlab="size",ylab="rho")
title("Size versus shape distance")
|
a4429c5a617d4f1479897614351006b36c068870 | f7408683a4b9f3ea36e6c56588f257eba9761e12 | /man/pfr_old.Rd | 5648c480eeac4b0299615d12a1df60c416387461 | [] | no_license | refunders/refund | a12ad139bc56f4c637ec142f07a78657727cc367 | 93cb2e44106f794491c7008970760efbfc8a744f | refs/heads/master | 2023-07-21T21:00:06.028918 | 2023-07-17T20:52:08 | 2023-07-17T20:52:08 | 30,697,953 | 42 | 22 | null | 2023-06-27T15:17:47 | 2015-02-12T10:41:27 | R | UTF-8 | R | false | true | 11,086 | rd | pfr_old.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/pfr_old.R
\name{pfr_old}
\alias{pfr_old}
\title{Penalized Functional Regression (old version)}
\usage{
pfr_old(
Y,
subj = NULL,
covariates = NULL,
funcs,
kz = 10,
kb = 30,
nbasis = 10,
family = "gaussian",
method = "REML",
smooth.option = "fpca.sc",
pve = 0.99,
...
)
}
\arguments{
\item{Y}{vector of all outcomes over all visits}
\item{subj}{vector containing the subject number for each observation}
\item{covariates}{matrix of scalar covariates}
\item{funcs}{matrix, or list of matrices, containing observed functional
predictors as rows. NA values are allowed.}
\item{kz}{can be NULL; can be a scalar, in which case this will be the
dimension of principal components basis for each and every observed
functional predictors; can be a vector of length equal to the number
of functional predictors, in which case each element will correspond
to the dimension of principal components basis for the corresponding
observed functional predictors}
\item{kb}{dimension of the B-spline basis for the coefficient function
(note: this is a change from versions 0.1-7 and previous)}
\item{nbasis}{passed to refund::fpca.sc (note: using fpca.sc is a change
from versions 0.1-7 and previous)}
\item{family}{generalized linear model family}
\item{method}{method for estimating the smoothing parameters; defaults
to REML}
\item{smooth.option}{method to do FPC decomposition on the predictors.
Two options available -- "fpca.sc" or "fpca.face". If using "fpca.sc",
a number less than 35 for \code{nbasis} should be used while if using
"fpca.face",35 or more is recommended.}
\item{pve}{proportion of variance explained used to choose the number of
principal components to be included in the expansion.}
\item{...}{additional arguments passed to \code{\link[mgcv]{gam}} to
fit the regression model.}
}
\value{
\item{fit }{result of the call to \code{gam}}
\item{fitted.vals }{predicted outcomes}
\item{fitted.vals.level.0 }{predicted outcomes at population level}
\item{fitted.vals.level.1 }{predicted outcomes at subject-specific level (if applicable)}
\item{betaHat }{list of estimated coefficient functions}
\item{beta.covariates }{parameter estimates for scalar covariates}
\item{varBetaHat }{list containing covariance matrices for the estimated coefficient functions}
\item{Bounds }{list of bounds of a pointwise 95\% confidence interval for the estimated coefficient functions}
\item{X }{design matrix used in the model fit}
\item{D }{penalty matrix used in the model fit}
\item{phi }{list of B-spline bases for the coefficient functions}
\item{psi }{list of principal components basis for the functional predictors}
\item{C }{stacked row-specific principal component scores}
\item{J }{transpose of psi matrix multiplied by phi}
\item{CJ }{C matrix multiplied J}
\item{Z1 }{design matrix of random intercepts}
\item{subj }{subject identifiers as specified by user}
\item{fixed.mat }{the fixed effects design matrix of the pfr as a mixed model}
\item{rand.mat }{the fixed effects design matrix of the pfr as a mixed model}
\item{N_subj }{the number of unique subjects, if subj is specified}
\item{p }{number of scalar covariates}
\item{N.pred }{number of functional covariates}
\item{kz }{as specified}
\item{kz.adj}{For smooth.option="fpca.sc", will be same as kz (or a vector of repeated values of the specified scalar kz). For smooth.option="fpca.face", will be the corresponding number of principal components for each functional predictor as determined by fpca.face; will be less than or equal to kz on an elemental-wise level.}
\item{kb }{as specified}
\item{nbasis }{as specified}
\item{totD }{number of penalty matrices created for mgcv::gam}
\item{funcs }{as specified}
\item{covariates }{as specified}
\item{smooth.option}{as specified}
}
\description{
This code implements the function pfr() available in refund 0.1-11. It is included
to maintain backwards compatibility.
Functional predictors are entered as a matrix or, in the case of
multiple functional predictors, as a list of matrices using the
\code{funcs} argument. Missing values are allowed in the functional
predictors, but it is assumed that they are observed over the same
grid. Functional coefficients and confidence bounds are returned as
lists in the same order as provided in the \code{funcs} argument, as
are principal component and spline bases. Increasing values of
\code{nbasis} will increase computational time and the values of
\code{nbasis}, \code{kz}, and \code{kb} in relation to each other may
need to be adjusted in application-specific ways.
}
\section{Warning}{
Binomial responses should be specified as a numeric vector rather than as a
matrix or a factor.
}
\examples{
\dontrun{
##################################################################
######### DTI Data Example #########
##################################################################
##################################################################
# For more about this example, see Swihart et al. 2013
##################################################################
## load and reassign the data;
data(DTI2)
Y <- DTI2$pasat ## PASAT outcome
id <- DTI2$id ## subject id
W1 <- DTI2$cca ## Corpus Callosum
W2 <- DTI2$rcst ## Right corticospinal
V <- DTI2$visit ## visit
## prep scalar covariate
visit.1.rest <- matrix(as.numeric(V > 1), ncol=1)
covar.in <- visit.1.rest
## note there is missingness in the functional predictors
apply(is.na(W1), 2, mean)
apply(is.na(W2), 2, mean)
## fit two univariate models
pfr.obj.t1 <- pfr(Y = Y, covariates=covar.in, funcs = list(W1), subj = id, kz = 10, kb = 50)
pfr.obj.t2 <- pfr(Y = Y, covariates=covar.in, funcs = list(W2), subj = id, kz = 10, kb = 50)
### one model with two functional predictors using "smooth.face"
### for smoothing predictors
pfr.obj.t3 <- pfr(Y = Y, covariates=covar.in, funcs = list(W1, W2),
subj = id, kz = 10, kb = 50, nbasis=35,smooth.option="fpca.face")
## plot the coefficient function and bounds
dev.new()
par(mfrow=c(2,2))
ran <- c(-2,.5)
matplot(cbind(pfr.obj.t1$BetaHat[[1]], pfr.obj.t1$Bounds[[1]]),
type = 'l', lty = c(1,2,2), col = c(1,2,2), ylab = "BetaHat",
main = "CCA", xlab="Location", ylim=ran)
abline(h=0, col="blue")
matplot(cbind(pfr.obj.t2$BetaHat[[1]], pfr.obj.t2$Bounds[[1]]),
type = 'l', lty = c(1,2,2), col = c(1,2,2), ylab = "BetaHat",
main = "RCST", xlab="Location", ylim=ran)
abline(h=0, col="blue")
matplot(cbind(pfr.obj.t3$BetaHat[[1]], pfr.obj.t3$Bounds[[1]]),
type = 'l', lty = c(1,2,2), col = c(1,2,2), ylab = "BetaHat",
main = "CCA - mult.", xlab="Location", ylim=ran)
abline(h=0, col="blue")
matplot(cbind(pfr.obj.t3$BetaHat[[2]], pfr.obj.t3$Bounds[[2]]),
type = 'l', lty = c(1,2,2), col = c(1,2,2), ylab = "BetaHat",
main = "RCST - mult.", xlab="Location", ylim=ran)
abline(h=0, col="blue")
##################################################################
# use baseline data to regress continuous outcomes on functional
# predictors (continuous outcomes only recorded for case == 1)
##################################################################
data(DTI)
# subset data as needed for this example
cca = DTI$cca[which(DTI$visit ==1 & DTI$case == 1),]
rcst = DTI$rcst[which(DTI$visit ==1 & DTI$case == 1),]
DTI = DTI[which(DTI$visit ==1 & DTI$case == 1),]
# note there is missingness in the functional predictors
apply(is.na(cca), 2, mean)
apply(is.na(rcst), 2, mean)
# fit two models with single functional predictors and plot the results
fit.cca = pfr(Y=DTI$pasat, funcs = cca, kz=10, kb=50, nbasis=20)
fit.rcst = pfr(Y=DTI$pasat, funcs = rcst, kz=10, kb=50, nbasis=20)
par(mfrow = c(1,2))
matplot(cbind(fit.cca$BetaHat[[1]], fit.cca$Bounds[[1]]),
type = 'l', lty = c(1,2,2), col = c(1,2,2), ylab = "BetaHat",
main = "CCA")
matplot(cbind(fit.rcst$BetaHat[[1]], fit.rcst$Bounds[[1]]),
type = 'l', lty = c(1,2,2), col = c(1,2,2), ylab = "BetaHat",
main = "RCST")
# fit a model with two functional predictors and plot the results
fit.cca.rcst = pfr(Y=DTI$pasat, funcs = list(cca, rcst), kz=10, kb=30, nbasis=20)
par(mfrow = c(1,2))
matplot(cbind(fit.cca.rcst$BetaHat[[1]], fit.cca.rcst$Bounds[[1]]),
type = 'l', lty = c(1,2,2), col = c(1,2,2), ylab = "BetaHat",
main = "CCA")
matplot(cbind(fit.cca.rcst$BetaHat[[2]], fit.cca.rcst$Bounds[[2]]),
type = 'l', lty = c(1,2,2), col = c(1,2,2), ylab = "BetaHat",
main = "RCST")
##################################################################
# use baseline data to regress binary case-status outcomes on
# functional predictors
##################################################################
data(DTI)
# subset data as needed for this example
cca = DTI$cca[which(DTI$visit == 1),]
rcst = DTI$rcst[which(DTI$visit == 1),]
DTI = DTI[which(DTI$visit == 1),]
# fit two models with single functional predictors and plot the results
fit.cca = pfr(Y=DTI$case, funcs = cca, family = "binomial")
fit.rcst = pfr(Y=DTI$case, funcs = rcst, family = "binomial")
par(mfrow = c(1,2))
matplot(cbind(fit.cca$BetaHat[[1]], fit.cca$Bounds[[1]]),
type = 'l', lty = c(1,2,2), col = c(1,2,2), ylab = "BetaHat",
main = "CCA")
matplot(cbind(fit.rcst$BetaHat[[1]], fit.rcst$Bounds[[1]]),
type = 'l', lty = c(1,2,2), col = c(1,2,2), ylab = "BetaHat",
main = "RCST")
##################################################################
######### Octane Data Example #########
##################################################################
data(gasoline)
Y = gasoline$octane
funcs = gasoline$NIR
wavelengths = as.matrix(2*450:850)
# fit the model using pfr and the smoothing option "fpca.face"
fit = pfr(Y=Y, funcs=funcs, kz=15, kb=50,nbasis=35,smooth.option="fpca.face")
matplot(wavelengths, cbind(fit$BetaHat[[1]], fit$Bounds[[1]]),
type='l', lwd=c(2,1,1), lty=c(1,2,2), xlab = "Wavelengths",
ylab = "Coefficient Function", col=1)
}
}
\references{
Goldsmith, J., Bobb, J., Crainiceanu, C., Caffo, B., and Reich, D. (2011).
Penalized functional regression. \emph{Journal of Computational and Graphical
Statistics}, 20(4), 830-851.
Goldsmith, J., Crainiceanu, C., Caffo, B., and Reich, D. (2012). Longitudinal
penalized functional regression for cognitive outcomes on neuronal tract
measurements. \emph{Journal of the Royal Statistical Society: Series C},
61(3), 453-469.
Swihart, Bruce J., Goldsmith, Jeff; and Crainiceanu, Ciprian M. (July 2012).
Testing for functional effects. Johns Hopkins University Dept. of Biostatistics
Working Paper 247, available at \url{https://biostats.bepress.com/jhubiostat/paper247/}
American Statistical Association, 109(508): 1425-1439.
}
\seealso{
\code{\link{rlrt.pfr}}, \code{\link{predict.pfr}}.
}
\author{
Bruce Swihart \email{bruce.swihart@gmail.com} and
Jeff Goldsmith \email{jeff.goldsmith@columbia.edu}
}
|
8f651d7089d8aa8d0d8b9ea3a7a5a1b9b50791a5 | b619e3a24086d825b2a7e53482e2d805b160b2c7 | /Script 1 - Testing Database Connection.R | d0692bd3c3c9949c8aab09293c8c413c3d7eea63 | [] | no_license | erica-ym/primary-care-informatics-research | bcf914db99ea25adc11620c9071ea3d3f184cec4 | c35332b276bbc5abc8fff34c838a0551c2a8dafa | refs/heads/master | 2020-03-15T00:38:31.048247 | 2018-05-02T15:58:56 | 2018-05-02T15:58:56 | 131,873,990 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,146 | r | Script 1 - Testing Database Connection.R | #this is all me learning how to use R, get on the database, and see what's there
library(RODBC)
chan <- odbcConnect("DELPHI",uid="eyarmolm",pwd="NJzQVcfTi8-jGHJUobmh")
print(chan)
res <- sqlQuery(chan,"SELECT name FROM master.dbo.sysdatabases")
print(res)
res <- sqlQuery(chan,"USE [CPCSSN National 2017]")
print(res)
res <- sqlQuery(chan,"SELECT * FROM information_schema.tables")
print(res)
res <- sqlQuery(chan,"SELECT TOP 100 * FROM [PatientDemographic_deid]")
print(res)
res <- sqlQuery(chan,"SELECT TOP 100 * FROM [FamilyHistory]")
View(res)
res <- sqlQuery(chan,"SELECT TOP 100 * FROM [Referral]")
View(res)
res <- sqlQuery(chan,"SELECT COUNT(*) FROM [Billing]")
print(res)
res <- sqlQuery(chan,"SELECT [DiagnosisCode_orig] FROM [Billing] WHERE [DiagnosisCode_orig] LIKE 298")
print(res)
res <- sqlQuery(chan,"SELECT COUNT(*) FROM [Medication]")
print(res)
res <- sqlQuery(chan,"SELECT COUNT(*) FROM [PatientDemographic]")
print(res)
res <- sqlQuery(chan,"SELECT TOP 10 * FROM [RiskFactor]")
print(res)
res <- sqlQuery(chan,"SELECT * FROM RiskFactor WHERE Name_calc NOT LIKE '%NA%'")
print(res)
#print the total count in RiskFactor
res <- sqlQuery(chan,"SELECT COUNT(*) FROM [RiskFactor]")
print(res)
#tell me the people in RiskFactor who have notes about previous family cancers - around 240!
FamilyHis <- sqlQuery(chan,"SELECT Patient_ID,Name_orig FROM [RiskFactor] WHERE Name_orig LIKE '%cancer%'")
print(FamilyHis)
nrow(FamilyHis)
#explore EncounterDiagnosis table
res <- sqlQuery(chan,"SELECT TOP 10 * FROM [EncounterDiagnosis]")
print(res)
#count the number of diagnosis that aren't a custom in that column, 50214
res <- sqlQuery(chan,"SELECT COUNT(*) FROM EncounterDiagnosis WHERE DiagnosisCodeType_orig NOT LIKE '%CUSTOM%'")
print(res)
#count the calc Codes that aren't NA, 76762
res <- sqlQuery(chan,"SELECT COUNT(*) FROM EncounterDiagnosis WHERE DiagnosisCode_calc NOT LIKE '%NA%'")
print(res)
#print the number of people diagnosed with depression as per ICD - 9 code
res <- sqlQuery(chan,"SELECT Patient_ID,DiagnosisText_calc,DiagnosisCode_calc FROM [EncounterDiagnosis] WHERE [DiagnosisCode_calc] LIKE '311%'")
print(res)
|
12e576041c00550ba46f9743598bac0a96eb1bff | 07d2e054273b8dbcff82ff8fb2c4e46a3b2fe826 | /R/BARIS_ui.R | 66938345e1a3466f03c2455b88628a63bee2af5e | [
"MIT"
] | permissive | feddelegrand7/BARIS | 83aa56c648ffc7166b24ec52152c7e7e3d6eb490 | 35c72d43a1e2d38d961f6db9e3c669021bb5290c | refs/heads/master | 2023-04-09T03:39:22.295326 | 2023-03-29T10:57:18 | 2023-03-29T10:57:18 | 236,185,652 | 21 | 0 | NOASSERTION | 2020-11-24T15:10:35 | 2020-01-25T15:07:34 | R | UTF-8 | R | false | false | 5,731 | r | BARIS_ui.R | BARIS_ui <- function() {
ui <- miniUI::miniPage(shiny::tags$style(".fa-lemon {color:gold}"),
shiny::tags$style("body{background-color:#111111 ; color:#F4F4F6"),
miniUI::miniTabstripPanel(
# home tab ----------------------------------------------------------------
miniUI::miniTabPanel(
"Home",
icon = shiny::icon("lemon"),
miniUI::gadgetTitleBar(
"Home data.gouv",
right = miniUI::miniTitleBarButton("done", "Get", primary = T),
left = miniUI::miniTitleBarButton("cancel", "Cancel", primary = T)
),
miniUI::miniContentPanel(
shiny::p("Click on Get to display data.gouv.fr home page data sets"),
shiny::tableOutput(outputId = "home")
)
),
# searching tab -----------------------------------------------------------
miniUI::miniTabPanel(
"Searching",
miniUI::gadgetTitleBar(
"Searching",
right = miniUI::miniTitleBarButton("done1", "Get", primary = T),
left = miniUI::miniTitleBarButton("cancel1", "Cancel", primary = T)
),
miniUI::miniContentPanel(
shiny::p("Queries must be written in French, click on Get the first time, after that just retype another query"),
shiny::textInput(inputId = "search_input", label = "What are you looking for ? "),
shiny::tableOutput(outputId = "search_output")
)
),
# description tab ---------------------------------------------------------
miniUI::miniTabPanel(
"Description",
miniUI::gadgetTitleBar(
"Description",
right = miniUI::miniTitleBarButton("done2", "Get", primary = T),
left = miniUI::miniTitleBarButton("cancel2", "Cancel", primary = T)
),
miniUI::miniContentPanel(
shiny::p("Paste the ID of the data set to get a description, click on Get"),
shiny::textInput(inputId = "description_input", label = "The ID of a Data Set"),
shiny::textOutput(outputId = "description_output")
)
),
# resource tab ------------------------------------------------------------
miniUI::miniTabPanel(
"Resources",
miniUI::gadgetTitleBar(
"Resources",
right = miniUI::miniTitleBarButton("done3", "Get", primary = T),
left = miniUI::miniTitleBarButton("cancel3", "Cancel", primary = T)
),
miniUI::miniContentPanel(
shiny::p("Paste the ID of the data set to list the resources contained in it"),
shiny::textInput(inputId = "resource_input", label = "The ID of a Data Set"),
shiny::tableOutput(outputId = "resource_output")
)
),
# extract tab -------------------------------------------------------------
miniUI::miniTabPanel(
"Extract",
miniUI::gadgetTitleBar(
"Extracting",
right = miniUI::miniTitleBarButton("done4", "Get", primary = T),
left = miniUI::miniTitleBarButton("cancel4", "Cancel", primary = T)
),
miniUI::miniContentPanel(
shiny::textInput(inputId = "resource_id", label = "The ID the resource"),
shiny::textInput(inputId = "resource_format", label = "The format of the resource (in lower case)"),
shiny::textInput(inputId = "resource_name", label = "Give it a name"),
shiny::p("Run the following code in your R session"),
shiny::verbatimTextOutput(outputId = "extract_output", placeholder = T)
)
)
))
# server ------------------------------------------------------------------
server <- function(input, output) {
# home output -------------------------------------------------------------
shiny::observeEvent(input$done, {
output$home <- shiny::renderTable(BARIS::BARIS_home())
})
# search output -----------------------------------------------------------
toListen <- shiny::reactive({
input$done1
})
shiny::observeEvent(toListen(), {
output$search_output <- shiny::renderTable(BARIS::BARIS_search(query = input$search_input))
})
# description output ------------------------------------------------------
description <- shiny::reactive({
input$done2
})
shiny::observeEvent(description(), {
output$description_output <- shiny::renderPrint(BARIS::BARIS_explain(datasetId = input$description_input))
})
# resource output ---------------------------------------------------------
resource <- shiny::reactive({
input$done3
})
shiny::observeEvent(resource(), {
output$resource_output <- shiny::renderTable(BARIS::BARIS_resources(datasetId = input$resource_input))
})
# extract output ----------------------------------------------------------
extract <- shiny::reactive({
input$done4
})
shiny::observeEvent(extract(), {
output$extract_output <- shiny::renderText(
paste(input$resource_name, " <- ", "BARIS::BARIS_extract(", "'",input$resource_id,"'" , " , ","'",input$resource_format,"'", " )", sep = "")
)
})
# cancel ------------------------------------------------------------------
shiny::observeEvent(input$cancel, {
shiny::stopApp(stop(""), call = FALSE)
})
shiny::observeEvent(input$cancel1, {
shiny::stopApp(stop(""), call = FALSE)
})
shiny::observeEvent(input$cancel2, {
shiny::stopApp(stop(""), call = FALSE)
})
shiny::observeEvent(input$cancel3, {
shiny::stopApp(stop(""), call = FALSE)
})
shiny::observeEvent(input$cancel4, {
shiny::stopApp(stop(""), call = FALSE)
})
}
shiny::runGadget(ui, server, viewer = shiny::paneViewer())
}
|
cf0d378f8b936028b6369832cf96b355a88bd153 | 68336f26ef98d15e241782442312ba69d8d0092b | /man/parser.Rd | 61e1aa2bb7dd8fb92a08def00d7d2992e3d4f54d | [] | no_license | hucara/rtweet | dd7dbe661e42cda0add5af2bf41afa1529b79973 | e0ff0d76cc8a9588b3407896c5c2334bcf913490 | refs/heads/master | 2021-01-13T09:15:00.524281 | 2016-10-24T01:53:55 | 2016-10-24T01:53:55 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 653 | rd | parser.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/parse.R
\name{parser}
\alias{parser}
\title{parser}
\usage{
parser(x, n = NULL, return_tweets = TRUE, return_users = TRUE,
clean_tweets = FALSE)
}
\arguments{
\item{x}{nested list of API data returned from fromJSON}
\item{n}{desired number to return}
\item{return_tweets}{logical indicating whether to return tweets data
object.}
\item{return_users}{logical indicating whether to return users data
object.}
\item{clean_tweets}{logical indicating whether to remove non-ASCII
characters in text of tweets. defaults to FALSE.}
}
\description{
parser
}
\keyword{internal}
|
75eec08464c77bf319603b164c8855a0206a9325 | 599256b93ca49fa50aba87739b9e49ee3eba2081 | /pkg/R/objectsAndSrcRefs.R | 86c44a1a84d411e4f52b1adbb83e263ee95eae9e | [] | no_license | mamueller/linkeddocs | aad3a4dcd64942092f4efb2380e99f085b8d86d2 | 8c3d6ddf34a13170cc283b91deaa05733f8100bd | refs/heads/master | 2021-01-20T14:47:33.161695 | 2019-10-10T12:37:08 | 2019-10-10T12:37:08 | 90,661,291 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,488 | r | objectsAndSrcRefs.R |
# vim:set ff=unix expandtab ts=2 sw=2:
objectsAndSrcRefsForClassesAndMethods <- function(pkgDir,pkgEnv){
# the purpose of this function is to combine
# the sourcereferences with the actual objects
# This is done as follows
# 1.) parsing the files into calls (but not evaluating them)
# 2.) finding the corresponding objects in the pkgEnv creating in step 1.).
requireNamespace('pkgload')
pkgName<-as.character(read.dcf(file=file.path(pkgDir,'DESCRIPTION'),fields='Package'))
# create but do not load the namespace
path_r<-normalizePath(file.path(pkgDir,'R'))
codeFiles <- pkgload:::withr_with_collate("C", tools::list_files_with_type(path_r, "code", full.names = TRUE))
results <- list()
j=1
for (fn in codeFiles){
lines <- readLines(fn)
sf <- srcfile(fn)
exprs <- parse(text=lines,srcfile=sf,keep.source=TRUE)
calls <- as.list(exprs)
srcreflist <- attr(exprs,'srcref')
n <- length(exprs)
for (i in seq_len(n)){
expr <- exprs[[i]]
call <- calls[[i]]
call<-standardise_call(call,pkgEnv)
name <- as.character(call[[1]])
if (length(name) > 1) next
parser <- find_parser(name)
if (is.null(parser)) next
# we have to change the parsers not to output the s3 object
res <- parser(call, pkgEnv)#, block)
#stop('')
results[[j]] <- list()
results[[j]][['res']] <- res
results[[j]][['srcref']] <-srcreflist[[i]]
j=j+1
}
}
return(results)
}
|
53b6b6d3ace0ef8112f1449224d7ee121bfefde2 | 09fa86f0a9971787a37a71002b645ff2e705666c | /man/show-methods.Rd | dcd94f7d6a5477981a6c60488b9896c2f19e0280 | [] | no_license | cran/optimalThreshold | d3c541c9cc4a62ebdeb7fb014ad3e88f424f6c94 | 66de5c78d76bb344ea4846c90fe1532216e71e75 | refs/heads/master | 2020-12-22T01:49:28.727109 | 2020-01-13T15:10:05 | 2020-01-13T15:10:05 | 236,634,535 | 0 | 1 | null | null | null | null | UTF-8 | R | false | true | 653 | rd | show-methods.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ClassTrtSelOptThresh.R, R/ClassDiagOptThresh.R
\docType{methods}
\name{show-methods}
\alias{show-methods}
\alias{show,trtSelOptThresh-method}
\alias{show.trtSelOptThresh}
\alias{show,diagOptThresh-method}
\alias{show.diagOptThresh}
\title{Show method}
\usage{
\S4method{show}{trtSelOptThresh}(object)
\S4method{show}{diagOptThresh}(object)
}
\arguments{
\item{object}{a \code{trtSelOptThresh} or a \code{diagOptThresh} S4 object.}
}
\value{
None
}
\description{
Show some of the slots of a \code{trtSelOptThresh} or a \code{diagOptThresh} objects.
}
|
54ba9141d4714ef89b670fa9fd1ef3044c3ca825 | 2b14a65b4b623f96cdc865a5196a6b4a8b3c7cc5 | /04_check_collinearity.R | 5bcebc385bd04459bf75189c4868516a5459ee20 | [] | no_license | JulFrey/understory-tls-cnn | 63b6b317f3401f13c360c12fea5df111f67ee92e | e2654964be06bd15efc5b0ec1898a6ea87cce4ee | refs/heads/main | 2023-08-28T07:02:41.755805 | 2021-10-28T13:01:53 | 2021-10-28T13:01:53 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 8,790 | r | 04_check_collinearity.R | ################################################################################
################################################################################
# RASTER COLINEARITY CHECKS
################################################################################
################################################################################
# load packages
library(raster)
library(sp)
library(Hmisc)
# set path
path_rasters <- "C:/Users/Zoe/Documents/understory_classification/4_Daten/rasters_2cm"
################################################################################
# GETTING RASTER SAMPLES
################################################################################
# get all relevant raster paths
raster_list <- list.files(path_rasters, pattern = "[.]tif", recursive = TRUE, full.names = TRUE)
raster_list <- raster_list[!grepl("nDSM_filtering", raster_list)] # remove unscaled nDSM from list
raster_list <- raster_list[!grepl("DTM", raster_list)] # remove DTM from list
raster_list <- raster_list[!grepl("ortho", raster_list)] # I want to keep this anyway
raster_list <- raster_list[!grepl("temp", raster_list)] # remove temporary files
# load all those rasters
rasters <- list()
for (idx in 1:length(raster_list)) {
rasters[[idx]] <- raster(raster_list[idx])
}
# get unique area names
area_names <- c()
for (name in raster_list) {
name <- strsplit(name, "[.]")[[1]][1]
name <- strsplit(name, "_")
name <- name[[1]][length(name[[1]]) - 1]
area_names <- c(area_names, name)
}
unique_areas <- as.numeric(unique(area_names))
# stack rasters (of same area respectively)
raster_stacks <- c()
for (area in unique_areas) {
single_stack <- stack(rasters[grepl(paste0("_", area, "_"), raster_list)])
raster_stacks <- c(raster_stacks, single_stack)
rm(single_stack)
}
rm(rasters)
# change the band names so they are the same for ever area & are short
band_names <- names(raster_stacks[[1]]) # assumes all have same rasters available
new_band_names <- c()
for (name in band_names) {
name <- strsplit(name, "_")
name <- name[[1]][1:2]
if ("area" %in% name) {
name <- name[1]
}
else {
name <- paste(name[1], name[2], sep = "_")
}
new_band_names <- c(new_band_names, name)
}
for (i in 1:length(raster_stacks)) {
names(raster_stacks[[i]]) <- new_band_names
}
# prepare empty data frame for samples
raster_df <- matrix(ncol = length(new_band_names), nrow = 0)
colnames(raster_df) <- new_band_names
raster_df <- data.frame(raster_df)
# draw samples from each plot & put them all into one data frame
for (i in 1:length(raster_stacks)) {
print(paste0("... getting samples from area ", i))
raster_samples <- sampleRandom(raster_stacks[[i]], size = 1000, cells = FALSE, sp = TRUE)
raster_samples <- as.data.frame(raster_samples@data, xy = FALSE)
raster_df <- rbind(raster_df, raster_samples)
rm(raster_samples)
}
# save to avoid waiting again
write.csv(raster_df, paste0(path_rasters, "/raster_samples_unscaled.csv"), row.names = FALSE)
################################################################################
# read samples
raster_df <- read.csv(paste0(path_rasters, "/raster_samples_unscaled.csv"))
# rescale sample values
for (i in 1:ncol(raster_df)) {
raster_df[, i] <- scale(raster_df[, i])
}
# save to avoid waiting again
write.csv(raster_df, paste0(path_rasters, "/raster_samples_scaled.csv"), row.names = FALSE)
################################################################################
# read samples
raster_df <- read.csv(paste0(path_rasters, "/raster_samples_scaled.csv"))
################################################################################
# PCA 1
################################################################################
# PCA biplot:
# - gleiche Richtung = positiv korreliert
# - entgegengesetzt = negativ korreliert
# - 90 Grad = nicht korreliert
pca_all <- prcomp(raster_df)
summary(pca_all) # with 2 PCs we are above the 90% explained variance
names(pca_all$sdev) <- as.character(1:20)
screeplot(pca_all, las = 1, main = "", cex.lab = 1.5, xlab = "Hauptkomponenten") # to see which PCs explain how much variance
round(pca_all$rotation, 3) # here we can see how important the variables is for each PC
biplot(pca_all, cex = c(0.5, 1)) # , xlim=c(-0.05, 0.05), ylim=c(-0.05, 0.05))
################################################################################
# CLUSTER ANALYSIS
################################################################################
# threshold: spearmans rho = 0.7
# base removal on the contributions of the variables to the first PCA axes
# look at the situation
clust_all_1 <- varclus(as.matrix(raster_df), similarity = c("spearman"))
plot(clust_all_1)
abline(h = 0.7^2, lty = 2, col = "deeppink3")
# clusters:
# - reflectance_max [18] / reflectance_mean [19]
# - curvature_sd [6] / anisotropy_sd [3] / sphericity_sd [15]
# - linearity_max [7] / linearity_mean [8]
# - planarity_max [10] / planarity_mean [11]
# - curvature_mean [5] / anisotropy_mean [2] / sphericity_mean [14] / curvature_max [4] / sphericity_max [13]
# cluster: reflectance_max [18] / reflectance_mean [19]
# keep: reflectance_mean [19]
# remove: reflectance_max [18]
clust_all_2 <- varclus(as.matrix(raster_df[-c(18)]), similarity = c("spearman"))
plot(clust_all_2)
abline(h = 0.7^2, lty = 2, col = "deeppink3")
# cluster: curvature_sd [6] / anisotropy_sd [3] / sphericity_sd [15] (all really similar)
# keep: sphericity_sd [15]
# remove: anisotropy_sd [3] / curvature_sd [6]
clust_all_3 <- varclus(as.matrix(raster_df[-c(18, 3, 6)]), similarity = c("spearman"))
plot(clust_all_3)
abline(h = 0.7^2, lty = 2, col = "deeppink3")
# cluster: linearity_max [7] / linearity_mean [8]
# keep: linearity_max [7]
# remove: linearity_mean [8]
clust_all_4 <- varclus(as.matrix(raster_df[-c(18, 3, 6, 8)]), similarity = c("spearman"))
plot(clust_all_4)
abline(h = 0.7^2, lty = 2, col = "deeppink3")
# cluster: planarity_max [10] / planarity_mean [11]
# keep: planarity_mean [11]
# remove: planarity_max [10]
clust_all_5 <- varclus(as.matrix(raster_df[-c(18, 3, 6, 8, 10)]), similarity = c("spearman"))
plot(clust_all_5)
abline(h = 0.7^2, lty = 2, col = "deeppink3")
# cluster: curvature_mean [5] / anisotropy_mean [2] / sphericity_mean [14] / sphericity_sd [15] / curvature_max [4] / sphericity_max [13]
# keep: curvature_max [4]
# remove: curvature_mean [5] / anisotropy_mean [2] / sphericity_mean [14] / sphericity_sd [15] / sphericity_max [13]
clust_all_6 <- varclus(as.matrix(raster_df[-c(18, 3, 6, 8, 10, 5, 2, 14, 15, 13)]), similarity = c("spearman"))
plot(clust_all_6)
abline(h = 0.7^2, lty = 2, col = "deeppink3")
# checking if everything under threshold
clust_all_6[["sim"]]
clust_all_6[["sim"]] > (0.7^2)
cor(raster_df[-c(18, 3, 6, 8, 10, 5, 2, 14, 15, 13)], method = "spearman")
cor(raster_df[-c(18, 3, 6, 8, 10, 5, 2, 14, 15, 13)], method = "spearman") < 0.7
# save non-collinear data
write.csv(raster_df[-c(18, 3, 6, 8, 10, 5, 2, 14, 15, 13)],
paste0(path_rasters, "/raster_samples_scaled_noncollinear.csv"),
row.names = FALSE
)
################################################################################
# PCA 2
################################################################################
pca_remains <- prcomp(raster_df[-c(18, 3, 6, 8, 10, 5, 2, 14, 15, 13)])
summary(pca_remains) # with 5 PCs we are above the 90% explained variance
names(pca_remains$sdev) <- as.character(1:10)
screeplot(pca_remains, las = 1, main = "", cex.lab = 1.5, xlab = "Hauptkomponenten") # to see which PCs explain how much variance
round(pca_remains$rotation, 3) # here we can see how important the variables is for each PC
biplot(pca_remains, cex = c(0.5, 1)) # , xlim=c(-0.05, 0.05), ylim=c(-0.05, 0.05))
################################################################################
# RESULTS
################################################################################
# keep:
keep_names <- sort(names(raster_df[-c(18, 3, 6, 8, 10, 5, 2, 14, 15, 13)]))
print(keep_names)
# "ortho", "anisotropy_max", "curvature_max", "linearity_max",
# "linearity_sd", "nDSM", "planarity_mean", "planarity_sd",
# "point_density", "reflectance_mean", "reflectance_sd")
# remove:
remove_names <- sort(names(raster_df[c(18, 3, 6, 8, 10, 5, 2, 14, 15, 13)]))
print(remove_names)
# "anisotropy_mean", "anisotropy_sd", "curvature_mean", "curvature_sd",
# "linearity_mean", "planarity_max", "reflectance_max", "sphericity_max",
# "sphericity_mean", "sphericity_sd"
################################################################################ |
d1a32540cc9496ac09ae6c2bc944e3a717e52cbd | 5b5a18142a86e49a7deb2c349b484dadc335920a | /man/dot-typ.Rd | 45e66496570414815b5dbb85e24aa0dce66e9eb2 | [] | no_license | stm/imagefluency | 9067b79f3ad3d6c3e5c683761f89ef2e202cf0ee | d9e6d1e9bea92a20bd464ca3d1b71942cb7cc79e | refs/heads/master | 2023-04-18T05:55:46.240210 | 2022-09-29T17:33:07 | 2022-09-29T17:33:07 | 78,774,174 | 4 | 1 | null | 2021-11-03T15:00:19 | 2017-01-12T18:23:32 | R | UTF-8 | R | false | true | 400 | rd | dot-typ.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/typicality.R
\name{.typ}
\alias{.typ}
\title{.typ}
\usage{
.typ(imglist)
}
\arguments{
\item{imglist}{A list of matrices with numeric values or
integer values.}
}
\value{
a numeric value (RMS contrast)
}
\description{
Returns the typicality of a list of images as the correlation with the mean image.
}
\keyword{internal}
|
dec8005fc100cd2bc700b3dfd260fa8d12f14aff | da627ef8abba2774be316152556d871160e1ac15 | /R/binCDFs.R | e07c03804c26d301f05f55b9ef5cbb5638789daa | [] | no_license | fditraglia/binivdoctr | fae27a133659a0378f229aa5f1b34a7d226a33f4 | 907482963e82a95fff5a7672a422610f61a3db9c | refs/heads/master | 2020-04-12T08:24:40.322701 | 2016-08-23T17:16:04 | 2016-08-23T17:16:04 | 52,390,880 | 0 | 2 | null | 2017-04-29T19:57:49 | 2016-02-23T20:53:29 | R | UTF-8 | R | false | false | 4,077 | r | binCDFs.R | #' Make plot of bounds on a0 and a1 implied by observable CDFs
#'
#' @param inData Dataframe with columns named Tobs (binary), y, and z (binary)
#' @param inc Increment for tau
#' @param frac Location of dashed lines: quantiles of y distribution
#'
#' @return Make plot of bounds on a0 and a1
#' @export
#'
#' @examples
plotAlphaBounds <- function(inData, inc = 0.01, j = 10){
Tobs <- inData$Tobs
z <- inData$z
y <- inData$y
p0 <- mean(Tobs[z == 0])
p1 <- mean(Tobs[z == 1])
y00 <- y[Tobs == 0 & z == 0]
y01 <- y[Tobs == 0 & z == 1]
y10 <- y[Tobs == 1 & z == 0]
y11 <- y[Tobs == 1 & z == 1]
F00 <- ecdf(y00)
F01 <- ecdf(y01)
F10 <- ecdf(y10)
F11 <- ecdf(y11)
F00tilde <- function(tau){
(1 - p0) * F00(tau)
}
F01tilde <- function(tau){
(1 - p1) * F01(tau)
}
F10tilde <- function(tau){
p0 * F10(tau)
}
F11tilde <- function(tau){
p1 * F11(tau)
}
# Bounds for a0
B0_z0_a0 <- function(tau){
F10tilde(tau) / (F10tilde(tau) + F00tilde(tau))
}
B1_z0_a0 <- function(tau){
(1 - F10tilde(tau) - (1 - p0)) / (1 - F10tilde(tau) - F00tilde(tau))
}
B0_z1_a0 <- function(tau){
F11tilde(tau) / (F11tilde(tau) + F01tilde(tau))
}
B1_z1_a0 <- function(tau){
(1 - F11tilde(tau) - (1 - p1)) / (1 - F11tilde(tau) - F01tilde(tau))
}
# Bounds for a1
B0_z0_a1 <- function(tau){
F00tilde(tau) / (F00tilde(tau) + F10tilde(tau))
}
B1_z0_a1 <- function(tau){
(1 - F00tilde(tau) - p0) / (1 - F00tilde(tau) - F10tilde(tau))
}
B0_z1_a1 <- function(tau){
F01tilde(tau) / (F01tilde(tau) + F11tilde(tau))
}
B1_z1_a1 <- function(tau){
(1 - F01tilde(tau) - p1) / (1 - F01tilde(tau) - F11tilde(tau))
}
tau_B0_z0 <- seq(max(sort(y00)[j], sort(y10)[j]), max(y), inc)
tau_B0_z1 <- seq(max(sort(y01)[j], sort(y11)[j]), max(y), inc)
tau_B1_z0 <- seq(min(y), min(sort(y00, TRUE)[j], sort(y10, TRUE)[j]), inc)
tau_B1_z1 <- seq(min(y), min(sort(y01, TRUE)[j], sort(y11, TRUE)[j]), inc)
plot_min <- min(c(tau_B0_z0, tau_B0_z1, tau_B1_z0, tau_B1_z1))
plot_max <- max(c(tau_B0_z0, tau_B0_z1, tau_B1_z0, tau_B1_z1))
# Set up side-by-side plot with legend beneath
op <- par(no.readonly = TRUE)
par(mfrow = c(1, 2), oma = c(4, 1, 1, 1))
# Make plot for a0
a0_B0_z0 <- B0_z0_a0(tau_B0_z0)
a0_B1_z0 <- B1_z0_a0(tau_B1_z0)
a0_B0_z1 <- B0_z1_a0(tau_B0_z1)
a0_B1_z1 <- B1_z1_a0(tau_B1_z1)
a0_min <- min(c(a0_B0_z0, a0_B1_z0, a0_B0_z1, a0_B1_z1))
a0_max <- max(c(a0_B0_z0, a0_B1_z0, a0_B0_z1, a0_B1_z1))
plot(tau_B0_z0, a0_B0_z0, type = 'l', xlab = expression(tau),
ylab = expression(bar(alpha[0])), lwd = 2, ylim = c(a0_min, a0_max),
xlim = c(plot_min, plot_max), col = "blue",
main = substitute(paste(alpha[0], " Upper Bounds")))
points(tau_B1_z0, a0_B1_z0, type = 'l', col = "red", lwd = 2)
points(tau_B0_z1, a0_B0_z1, type = 'l', col = "green", lwd = 2)
points(tau_B1_z1, a0_B1_z1, type = 'l', col = "orange", lwd = 2)
# Make plot for a1
a1_B0_z0 <- B0_z0_a1(tau_B0_z0)
a1_B1_z0 <- B1_z0_a1(tau_B1_z0)
a1_B0_z1 <- B0_z1_a1(tau_B0_z1)
a1_B1_z1 <- B1_z1_a1(tau_B1_z1)
a1_min <- min(c(a1_B0_z0, a1_B1_z0, a1_B0_z1, a1_B1_z1))
a1_max <- max(c(a1_B0_z0, a1_B1_z0, a1_B0_z1, a1_B1_z1))
plot(tau_B0_z0, a1_B0_z0, type = 'l', xlab = expression(tau),
ylab = expression(bar(alpha[1])), lwd = 2, ylim = c(a1_min, a1_max),
xlim = c(plot_min, plot_max), col = "blue",
main = substitute(paste(alpha[1], " Upper Bounds")))
points(tau_B1_z0, a1_B1_z0, type = 'l', col = "red", lwd = 2)
points(tau_B0_z1, a1_B0_z1, type = 'l', col = "green", lwd = 2)
points(tau_B1_z1, a1_B1_z1, type = 'l', col = "orange", lwd = 2)
# Add legend beneath side-by-side plots
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", legend = c("B0, z0", "B1, z0", "B0, z1", "B1, z1"), xpd = TRUE,
horiz = TRUE, inset = c(0,0), bty = "n",
fill = c("blue", "red", "green", "orange"), cex = 1.3)
par(op)
}
|
07bd91266421d4d5e8e3dc40af6226e99b11c418 | edc6f37b37f483bcabc9ad95b857db59c90d09c1 | /tennis-win-probability.R | 3065a888b88821fd0b521e06e3b95de62e95ae7f | [
"MIT"
] | permissive | topfunky/r-tennis-win-probability | bb91412c7b9b476198fc49fe9248ee78aa5f3caf | c1b307f6e4d218b16d17faf514453364e01d9377 | refs/heads/main | 2023-05-10T10:23:37.885293 | 2021-06-14T04:43:07 | 2021-06-14T04:43:07 | 338,945,263 | 1 | 0 | MIT | 2021-02-15T02:04:23 | 2021-02-15T02:03:22 | null | UTF-8 | R | false | false | 13,262 | r | tennis-win-probability.R | # Load libraries
# install.packages("devtools")
# devtools::install_github("topfunky/gghighcontrast")
library(tidyverse)
library(gghighcontrast)
library(scales)
library(xgboost)
library(caTools)
library(dplyr)
library(caret)
library(Ckmeans.1d.dp)
library(future)
library(future.apply)
is_running_in_r_studio <- Sys.getenv("RSTUDIO") == "1"
if (is_running_in_r_studio) {
plan(multisession)
} else {
plan(multicore)
}
future.seed = TRUE
DEVELOPMENT_MODE = FALSE
# Don't display numbers in scientific notation
options(scipen = 9999)
# Colors
dayglo_orange = "#ff6700"
light_blue = "#0098ff"
red = "#ff0000"
grey = "#808080"
kiwi_green = "#8ee53f"
dark_olive_green = "#556b2f"
dark_raspberry = "#872657"
rich_black = "#010203"
yellowgreen_neon = "#8bff00"
light_grey = "#999999"
directories <- list("data", "out", "out/w", "out/m")
for (directory in directories) {
if (!dir.exists(directory)) {
dir.create(directory)
}
}
# Point by point records for matches: "w" or "m".
#
# Caches remote file if missing from local filesystem. Returns data frames.
charting_points <- function(gender) {
retrieve_csv_and_cache_data_locally(
str_interp(
"https://raw.githubusercontent.com/JeffSackmann/tennis_MatchChartingProject/master/charting-${gender}-points.csv"
)
)
}
retrieve_csv_and_cache_data_locally <- function(url) {
filename <- basename(url)
# Check for cache or download if missing
local_filename_with_path = str_interp("data/${filename}")
if (!file.exists(local_filename_with_path)) {
download.file(url, local_filename_with_path)
}
data <- read_csv(local_filename_with_path)
return(data)
}
build_win_prediction_model <- function(data) {
set.seed(525)
# Sample 80% of rows
indexes = sample(1:nrow(data),
round(nrow(data) * 0.8),
replace = FALSE)
train <- data[indexes, ]
y = as.numeric(train$Player1Wins)
x = train |> select(SetDelta, GmDelta, Pts1Delta, PtCountdown, Player1IsServing)
xgb_train <- xgb.DMatrix(data = as.matrix(x), label = y)
xgb_params <-
list(
booster = "gbtree",
objective = "binary:logistic",
nthread = -1,
# default: use as many cores as possible
eta = 0.3,
gamma = 0,
max_depth = 6,
min_child_weight = 1,
subsample = 1,
colsample_bytree = 1
)
win_prediction_model <- xgb.train(
params = xgb_params,
data = xgb_train,
nrounds = 30,
verbose = 1
)
return(win_prediction_model)
}
render_importance_chart <- function(model, gender) {
# Importance
importance <- xgboost::xgb.importance(feature_names = colnames(model),
model = model)
importance_plot = xgboost::xgb.ggplot.importance(importance_matrix = importance) +
theme_high_contrast(base_family = "InputMono")
ggsave(
str_interp("out/${gender}/importance.png"),
plot = importance_plot,
width = 6,
height = 4
)
}
populate_each_row_with_prediction <- function(pbp, gender) {
win_prediction_model <- build_win_prediction_model(pbp)
render_importance_chart(win_prediction_model, gender)
pbp %<-% {
pbp |>
mutate(win_probability_player_1 =
predict(win_prediction_model, as.matrix(
pbp[row_number(),] |> select(
SetDelta,
GmDelta,
Pts1Delta,
PtCountdown,
Player1IsServing
)
), reshape = TRUE))
}
return(pbp)
}
plot_for_match_id <- function(data, single_match_id, prefix) {
single_match_records <- data |> filter(match_id == single_match_id)
plot <- plot_for_data(single_match_records,
"white",
dayglo_orange)
ggsave(
str_interp("out/${prefix}/${single_match_id}.png"),
plot = plot,
width = 8,
height = 4
)
}
# Plot a single match.
#
# Returns the plot which can be saved to disk or displayed otherwise.
plot_for_data <-
function(data,
foreground_color,
background_color) {
this_match <- data[1,]
plot <- ggplot(data,
aes(x = Pt, y = win_probability_player_1)) +
# 50% reference line
geom_hline(yintercept = 0.5,
color = foreground_color,
size = 1) +
geom_vline(
data = data |> filter(IsStartOfSet),
aes(xintercept = Pt),
color = foreground_color,
size = 0.25
) +
# Win Probability
geom_line(size = 0.8) +
annotate(
"text",
x = 5,
y = 0.95,
label = this_match$Player1,
family = "InputMono",
color = foreground_color,
size = 2
) +
annotate(
"text",
x = 5,
y = 0.05,
label = this_match$Player2,
family = "InputMono",
color = foreground_color,
size = 2
) +
# Formatting
scale_y_continuous(labels = percent, limits = c(0, 1)) +
theme_high_contrast(
base_family = "InputMono",
background_color = background_color,
foreground_color = foreground_color
) +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
labs(
title = str_interp(
"${this_match$Player1} vs ${this_match$Player2} @ ${this_match$Tournament} ${this_match$MatchDate}"
),
subtitle = "Custom win probability model for tennis",
caption = "Model: topfunky.com • Data: The Match Charting Project",
x = "Plays",
y = "Win Probability"
)
}
plot_accuracy <-
function(data,
gender,
foreground_color,
background_color) {
data <- data |>
filter(!is.na(SetCount)) |>
mutate(bin_pred_prob = round(win_probability_player_1 / 0.05) * 0.05) |>
group_by(SetCount, bin_pred_prob) |>
# Calculate the calibration results:
summarize(
n_plays = n(),
n_wins = sum(Player1Wins),
bin_actual_prob = n_wins / n_plays
) |>
ungroup()
plot <- data |>
ggplot() +
geom_point(aes(x = bin_pred_prob,
y = bin_actual_prob,
size = n_plays),
color = yellowgreen_neon) +
geom_smooth(aes(x = bin_pred_prob, y = bin_actual_prob),
color = foreground_color,
method = "loess") +
geom_abline(
slope = 1,
intercept = 0,
color = foreground_color,
lty = 2 # dashed
) +
scale_x_continuous(labels = percent, limits = c(0, 1)) +
scale_y_continuous(labels = percent, limits = c(0, 1)) +
theme_high_contrast(
base_family = "InputMono",
background_color = background_color,
foreground_color = foreground_color
) +
theme(legend.position = "none") +
labs(
title = str_interp("Model Accuracy by Set: ${gender}"),
subtitle = "Model prediction vs actual win percentage",
caption = "Model: topfunky.com • Data: The Match Charting Project",
x = "Predicted",
y = "Actual"
) +
facet_wrap(~ SetCount, nrow = 2)
}
# Either process the data, write a cached version, and return it,
# or just return the cached version from disk for quicker processing.
load_and_clean_data <- function(data, gender) {
local_data_cache_filename <- str_interp("data/${gender}.rds")
if (DEVELOPMENT_MODE) {
# Always recalculate if in development mode
return(clean_data(data))
} else if (!file.exists(local_data_cache_filename)) {
# Recalculate and save to disk
cleaned_data <- clean_data(data)
write_rds(cleaned_data, local_data_cache_filename)
return(cleaned_data)
} else {
# Use cache
cleaned_data <- readRDS(local_data_cache_filename)
return(cleaned_data)
}
}
# Turn "0", "15", "30", "40", "AD" to 1, 2, 3, 4, 5
# so traditional math can be done against the points scored.
convert_pts_to_integer <- function(v) {
case_when(
v == "0" ~ 0,
v == "15" ~ 1,
v == "30" ~ 2,
v == "40" ~ 3,
v == "AD" ~ 4,
# Tiebreak
v == "1" ~ 1,
v == "2" ~ 2,
v == "3" ~ 3,
v == "4" ~ 4,
v == "5" ~ 5,
v == "6" ~ 6,
)
}
clean_data <- function(data) {
pbp <- data |>
# Fix problematic encoding on some rows
mutate(match_id = iconv(match_id, "ASCII", "UTF-8")) |>
# The `separate` function splits a string like "20200823-A-B-C" on dashes.
# Grab only the first piece as a new `date_string` column.
separate(
match_id,
c(
"date_string",
"Gender",
"Tournament",
"MatchRound",
"Player1",
"Player2"
),
remove = FALSE,
sep = "-"
) |>
separate(Pts, c("PtsA", "PtsB"), remove = FALSE, sep = "-") |>
mutate(
PtsA = convert_pts_to_integer(PtsA),
PtsB = convert_pts_to_integer(PtsB),
# If server is Player1, then PtsA will be the server's score
Pts1Delta = ifelse(Svr == 1, (PtsA - PtsB), (PtsB - PtsA)),
Pts2Delta = ifelse(Svr == 2, (PtsA - PtsB), (PtsB - PtsA)),
MatchDate = as.Date(date_string, format = "%Y%m%d"),
Player1 = str_replace_all(Player1, "_", " "),
Player2 = str_replace_all(Player2, "_", " "),
Tournament = str_replace_all(Tournament, "_", " "),
Player1IsServing = as.numeric(Svr == 1)
)
# Get final play to determine match winner
final_play_for_each_match <-
pbp |>
group_by(match_id) |>
filter(Pt == max(Pt)) |>
mutate(
Player1Wins = as.numeric(PtWinner == 1),
Pt = Pt + 1,
PtTotal = Pt
) |>
ungroup()
# Select only a few fields
match_winners <- final_play_for_each_match |>
select(match_id, Player1Wins, PtTotal)
# Join so all rows include the match winner
pbp <-
pbp |>
inner_join(match_winners, by = "match_id")
# Create rows for final outcome.
# The point by point frames don't include the final score.
match_result_plays <- final_play_for_each_match |>
mutate(
Set1 = ifelse(Player1Wins == 1, Set1 + 1, Set1),
Set2 = ifelse(Player1Wins == 0, Set2 + 1, Set2),
Gm1 = 0,
Gm2 = 0,
Pts = "0-0",
Pts1Delta = 0,
Pts2Delta = 0
) |>
select(
match_id,
Pt,
Set1,
Set2,
Gm1,
Gm2,
Pts,
Player1Wins,
MatchDate,
Gender,
Tournament,
MatchRound,
Player1,
Player2,
PtTotal,
Pts1Delta,
Pts2Delta,
Player1IsServing
)
pbp <- bind_rows(pbp, match_result_plays)
# Calculate delta for Sets, Games, Pt (number of plays)
pbp <- pbp |>
mutate(
SetDelta = Set1 - Set2,
GmDelta = Gm1 - Gm2,
PtCountdown = PtTotal - Pt,
IsStartOfSet = (Pt < PtTotal & (Set1 > lag(Set1) |
Set2 > lag(Set2))),
# Calculate set but index from 1 (first set played is Set 1)
SetCount = ifelse(Pt < PtTotal, Set1 + Set2 + 1, NA)
) |>
arrange(match_id, Pt)
return(pbp)
}
run_w <- function() {
match_ids <- list(
"20190928-W-Wuhan-F-Aryna_Sabalenka-Alison_Riske",
"20190325-W-Miami-R16-Caroline_Wozniacki-Su_Wei_Hsieh",
"20190325-W-Miami-R16-Ashleigh_Barty-Kiki_Bertens",
"20080705-W-Wimbledon-F-Venus_Williams-Serena_Williams"
)
pbp <- load_and_clean_data(charting_points("w"), "w") |>
filter(MatchDate > as.Date("2005-01-01")) |>
populate_each_row_with_prediction("w")
for (single_match_id in match_ids) {
plot_for_match_id(pbp, single_match_id, "w")
}
plot <- plot_accuracy(pbp, "Women", light_grey, "#222222")
ggsave(
"out/w/accuracy.png",
plot = plot,
width = 6,
height = 4
)
}
run_m <- function() {
match_ids <- list(
"20210212-M-Australian_Open-R32-Andrey_Rublev-Feliciano_Lopez",
"20080811-M-Los_Angeles-F-Andy_Roddick-Juan_Martin_Del_Potro",
"20200130-M-Australian_Open-SF-Roger_Federer-Novak_Djokovic",
"20050403-M-Miami_Masters-F-Roger_Federer-Rafael_Nadal",
"20180905-M-US_Open-QF-Rafael_Nadal-Dominic_Thiem",
"20190704-M-Wimbledon-R64-Rafael_Nadal-Nick_Kyrgios"
)
pbp <- load_and_clean_data(charting_points("m"), "m") |>
filter(MatchDate > as.Date("2005-01-01")) |>
populate_each_row_with_prediction("m")
for (single_match_id in match_ids) {
plot_for_match_id(pbp, single_match_id, "m")
}
plot <- plot_accuracy(pbp, "Men", light_grey, "#222222")
ggsave(
"out/m/accuracy.png",
plot = plot,
width = 6,
height = 4
)
# Decision tree experiment
require(rpart)
require(rpart.plot)
binary.model <-
rpart(Player1Wins ~ SetDelta + GmDelta + Pts1Delta + PtCountdown + Player1IsServing,
data = pbp)
png(
filename = "out/m/decision_tree_plot.png",
width = 2000,
height = 2000,
res = 216
)
decision_tree_plot = binary.model |> rpart.plot(
main = "Match Win Decision Tree",
roundint = FALSE,
cex = 0.8,
fallen.leaves = TRUE,
extra = 101
)
dev.off()
}
# run_w()
# run_m()
# Run in parallel
functions <- list(run_w, run_m)
future_lapply(functions, function(x) {
x()
}, future.seed = TRUE)
|
806a5285aa0bd1c10a219897091ffa8a56f72378 | f51ce17cc7734bbcb1de533b3822da4a91326ce3 | /man/getNativeLibsPath.Rd | 7503b0d5680903bd63af798a8f4c1c1eb3daa348 | [] | no_license | Open-Systems-Pharmacology/rClr | cebc10301ec623ceb5f93d5e7c92771f374655f1 | c764e5d8554377555c90323e63564aa73d4eb58b | refs/heads/master | 2023-09-01T11:46:44.834518 | 2022-06-01T15:50:23 | 2022-06-01T15:50:23 | 225,075,749 | 1 | 7 | null | 2023-09-06T09:08:24 | 2019-11-30T22:07:56 | C# | UTF-8 | R | false | true | 650 | rd | getNativeLibsPath.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/rClr-exported.R
\name{getNativeLibsPath}
\alias{getNativeLibsPath}
\title{Architecture dependent path to the rClr native library}
\usage{
getNativeLibsPath(pkgName)
}
\arguments{
\item{pkgName}{the name of a package, e.g. 'rClr'}
}
\value{
the prospective path in which a native library would be found, e.g. c:/R/library/rClr/libs/x64
}
\description{
Guess the directory where to expect the architecture dependent native library of a specified package
e.g. for the package rClr, ${R_HOME}/library/rClr/libs/x64
This is a utility that is not specific to the rClr package
}
|
464606cae61baed1d97d5bc492a21fb003fd7ee5 | 7dba935c143445aed9957092c40435dd0e75e1a8 | /App.R | 398c35449728ef49aaeba507c733d5e76a1c33cf | [] | no_license | RudyVeenhoff/TFA-Shiny-App | 714844d5634f3f76e1b11998014e3da97d6affbd | 2e52e2cb8c915ad64457caab4fdbab5bb6e22c97 | refs/heads/master | 2021-01-12T06:02:15.682515 | 2016-12-24T11:35:18 | 2016-12-24T11:35:18 | 77,280,030 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 8,685 | r | App.R | library(plotly)
library(shinydashboard)
library(lubridate)
library(forecast)
halfyearData <- read.csv("halfyearData.csv")
colNames <- gsub("^X","",colnames(halfyearData))
colNames <- as.numeric(colNames)
## used by fullNameOfDay()
daysof2011 <- seq(as.POSIXct("2011/1/1"),as.POSIXct("2011/12/31"),"day")
# returns the time, e.g. "13:45"
convertTime <- function(min){
time <- paste0(min %/% 60, ":", min %% 60)
format(strptime(time, format = "%H:%M"), "%H:%M")
}
### creating the a vector with all the clock times
timeVector <- NULL
for(i in 0:1439){
timeVector <- c(timeVector,convertTime(i))
}
## returns the date e.g. "Thursday 27 October 2011"
fullNameOfDay <- function(n){
format(daysof2011[n],"%A %d %B %Y")
}
yearDay <- function(n){
yday(as.character(n))
}
## select day from DF
dayDF <- function(n){
beginofday <- (n-1)*60*24+1
endofday <- n*60*24
halfyearData[beginofday:endofday,]
}
weekDF <-function(n){
beginofweek <- (n-7)*60*24+1
endofweek <- (n-1)*60*24
halfyearData[beginofweek:endofweek,]
}
header <- dashboardHeader(title = "Traffic Forecasting App", titleWidth = 250)
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("Plot", icon=icon("line-chart"),
menuSubItem("Speed vs Time", tabName="TvS"),
menuSubItem("Speed vs Location", tabName="LvS"),
menuSubItem("Heatmap", tabName="heatmap")),
menuItem("Forecast", tabName="fc", icon=icon("car")),
menuItem("Documentation",icon=icon("info"),
menuSubItem("About", tabName="info"),
menuSubItem("Plot", tabName="infoPlot"),
menuSubItem("Forecasting", tabName="infofc")
)
)
)
body <- dashboardBody(
tabItems(
tabItem(tabName = "infoPlot", includeMarkdown("Plot.Rmd")),
tabItem(tabName = "infofc", includeMarkdown("Forecast.Rmd")),
tabItem(tabName = "info", includeMarkdown("Info.Rmd")),
tabItem(tabName = "fc",
fluidRow(box(width = 12, plotlyOutput("plotfc"))),
fluidRow(box(width = 4,
title = "Input Date", solidHeader = TRUE, status = "info",
dateInput(inputId = "dateInputId4", label = NULL,
value = "2011-01-08",
min = "2011-01-08",
max = "2011-6-31")),
box(width = 4,
title = "Select Mile Marker", solidHeader = TRUE, status = "info",
uiOutput("selectInput2")),
box(width = 4, background = "navy",
actionButton("actionButton",
label = "Toggle Actual Speeds On/Off")))),
tabItem(tabName = "TvS", fluidRow(box(width = 12, plotlyOutput("plottvs"))),
fluidRow(box(width = 4,
title = "Input Date", solidHeader = TRUE, status = "info",
dateInput(inputId = "dateInputId1", label = NULL,
value = "2011-01-01",
min = "2011-01-01",
max = "2011-6-31")),
box(width = 4,
title = "Select Mile Marker", solidHeader = TRUE, status = "info",
uiOutput("selectInput")))),
tabItem(tabName = "LvS", fluidRow(box(width = 12, plotlyOutput("plotlvs"))),
fluidRow(box(width = 4, height = "137",
title = "Input Date", solidHeader = TRUE, status = "info",
br(),
dateInput(inputId = "dateInputId2", label = NULL,
value = "2011-01-01",
min = "2011-01-01",
max = "2011-6-31")),
box(width = 4, height = "137", title = "Input Minutes",
solidHeader = TRUE, status = "info",
sliderInput("minutes", label = NULL,
min = 0,
max = 1439,
value = 0)))),
tabItem(tabName = "heatmap", fluidRow(box(width = 12, plotlyOutput("plotheatmap"))),
fluidRow(box(width = 4,
title = "Input Date", solidHeader = TRUE, status = "info",
dateInput(inputId = "dateInputId3", label = NULL,
value = "2011-01-01",
min = "2011-01-01",
max = "2011-6-31"))))
)
)
ui = dashboardPage(header,sidebar,body)
#############################################
server = function(input, output){
output$selectInput <- renderUI({
selectInput("location", label = NULL,
choices = colNames,
selected = 1)
})
output$selectInput2 <- renderUI({
selectInput("location2", label = NULL,
choices = colNames)
})
output$plottvs <- renderPlotly({
n <- yearDay(input$dateInputId1)
df <- dayDF(n)
colNumber<- which(colNames == input$location)
speeds <- df[,colNumber]
numericSpeeds <- as.numeric(speeds)
plottingData <- data.frame(Time=timeVector, Speed=numericSpeeds)
p <- plot_ly(data = plottingData, x = ~Time) %>%
add_lines(y = ~Speed, line = list(color = "#00526d", width = .5)) %>%
layout(title = paste(fullNameOfDay(n),"@",input$location),
xaxis= list(title = ""),
yaxis= list(title= "Speed in km/h"),
margin = list(b=60))
})
output$plotlvs <- renderPlotly({
n <- yearDay(input$dateInputId2)
df <- dayDF(n)
minutes <- input$minutes
speeds <- df[minutes+1,]
numericSpeeds <- as.numeric(speeds)
plottingData <- data.frame(Hectometerpaaltje=colNames, Speed=numericSpeeds)
p <- plot_ly(data = plottingData, x = ~Hectometerpaaltje) %>%
add_lines(y = ~Speed, line = list(color = "#2e9659", width = 3)) %>%
layout(title = paste(fullNameOfDay(n), convertTime(minutes)),
xaxis= list(title = ""),
yaxis= list(title= "Speed in km/h"))
})
output$plotheatmap <- renderPlotly({
n <- yearDay(input$dateInputId3)
df <- dayDF(n)
x <- list(title = "The 143 measurement points on the A13")
y <- list(title = "Minutes past midnight")
p <- plot_ly(z=as.matrix(df), type="heatmap") %>%
colorbar(title = "Speed in km/h") %>%
layout(title = fullNameOfDay(n),xaxis = x,yaxis = y)
})
output$plotfc <- renderPlotly({
n <- yearDay(input$dateInputId4)
colNumber <- which(colNames == input$location2)
tsdata <- weekDF(n)
tsdata <- tsdata[,colNumber]
fit <- stlf(ts(tsdata[1:length(tsdata)], frequency=1440), h=1440)
plottingData <- data.frame(Time=timeVector, PredictedSpeed=fit$mean,
TrueValues = dayDF(n)[,colNumber])
p <- plot_ly(data = plottingData, x = ~Time) %>%
add_lines(y = ~PredictedSpeed,
line = list(color = "#2e9659", width = 1),
name = "Forecast") %>%
layout(title = paste(fullNameOfDay(n),"@",input$location2),
xaxis= list(title = ""),
yaxis= list(title= "Speed in km/h"),
margin = list(b=60))
if(input$actionButton %% 2 == 1){
p <- p %>%
add_lines(y = ~TrueValues,
line = list(color = "#f9a65a", width = 1),
name="Observed Speed") %>%
layout(legend = list(x = 0, y = 0))
}
p
})
}
shinyApp(ui, server)
|
e9f6225c557ae25004660b18f84ba96a6a4c9131 | 81ad4adf9aac78235df4198999ab1ab397e4ffd9 | /gmd-8-3441-2015-supplement/SHIMMER/library/SHIMMER_set_start_values.R | 4959aabe1ffcd4ac0cf583a3581fcdf41dbfbbe9 | [] | no_license | jbradley8365/2015_SHIMMER_GMD | 8ee763430a6db33c8a3631581d3066b2839f1496 | 4e9b9829c03d9e20085cb382dd24b22b726ada57 | refs/heads/master | 2021-04-27T02:25:03.788710 | 2018-02-24T03:11:56 | 2018-02-24T03:11:56 | 122,695,459 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,964 | r | SHIMMER_set_start_values.R | # Set the initial conditions
# Units are micrograms per gram (ug/g)
# State variables:
# A1 = Autotrophs (subglacial chemoautotrophs)
# A2 = Autotrophs (soil)
# A3 = Autotrophs (soil N-fixers)
# H1 = Heterotrophs (subglacial)
# H2 = Heterotrophs (soil)
# H3 = Heterotrophs (soil N-fixers)
# S1 = Particulate Carbon Substrate - Labile
# S2 = Particulate Carbon Substrate - Refractory
# DIN = Dissolved Inrganic Nitrogen
# DIP = Dissolved Inorganic Phosphorus
# PON1 = Organic Nitrogen - Labile
# PON2 = Organic Nitrogen - Refractory
# POP1 = Organic Phosphorus - Labile
# POP2 = Organic Phosphorus - Refractory
# Derived variables:
# cum_A1<-xx[15] # Cumulative A1 (increase in biomass)
# cum_A2<-xx[16] # Cumulative A2 (increase in biomass)
# cum_A3<-xx[17] # Cumulative A3 (increase in biomass)
# cum_H1<-xx[18] # Cumulative H1 growth
# cum_H2<-xx[19] # Cumulative H2 growth
# cum_H3<-xx[20] # Cumulative H3 growth
# cum_DIC_A<-xx[21] # Cumulative DIC produced by autotrophs
# cum_DIC_H<-xx[22] # Cumulative DIC produced by heterotrophs
# cum_DIN<-xx[23] # Cumulative DIN consumed by everything
# cum_nf<-xx[24] # cum_nf = Cumulative N2 fixed
# cum_I_Sub<-xx[25] # Cumulative input of substrate (multiplied by v_Sub)
# cum_G_X<-xx[26] # Cumulative contribution of deaths and exudates to substrate
start<-c(A1=0.617,
A2=0.617,
A3=0.617,
H1=0.617,
H2=0.617,
H3=0.617,
S1=278.520,
S2=417.780,
DIN=0.160,
DIP=0.500,
PON1=39.440,
PON2=59.160,
POP1=23.120,
POP2=34.680,
cum_A1=0,
cum_A2=0,
cum_A3=0,
cum_H1=0,
cum_H2=0,
cum_H3=0,
cum_DIC_A=0,
cum_DIC_H=0,
cum_DIN=0,
cum_nf=0,
cum_I_Sub=0,
cum_G_X=0
)
#.................................................................................
|
4ed94919cf86ace1cb3d8a123d410973a3c264c8 | 0a906cf8b1b7da2aea87de958e3662870df49727 | /biwavelet/inst/testfiles/rcpp_row_quantile/libFuzzer_rcpp_row_quantile/rcpp_row_quantile_valgrind_files/1610554105-test.R | a615108a5abec2b396008cc1c3dfcefbaa57b20a | [] | no_license | akhikolla/updated-only-Issues | a85c887f0e1aae8a8dc358717d55b21678d04660 | 7d74489dfc7ddfec3955ae7891f15e920cad2e0c | refs/heads/master | 2023-04-13T08:22:15.699449 | 2021-04-21T16:25:35 | 2021-04-21T16:25:35 | 360,232,775 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 405 | r | 1610554105-test.R | testlist <- list(data = structure(c(9.4882464106786e+77, 9.48968865377627e+170, 6.48706360978439e+174, 1.6260514384671e-260, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(8L, 8L)), q = 0)
result <- do.call(biwavelet:::rcpp_row_quantile,testlist)
str(result) |
1f27577807199b2463dbbd18e02689c4cfca25e4 | 8377e267221e5331fd94aebc8e0b866df1e40e28 | /my_function.R | 2682d3fac747c0039067e26c397fb4926ff4670a | [] | no_license | alijg/Holla_earth | 32a962e9232c69f4df0b1bb9854dbb309d7525dc | 0f97a15d6c4b0f2622f185f93672cf5834198e3a | refs/heads/master | 2020-03-29T02:34:35.355555 | 2018-09-19T12:31:05 | 2018-09-19T12:31:05 | 149,443,839 | 0 | 0 | null | 2018-09-19T12:31:06 | 2018-09-19T11:59:50 | R | UTF-8 | R | false | false | 82 | r | my_function.R | fun1 <- function(x) {
4* x - 3
}
fun1(5)
#here is my ironic and clever edit
|
57e438695f1a10d1de9a34fe610a36a5089eff02 | 24153b01d4de0a50249422517acf83d4ab18c6bf | /Part3/twitter_gather_clean_plot.R | aed216db55093026587c4db65e0200647e0f4a74 | [] | no_license | tannupriyasingh/DATA-COLLECTION-AND-EXPLORATORY-DATA-ANALYSIS | b64b14361f3586ba33db4bf9346a3855ac4a307a | 85096f6c4ce000b9127dba4558f99c46e3d37779 | refs/heads/master | 2020-06-09T08:33:51.389681 | 2019-06-24T01:01:30 | 2019-06-24T01:01:30 | 193,409,782 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,524 | r | twitter_gather_clean_plot.R | install.packages("rtweet")
install.packages("fiftystater")
library(rtweet)
library(fs)
library(ggmap)
library(fiftystater)
library(ggplot2)
######## Lab 1, Part 3 Credentials #######
# Using rtweet to find tweets
# The following keys are mine (rakshitm), you can use them
# or use yours
create_token(
app = "SOLR_CSE535",
consumer_key = "MiYJPLSSbO5PvZHXcoACrUqIA",
consumer_secret = "gVL0SrKvcDgdULoASJwKA9H0Mq6ZGAcBsxf4UVakp4EelTt3gP",
access_token = "1068558463083655168-SSR9ItGPZID9uGbhVEFgYYuDEn40zX",
access_secret = "8nxOu8PMZtim7rrn6hNJ8R05xl5bvCgyFsmDxpHUsVl62")
register_google(key = "AIzaSyBkxf5ZwATGGsRfjmDh73786lucI--p54o")
####### Lab 1, Part 3 Twitter data collection #######
# if you want to search upto a specific date,
# please mention it here.
until <- "2019-02-26"
# the keywords to query against.
q <- "flu OR influenza OR Tamiflu OR pneumonia"
# Scan to get the tweets and it will be
# saved to the get_tweets data.frame.
get_tweets <- search_tweets(q,
n = 18000,
geocode = lookup_coords("usa"),
include_rts = FALSE,
lang = "en",
search_type = "recent",
until=until)
# Function to separate the latitude and longitude
# from the tweet record.
rt2 <- lat_lng(get_tweets)
# Flatten the whole dataset.
rt2 <- apply(rt2,2,as.character)
# Write the file name you want to save to.
file_create(path("flu_geocoded_rt2.csv"))
# Flattens the array within array.
rt2 <- apply(rt_clean3,2,as.character)
# Save it to the file.
write.csv(clean_tweets, file = "flu_clean.csv")
####### Lab 1 Part 3 Twitter data cleaning and plotting #######
# Read the file that contains all the needed tweets
# that should be loaded.
# We can use data from previous part here, if we didn't save it.
all_tweets <- read.csv(file.choose())
# New array to store clean geotagged tweets
# We initialize this to store all the clean tweets.
# It only contains the tweets with latitude, longitude and state.
clean_tweets <- data.frame(stringsAsFactors = FALSE)
# To check the all the tweets are unique.
# It should return true.
print(length(unique(all_tweets$status_id)) == nrow(all_tweets))
# First Step.
# Remove tweets that are not geo-tagged, by checking for "NA" values.
# This way we are skimming out data for the next part.
for(i in 1:nrow(all_tweets)) {
if (!is.na(all_tweets[i,]$lat) && !is.na(all_tweets[i,]$lng)) {
clean_tweets <- rbind(clean_tweets, all_tweets[i,]);
}
};
# Second Step.
# Reverse geocode to get the full address of the lat/lon
# then we go through the response, which is a list.
# We go from google and see inside which part of the response does the state sit.
# It generally sits in the list itemthat has type "administrative_area_level_1".
# Once we know where the state can potentially be,
# we access that list item and retrive the state from it.
clean_tweets$state<-NA
for(i in 1:nrow(clean_tweets)) {
print(i);
temp_loc <- revgeocode(as.numeric(c(clean_tweets[i,90],clean_tweets[i,89])), output = "all");
if (!is.na(temp_loc)) {
temp_loc <- c(temp_loc$results[[1]]$address_components);
for (j in temp_loc) {
if (j$types[1] == "administrative_area_level_1") {
clean_tweets[i,]$state = j$long_name;
}
}
}
}
# Third Step.
# A seperate data frame that will get the count of tweets/state
loc_count_all <- data.frame(state=state.name, stringsAsFactors = FALSE);
loc_count_all$count<-NA
for (i in 1:nrow(loc_count_all)) {
loc_count_all[i,]$count <- length(which(clean_tweets$state == loc_count_all[i,]$state));
}
# Exact number of 50 State Tweets
print(sum(loc_count_all$count))
# Plotting the heatmap.
ggplot(loc_count_all, aes(map_id = tolower(loc_count_all$state))) +
coord_map() +
geom_map(map = fifty_states, aes(fill = count)) +
expand_limits(x = fifty_states$long, y= fifty_states$lat) +
ggtitle("Count of Tweets Per State") +
theme(plot.title = element_text(hjust = 0.5, face = 'bold')) +
labs(fill = "Number of Tweets") +
theme(axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
panel.background=element_blank()) +
scale_fill_gradientn(guide = "legend",
colours = rainbow(5),
expand = c(0, 0),
limits = c(0, max(loc_count_all$count)))
|
7dbad356ced270c59462031da5732e64f26a4efc | 3179c65e65ae94605f82ba425173f9334a822577 | /doc/article/nriter-x-finnn-smooth.R | 783ea2e3095de5f167e27cb74a791a3fae1a039d | [] | no_license | rmfoard/netaut | 07a001d53b8b0fd4e2c76f1de0cdcb05201c4cbd | 9edf4ed464d2e795ddd317e35d90e93832dd0704 | refs/heads/master | 2021-06-20T19:30:14.723403 | 2019-08-06T20:39:21 | 2019-08-06T20:39:21 | 131,421,915 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 703 | r | nriter-x-finnn-smooth.R | print("verify database 'primes':")
print(database)
p <- ggplot(data=filter(sd, machinetype=="C", outcome!="UND")) +
geom_smooth(mapping=
aes(y=nriterations, x=finnrnodes, linetype=outcome),
color="blue"
) +
facet_wrap(~ factor(initnrnodes)) +
theme(
legend.title=element_text(size=18),
legend.text=element_text(size=14),
axis.title=element_text(size=20),
legend.title.align=0.5,
axis.line = element_line(color="gray"),
panel.background=element_blank()
) +
labs(
x="Terminal graph size (nodes)",
y="Number of iterations"
)
print(p)
dev.copy(png, filename="../nriter-x-finnn-smooth.png")
dev.off()
|
91bc4fb65c85c07cc1ad6e5f60ee1a9d8653816f | f5afbadddca7d58c88decdd799386dae41354dd4 | /Leftovers/2017.10.05 TOSTtwoBayes Cohens d with Cauchy+HalfCauchy.R | cc94a74fb18289d3e4e2ebde7bb325ec32fc7927 | [] | no_license | Lakens/BF_TOST | 8415d386fcc0a4feedbb42be07ed82a850440a45 | 7eee03c7732a2dbc7ee8c3212d761d29bf087431 | refs/heads/master | 2021-01-20T05:20:53.470483 | 2018-06-19T16:09:09 | 2018-06-19T16:09:09 | 101,436,397 | 3 | 3 | null | 2017-11-22T15:49:31 | 2017-08-25T19:36:58 | R | UTF-8 | R | false | false | 11,038 | r | 2017.10.05 TOSTtwoBayes Cohens d with Cauchy+HalfCauchy.R | #' TOST function for an independent t-test (Cohen's d)
#' @param m1 mean of group 1
#' @param m2 mean of group 2
#' @param sd1 standard deviation of group 1
#' @param sd2 standard deviation of group 2
#' @param n1 sample size in group 1
#' @param n2 sample size in group 2
#' @param low_eqbound_d lower equivalence bounds (e.g., -0.5) expressed in standardized mean difference (Cohen's d)
#' @param high_eqbound_d upper equivalence bounds (e.g., 0.5) expressed in standardized mean difference (Cohen's d)
#' @param alpha alpha level (default = 0.05)
#' @param var.equal logical variable indicating whether equal variances assumption is assumed to be TRUE or FALSE. Defaults to FALSE.
#' @return Returns TOST t-value 1, TOST p-value 1, TOST t-value 2, TOST p-value 2, degrees of freedom, low equivalence bound, high equivalence bound, low equivalence bound in Cohen's d, high equivalence bound in Cohen's d, Lower limit confidence interval TOST, Upper limit confidence interval TOST
#' @importFrom stats pnorm pt qnorm qt
#' @importFrom graphics abline plot points segments title
#' @examples
#' ## Eskine (2013) showed that participants who had been exposed to organic
#' ## food were substantially harsher in their moral judgments relative to
#' ## those exposed to control (d = 0.81, 95% CI: [0.19, 1.45]). A
#' ## replication by Moery & Calin-Jageman (2016, Study 2) did not observe
#' ## a significant effect (Control: n = 95, M = 5.25, SD = 0.95, Organic
#' ## Food: n = 89, M = 5.22, SD = 0.83). Following Simonsohn's (2015)
#' ## recommendation the equivalence bound was set to the effect size the
#' ## original study had 33% power to detect (with n = 21 in each condition,
#' ## this means the equivalence bound is d = 0.48, which equals a
#' ## difference of 0.384 on a 7-point scale given the sample sizes and a
#' ## pooled standard deviation of 0.894). Using a TOST equivalence test
#' ## with default alpha = 0.05, not assuming equal variances, and equivalence
#' ## bounds of d = -0.43 and d = 0.43 is significant, t(182) = -2.69,
#' ## p = 0.004. We can reject effects larger than d = 0.43.
#'
#' TOSTtwo(m1=5.25,m2=5.22,sd1=0.95,sd2=0.83,n1=95,n2=89,low_eqbound_d=-0.43,high_eqbound_d=0.43)
#' @section References:
#' Berger, R. L., & Hsu, J. C. (1996). Bioequivalence Trials, Intersection-Union Tests and Equivalence Confidence Sets. Statistical Science, 11(4), 283-302.
#'
#' Gruman, J. A., Cribbie, R. A., & Arpin-Cribbie, C. A. (2007). The effects of heteroscedasticity on tests of equivalence. Journal of Modern Applied Statistical Methods, 6(1), 133-140, formula for Welch's t-test on page 135
#' @export
#'
TOSTtwo<-function(m1,m2,sd1,sd2,n1,n2,low_eqbound_d, high_eqbound_d, alpha, var.equal, prior_dist, effect_prior, se_prior, df_prior){
if(missing(alpha)) {
alpha<-0.05
}
if(missing(var.equal)) {
var.equal<-FALSE
}
if(var.equal==TRUE) {
sdpooled<-sqrt((((n1 - 1)*(sd1^2)) + (n2 - 1)*(sd2^2))/((n1+n2)-2)) #calculate sd pooled
low_eqbound<-low_eqbound_d*sdpooled
high_eqbound<-high_eqbound_d*sdpooled
degree_f<-n1+n2-2
t1<-((m1-m2)-low_eqbound)/(sdpooled*sqrt(1/n1 + 1/n2)) #students t-test lower bound
p1<-pt(t1, degree_f, lower.tail=FALSE)
t2<-((m1-m2)-high_eqbound)/(sdpooled*sqrt(1/n1 + 1/n2)) #students t-test upper bound
p2<-pt(t2, degree_f, lower.tail=TRUE)
t<-(m1-m2)/(sdpooled*sqrt(1/n1 + 1/n2))
pttest<-2*pt(-abs(t), df=degree_f)
LL90<-(m1-m2)-qt(1-alpha, n1+n2-2)*(sdpooled*sqrt(1/n1 + 1/n2))
UL90<-(m1-m2)+qt(1-alpha, n1+n2-2)*(sdpooled*sqrt(1/n1 + 1/n2))
LL95<-(m1-m2)-qt(1-(alpha/2), n1+n2-2)*(sdpooled*sqrt(1/n1 + 1/n2))
UL95<-(m1-m2)+qt(1-(alpha/2), n1+n2-2)*(sdpooled*sqrt(1/n1 + 1/n2))
} else {
sdpooled<-sqrt((sd1^2 + sd2^2)/2) #calculate sd root mean squared for Welch's t-test
low_eqbound<-low_eqbound_d*sdpooled
high_eqbound<-high_eqbound_d*sdpooled
degree_f<-(sd1^2/n1+sd2^2/n2)^2/(((sd1^2/n1)^2/(n1-1))+((sd2^2/n2)^2/(n2-1))) #degrees of freedom for Welch's t-test
t1<-((m1-m2)-low_eqbound)/sqrt(sd1^2/n1 + sd2^2/n2) #welch's t-test upper bound
p1<-pt(t1, degree_f, lower.tail=FALSE) #p-value for Welch's TOST t-test
t2<-((m1-m2)-high_eqbound)/sqrt(sd1^2/n1 + sd2^2/n2) #welch's t-test lower bound
p2<-pt(t2, degree_f, lower.tail=TRUE) #p-value for Welch's TOST t-test
t<-(m1-m2)/sqrt(sd1^2/n1 + sd2^2/n2) #welch's t-test NHST
pttest<-2*pt(-abs(t), df=degree_f) #p-value for Welch's t-test
LL90<-(m1-m2)-qt(1-alpha, degree_f)*sqrt(sd1^2/n1 + sd2^2/n2) #Lower limit for CI Welch's t-test
UL90<-(m1-m2)+qt(1-alpha, degree_f)*sqrt(sd1^2/n1 + sd2^2/n2) #Upper limit for CI Welch's t-test
LL95<-(m1-m2)-qt(1-(alpha/2), degree_f)*sqrt(sd1^2/n1 + sd2^2/n2) #Lower limit for CI Welch's t-test
UL95<-(m1-m2)+qt(1-(alpha/2), degree_f)*sqrt(sd1^2/n1 + sd2^2/n2) #Upper limit for CI Welch's t-test
}
ptost<-max(p1,p2) #Get highest p-value for summary TOST result
ttost<-ifelse(abs(t1) < abs(t2), t1, t2) #Get lowest t-value for summary TOST result
dif<-(m1-m2)
testoutcome<-ifelse(pttest<alpha,"significant","non-significant")
TOSToutcome<-ifelse(ptost<alpha,"significant","non-significant")
plot(NA, ylim=c(0,1), xlim=c(min(LL90,low_eqbound)-max(UL90-LL90, high_eqbound-low_eqbound)/10, max(UL90,high_eqbound)+max(UL90-LL90, high_eqbound-low_eqbound)/10), bty="l", yaxt="n", ylab="",xlab="Mean Difference")
points(x=dif, y=0.5, pch=15, cex=2)
abline(v=high_eqbound, lty=2)
abline(v=low_eqbound, lty=2)
abline(v=0, lty=2, col="grey")
segments(LL90,0.5,UL90,0.5, lwd=3)
segments(LL95,0.5,UL95,0.5, lwd=1)
title(main=paste("Equivalence bounds ",round(low_eqbound,digits=3)," and ",round(high_eqbound,digits=3),"\nMean difference = ",round(dif,digits=3)," \n TOST: ", 100*(1-alpha*2),"% CI [",round(LL90,digits=3),";",round(UL90,digits=3),"] ", TOSToutcome," \n NHST: ", 100*(1-alpha),"% CI [",round(LL95,digits=3),";",round(UL95,digits=3),"] ", testoutcome,sep=""), cex.main=1)
if(var.equal == TRUE) {
message(cat("Using alpha = ",alpha," Student's t-test was ",testoutcome,", t(",degree_f,") = ",t,", p = ",pttest,sep=""))
cat("\n")
message(cat("Using alpha = ",alpha," the equivalence test based on Student's t-test was ",TOSToutcome,", t(",degree_f,") = ",ttost,", p = ",ptost,sep=""))
} else {
message(cat("Using alpha = ",alpha," Welch's t-test was ",testoutcome,", t(",degree_f,") = ",t,", p = ",pttest,sep=""))
cat("\n")
message(cat("Using alpha = ",alpha," the equivalence test based on Welch's t-test was ",TOSToutcome,", t(",degree_f,") = ",ttost,", p = ",ptost,sep=""))
}
TOSTresults<-data.frame(t1,p1,t2,p2,degree_f)
colnames(TOSTresults) <- c("t-value 1","p-value 1","t-value 2","p-value 2","df")
bound_d_results<-data.frame(low_eqbound_d,high_eqbound_d)
colnames(bound_d_results) <- c("low bound d","high bound d")
bound_results<-data.frame(low_eqbound,high_eqbound)
colnames(bound_results) <- c("low bound raw","high bound raw")
CIresults<-data.frame(LL90,UL90)
colnames(CIresults) <- c(paste("Lower Limit ",100*(1-alpha*2),"% CI raw",sep=""),paste("Upper Limit ",100*(1-alpha*2),"% CI raw",sep=""))
cat("TOST results:\n")
print(TOSTresults)
cat("\n")
cat("Equivalence bounds (Cohen's d):\n")
print(bound_d_results)
cat("\n")
cat("Equivalence bounds (raw scores):\n")
print(bound_results)
cat("\n")
cat("TOST confidence interval:\n")
print(CIresults)
#below added BF calc
bayes<-TRUE #expect to provide bayes
if(missing(effect_prior)) {
bayes<-FALSE #if no prior effect size is provided, BF not calculated
}
if(bayes==TRUE) {
if(prior_dist=="normal") {
if(missing(se_prior)) {
se_prior<-effect_prior/2 #if not specified otherwise, default SE is effect/2
}
}
if(prior_dist=="halfnormal") {
if(missing(se_prior)) {
se_prior<-effect_prior #if not specified otherwise, default SE is effect
effect_prior<-0 #halfnormal is centered on 0
} }
if(prior_dist=="cauchy") {
df_prior<-1
{
if(missing(se_prior))
{df_prior<-1
se_prior<-effect_prior/2} #if not specified otherwise, default SE is effect
}}
if(prior_dist=="halfcauchy") {
{df_prior<-1}
if(missing(se_prior)) {
df_prior<-1
se_prior<-effect_prior #if not specified otherwise, default SE is effect
effect_prior<-0 #halfcauchy is centered on 0
}}
if(missing(df_prior)) {
df_prior<-1000 #if not specified otherwise, default df = 100000 (practically normal)
}
theta <- effect_prior - 10 * se_prior
incr <- se_prior / 200
theta=seq(from = effect_prior - 10 * se_prior, by = incr, length = 4001)
dist_theta <- dt(x = (theta-effect_prior)/se_prior, df=df_prior)
if(prior_dist=="halfnormal"){
dist_theta[theta <= 0] = 0
}
if(prior_dist=="halfcauchy"){
dist_theta[theta <= 0] = 0
}
dist_theta_alt = dist_theta/sum(dist_theta)
likelihood <- dt((dif-theta)/(dif/t), df = degree_f) #use dif - can be set to d
likelihood_alt = likelihood/sum(likelihood)
height <- dist_theta * likelihood
area <- sum(height * incr)
normarea <- sum(dist_theta * incr)
height_alt = dist_theta_alt * likelihood_alt
height_alt = height_alt/sum(height_alt)
LikelihoodTheory <- area/normarea
LikelihoodNull <- dt(dif/(dif/t), df = degree_f)
BayesFactor <- round(LikelihoodTheory / LikelihoodNull, 2)
bayes_results <- data.frame(BayesFactor, LikelihoodTheory, LikelihoodNull)
colnames(bayes_results) <- c("Bayes Factor","Likelihood (alternative)","Likelihood (null)")
cat("Bayes Results:\n")
print(bayes_results)
cat("\n")
invisible(list(TOST_t1=t1,TOST_p1=p1,TOST_t2=t2,TOST_p2=p2, TOST_df=degree_f,alpha=alpha,low_eqbound=low_eqbound,high_eqbound=high_eqbound,low_eqbound=low_eqbound,high_eqbound=high_eqbound, LL_CI_TOST=LL90,UL_CI_TOST=UL90,bf=BayesFactor, ll_theory=LikelihoodTheory, ll_null=LikelihoodNull))
}}
TOSTtwo(m1=5.25,m2=5.22,sd1=0.95,sd2=0.83,n1=95,n2=89,low_eqbound_d=-0.43,high_eqbound_d=0.43, var.equal=TRUE, prior_dist = "halfnormal", effect_prior = 0.5) # B = 0.31
TOSTtwo(m1=5.25,m2=5.22,sd1=0.95,sd2=0.83,n1=95,n2=89,low_eqbound_d=-0.43,high_eqbound_d=0.43, var.equal=TRUE, prior_dist = "halfcauchy", effect_prior = 0.5) # B = 0.25
## Checking directionality - Moon and Roeder data
# means one way
TOSTtwo(m1 = 0.50,
m2 = 0.46,
sd1 = 0.18,
sd2 = 0.17,
n1 = 48,
n2 = 53,
low_eqbound = -0.0625,
high_eqbound = 0.0625,
alpha = .05,
prior_dist="halfnormal",
effect_prior=0,
se_prior=0.05
)
# B = 1.47
# means switched around
TOSTtwo(m1 = 0.46,
m2 = 0.50,
sd1 = 0.17,
sd2 = 0.18,
n1 = 53,
n2 = 48,
low_eqbound = -0.0625,
high_eqbound = 0.0625,
alpha = .05,
prior_dist="halfnormal",
effect_prior=0,
se_prior=0.05
)
# B = 0.31
|
5e76e26ed3033add8d560ae7e569ea77a6e70fde | 03534d9b9d87ede322b1709fc24294b27cfffe04 | /renderUI_tab_buttons/global.R | 09efff5f053c92084133550cf8a80560b3a31fdc | [] | no_license | jhhughes256/shinyapps | a447bd0a844155f04d20c17e21f08adebddd2857 | 4ccef77e411f0e47fd03710131f567f2c71aa6bb | refs/heads/master | 2021-05-23T04:47:58.503082 | 2020-06-03T19:58:14 | 2020-06-03T19:58:14 | 81,397,341 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 2,341 | r | global.R | # Shiny app example of buttons to navigate tabBox
# App based on blog post from "guillotantoine":
# https://antoineguillot.wordpress.com/2017/02/15/three-r-shiny-tricks-to-make-your-shiny-app-shines-13/
# Javascript giving mouseover functionality was removed
# This doesn't really have much to do with
# Load libraries
# This app uses shinydashboard::tabBox
library(shiny)
library(shinydashboard)
# Set up non-reactive code
# Non-reactive code is set up in global.r in this app as we are using
# shinydashboard, and will be calling the tabList object from within the ui
# and the server
# The buttons used in renderUI do not change (however the way they link to their
# respective tabs do) so we can put them in the non-reactive area as ui chunks.
# Here we use an icon() instead of a string to put a "font-awesome" icon on
# the button, `class = fa-2x` makes it twice as big
prevButton <- actionButton("prevTab",
icon("angle-double-left",
class = "fa-2x"
),
width = 70
)
nextButton <- actionButton("nextTab",
icon("angle-double-right",
class = "fa-2x"
),
width = 70
)
# Next we make a function that contains these simple UI functions, but takes
# the value x to determine the offset
prevFun <- function(x) {
column(1,
prevButton,
offset = x
) # column
} # prevFun
nextFun <- function(x) {
column(1,
nextButton,
offset = x
) # column
} # nextFun
# Set up list of Tabs that will be used
tabList <- c("Tab1", "Tab2", "Tab3", "Tab4")
# This could be set up to make easily modifiable number of tabs
# the following function is the idea, but is untested
# the ui argument would be given a list of ui elements you want in each of your tabs
#library(plyr)
#multiTabPanel <- function(x, ui = list(1:length(x))) {
# llply(1:length(x), function(i) {
# tabPanel(x[i], ui[i])
# })
#}
# Blog code for previous and next buttons: Note that the method of making a
# wider button used below is an side effect of setting col-sm-4
# 70 pixels is about equivalent...
# prevButton <- div(actionButton("prevTab",
# HTML(
# '<div class="col-sm-4"><i class="fa fa-angle-double-left fa-2x"></i></div>'
# ) # HTML
# )) # div
# nextButton <- div(actionButton("nextTab",
# HTML(
# '<div class="col-sm-4"><i class="fa fa-angle-double-right fa-2x"></i></div>'
# ) # HTML
# )) # div
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.