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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
485a4948a26a887a4f76bffea2e6ce85b6ef64b6 | c0143d9d3b09ec8c7659a90b8534e568ca45db0b | /R/clean.R | 7779cfa0f6e303c517a2d037b1555a64a7945caa | [] | no_license | araupontones/muva_mapa_grupos | 66866e324346e2ab49dc9c2bbcaafb121395705a | edeacbfa26a97eb0af4c4e35c51e8950a303d4be | refs/heads/main | 2023-02-22T13:52:43.806500 | 2021-01-26T10:28:25 | 2021-01-26T10:28:25 | 317,214,188 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 596 | r | clean.R |
source("set_up.R")
#read shapefile ---------------------------------------------------------------
shape = import(file.path(dir_data, "districts.rds")) %>%
sf::st_as_sf()
provinces = import(file.path(dir_data, "provinces.rds")) %>%
sf::st_as_sf()
#esport list of districts ----------------------------------------------------
shape %>%
as.data.frame() %>%
select(Province_ID, Province, District_ID, District) %>%
arrange(Province, District) %>%
export(file.path(dir_data, "lista_distritos.xlsx"))
list.files(dir_data)
#test polygons
ggplot(data = provinces) +
geom_sf()
|
9d2479eae249a79706fd24fa769164dd311e1dbc | 5dbc32d306cccc5aaccf9e42ee6edd1fe585f9ef | /Assignment 3 - Optimization/profiling.R | 681764d840efa7fe863c6f042f79a2457f1ab5ab | [] | no_license | Gumle/R_Code | 230d98f340d5819e342603dda4344b2fac4c9576 | 6740d300bb1d259dd8fc134d1f095a216ba54e00 | refs/heads/main | 2023-06-23T17:24:16.307341 | 2021-07-25T13:53:48 | 2021-07-25T13:53:48 | 389,350,489 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,740 | r | profiling.R | library(splines) # splineDesign (B-splines)
library(LaplacesDemon) # logit and invlogit
library(Rcpp) # c++
library(profvis) # profiling
library(numDeriv) # numerical methods for grad and hess
library(ggplot2)
library(ggpubr)
library(microbenchmark) # benchmarking
library(bench)
library(gridExtra)
library(dplyr) # data manipulation
library(Matrix) # sparse matrix
setwd("~/Documents/Statistics - KU/Computational Statistics/Assignments/Assignment 3 - Optimization")
source("Debugging_and_tracing.R")
source("Assignment-3-functions.R")
library(simts)
n = 10000
# creating knots for B-spline basis
knots <- function(inner_knots) {
sort(c(rep(range(inner_knots), 3), inner_knots))
}
# f(x|beta) = (phi1(x), phi2(x),...,phim(x)) * beta
f <- function(par, x ,inner_knots) {
if(length(par) != length(inner_knots) + 2) {
stop("none compaterble dimensions")
}
phi <- splineDesign(knots(inner_knots), x) # designmatrix
phi %*% par
}
xx <- seq(0, 1000, length.out = n)
inner_knotsxx <- seq(range(xx)[1], range(xx)[2], length.out = 3)
par0 <- rnorm(5)
pvaerdier <- function(x)
{
f <- f(par0, x, inner_knotsxx) #0.1 + 1.2*(x-0.5)^2 + 0.9*x^3 + 0.3*x^4 + 0.2*x^5
exp(f)/(1 + exp(f))
}
yy <- rbinom(n, 1, pvaerdier(xx))
xx <- sample(xx)
profvis(Newton(par0, H, grad_H, hessian_H, maxiter = 500, d = 0.1, c = 0.1, gamma0 = 1, epsilon = 1e-5, stop = 'func', cb = NULL, xx, yy, lambda, inner_knotsxx))
profvis(GD(par0, H, grad_H, hessian_H, maxiter = 10000, d = 0.1, c = 0.1, gamma0 = 1, epsilon = 1e-5, stop = 'func', cb = NULL, xx, yy, lambda, inner_knotsxx))
profvis(CG(par0, H, grad_H, hessian_H, maxiter = 10000, d = 0.1, c = 0.1, gamma0 = 1, epsilon = 1e-5, stop = 'func', cb = NULL, xx, yy, lambda, inner_knotsxx))
|
ea28a37716556eb774b688cc725b32d22ff5ba7a | f08c51ed7b1fbef5cf6a8ceb612b5e37d4ba2caf | /tests/testthat/test_plot_karl.R | 4365db95f87e19249f23b4f87550edab8a070130 | [
"MIT"
] | permissive | UBC-MDS/Karl | be19f3af4738d2365969bc7257a5ee9f5233fcc2 | 0e098aff300c616cffa59069e56afb830b9fa93c | refs/heads/master | 2021-05-02T07:25:11.879781 | 2018-03-17T22:41:19 | 2018-03-17T22:41:19 | 120,827,883 | 0 | 4 | MIT | 2018-03-17T22:41:20 | 2018-02-08T22:52:05 | HTML | UTF-8 | R | false | false | 1,385 | r | test_plot_karl.R | # Test plot_karl function
# March 2018
## Packages
require(testthat)
require(matlib)
require(ggplot2)
require(gridExtra)
# Generate small data to test our function
set.seed(4)
X <- data.frame('X1' = rnorm(10))
y <- X$X1 + rnorm(10)
# True value of the coefficients
beta <- cov(X$X1, y)/var(X$X1)
alpha <- mean(y) - beta*mean(X$X1)
fit <- alpha + beta*X$X1
res <- y - fit
# Fit a linear regression on the data
model <- LinearRegression(X, y)
# Plot Linear Model Diagnostics
plots <- plot_karl(model)
test_that("plot_karl(): returns various plots using the linear model object", {
# expected inputs:
expect_equal(is.null(model$residuals), FALSE) # Expect not null input
expect_match(typeof(model), 'list') # Expect type list
expect_equal(names(model), c('weights', 'fitted', 'residuals')) # Expect names of inputs
expect_equal(length(model$fitted), length(model$residuals)) # Length of residuals and fitted values to match
expect_true(length(model$fitted)>1) # Expect length of fitted values greater than 1
expect_true(length(model$residuals)>1) # Expect length of residuals values greater than 1
# expected outputs:
expect_match(typeof(plots), "list") # Checks to see if the plotting type is correct
expect_equal(length(plots), 2) # Checks to see if the number of outputs is correct.
expect_false(plots$respect) # Respective to eachother the outputs.
})
|
67738f4079df1d1f4284188937b6524664df344b | 9cd83b84a4caf9f977901a1f99e7060fdd12d369 | /server.R | 0e265e88733836cc4d1b5e72449409ddfddd1fff | [] | no_license | vijaygurram/Shiney-Application | bf5c8f5c3513e912c60c1eb74cdb8fb81a60910c | 37f8b73bb28d0d8e9aeb9e0203afff8937b80f03 | refs/heads/master | 2021-09-02T08:07:10.414000 | 2017-12-31T19:51:40 | 2017-12-31T19:51:40 | 115,882,517 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,060 | r | server.R | #
# This is the server logic of a Shiny web application. You can run the
# application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(caret)
library(lattice)
shinyServer(function(input, output) {
data(ChickWeight)
trainedModel <- lm(weight~Time, data=ChickWeight)
predictWt <- reactive({
myEntry <- data.frame(Time = input$days, Diet = input$diet)
prediction <- predict(trainedModel, newdata = myEntry)
return(prediction)
})
output$ChkWtPlot <- renderPlot({
plot(ChickWeight$weight, ChickWeight$Time, xlab = "No. of Days", ylab = "Chick Weight", pch = 16, xlim = c(1, 21), ylim = c(10, 400))
abline(trainedModel, col = "blue", lwd = 2)
points(input$days, predictWt(), col = "red", pch = 16, cex = 2)
})
output$ChickWt <- renderText({
predictWt()
})
})
|
d9454ca4aab17ee3b002619bb5a21944ca4ab285 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/heemod/examples/plot.run_model.Rd.R | 59b8baa84b16a792c345f59262de883b2404510f | [] | 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 | 721 | r | plot.run_model.Rd.R | library(heemod)
### Name: plot.run_model
### Title: Plot Results of a Markov Model
### Aliases: plot.run_model
### ** Examples
## These examples require \code{res_mod} from the hip replacement model discussed in
## `vignette("non-homogeneous", package = "heemod")`.
## Not run:
##D plot(res_mod)
##D
##D plot(res_mod, model = "all")
##D plot(res_mod, model = "all", panels = "by_state")
##D
##D plot(res_mod, model = "all", include_states = c("RevisionTHR", "SuccessR"))
##D plot(res_mod, model = "all", panels = "by_state", include_states = c("RevisionTHR", "SuccessR"))
##D
##D plot(res_mod, model = 2, panel = "by_state", include_states = c("RevisionTHR", "SuccessR"))
##D
## End(Not run)
|
0c4fe6df6442b3ff386b6a4dbd4ef8ad3fe6c35a | bbd73e22684497a51ec61013277dcce89d417485 | /src/4paleolibrary.R | d1afeb8e83b3f0935f8939d71d6b14a423c82048 | [] | no_license | tlaepple/paleolibrary | a432c6405388474ca3295fdc2aadd65f9f6edbac | daed039f08854dcbb99b8194fd99ce7fec662842 | refs/heads/master | 2021-01-23T08:34:51.242448 | 2011-10-31T18:27:44 | 2011-10-31T18:27:44 | 2,659,270 | 1 | 1 | null | null | null | null | UTF-8 | R | false | false | 11,944 | r | 4paleolibrary.R | read_data<-function(FILENAME="C:/data/NCEP/DJFslp.nc",varname=NULL,name="",lonname=NULL,latname=NULL,missVal=c(-1e+20,1e+20)){
temp.nc = open.ncdf(FILENAME)
# read varname from temp.nc
if(is.null(varname)){
if(temp.nc$nvars>1){
varnames<-c()
for (i in 1:length(temp.nc$var)){
varnames<-c(varnames,temp.nc$var[[i]]$name)
}
print("following varnames are given:")
for (i in 1:length(varnames)){print(varnames[i])}
stop("you have to specify varname")
}
varname<-temp.nc$var[[1]]$name
}
# read name for lon and lat variabels from temp.nc
if(is.null(lonname)){
lonnames<-c("lon","longitude") # list of known lonnames
lonname<-find.var(temp.nc,lonnames)[1]
}
if(is.null(latname)){
latnames<-c("lat","latitude") # list of known latnames
latname<-find.var(temp.nc,latnames)[1]
}
#Read out the data
temp.time <- get.var.ncdf(temp.nc,"time")
temp.data <-get.var.ncdf(temp.nc,varname)
temp.lat <-get.var.ncdf(temp.nc,latname)
temp.lon <-get.var.ncdf(temp.nc,lonname)
#convert from missVal given values to NA
temp.data[temp.data<=missVal[1]]<-NA
temp.data[temp.data>=missVal[2]]<-NA
##convert dates for yearly and monthly data
# get informations about "time"-variable
timevar<-as.numeric(find.var(temp.nc,"time")[2:3])
unit.time<-temp.nc$var[[timevar[1]]]$dim[[timevar[2]]]$units
diff.time<-max(diff(temp.nc$var[[timevar[1]]]$dim[[timevar[2]]]$vals))
#diff.time<-temp.nc$var[[timevar[1]]]$dim[[timevar[2]]]$vals[[2]]-temp.nc$var[[timevar[1]]]$dim[[timevar[2]]]$vals[[1]]
if(unit.time=="day as %Y%m%d.%f"){
if(diff.time==100){
year <- floor(temp.time/10000)
temp.date <- year + (floor((temp.time-(year*10000))/100)-1)/12
}else{
if(diff.time==10000){
temp.date<-temp.time%/%10000
}else{
if(min(diff(temp.nc$var[[timevar[1]]]$dim[[timevar[2]]]$vals))==1){
d.year<-floor(temp.time/10000)
reftime<-julday.own(floor(temp.time[1]/10000)*10000+101)
d.day<-julday.own(temp.time)-reftime
len<-length(temp.date)
d.day[d.day>(len-1)]<-d.day[d.day>(len-1)]-len
temp.date<-d.year+d.day/365
}else{stop("time steps are not daily, monthly or yearly")}
}}
}else{
if(unit.time=="hours since 1-1-1 00:00:0.0"|unit.time=="hours since 1-01-01 00:00"){
if (diff.time==24){
temp.date<-(chron(temp.time/24,origin=c(month=1,day=1,year=01)))
d.year<-as.numeric(as.character(years(temp.date)))
d.day<-as.numeric(temp.date-chron(paste("1/1/",years(temp.date),sep="")))
temp.date<-d.year+d.day/365
}else{
temp.date <- as.vector(as.yearmon(chron(temp.time/24,origin=c(month=1,day=1,year=01))))
}
}else{
if(length(grep(glob2rx("days since ????-??-?? ??:??"),unit.time))){
start.year<-as.numeric(sub("-..-.....:..","",sub("days since ","",unit.time)))
start.mon<-as.numeric(sub("-.....:..","",sub("days since ....-","",unit.time)))
start.day<-as.numeric(sub("...:..","",sub("days since ....-..-","",unit.time)))
abs.start.day<-julday(start.mon,start.day,2001)-julday(1,1,2001)
d.day<-(temp.time+abs.start.day)/365
temp.date<-start.year+d.day
}else{stop(paste("time format",unit.time,"not supported by read_data"))}
}}
#Sort the latitudes
tmp<-sort(temp.lat,index.return=TRUE)
temp.lat<-temp.lat[tmp$ix]
temp.data<-temp.data[,tmp$ix,]
#sort the longitudes
temp.lon[temp.lon<0]<-temp.lon[temp.lon<0]+360
tmp<-sort(temp.lon,index.return=TRUE)
temp.lon<-temp.lon[tmp$ix]
temp.data<-temp.data[tmp$ix,,]
return(pField(temp.data,temp.date,lat=temp.lat,lon=temp.lon,name=name,history=FILENAME))
}
find.var<-function(data.nc,searched_vars)
{
for (i in 1:length(data.nc$var))
{
for (j in 1:length(data.nc$var[[i]]$dim))
{
if(is.element(data.nc$var[[i]]$dim[[j]]$name,searched_vars)){
varname<-data.nc$var[[i]]$dim[[j]]$name
return(c(varname,i,j))
}
}
}
}
julday.own<-function(x){
year<-floor(x/10000)
month<-floor((x-year*10000)/100)
day<-x-(year*10000+month*100)
return(julday(month,day,year))
}
cor.pTs<-function(pTs,field,use="complete.obs",min.obs=30,debug=F)
{
#bring both on the same time basis
start<-max(start(pTs)[1],start(field)[1])
end<-min(end(pTs)[1],end(field)[1])
if (debug) print(paste("Common time period: ",start,end))
pTs<-window(pTs,start,end)
field<-window(field,start,end)
if (class(field)[1]=="pField") #field correlation
{
n.Time<-length(time(field))
class(field)<-"matrix"
index<-((n.Time-colSums(is.na(field)))>min.obs)
dat<-field[,index]
result<-matrix(NA,1,ncol(field))
tresult<-cor(dat,pTs,use=use)
result[,index]<-tresult
class(field)<-"pField"
return(copyattr(result,field))
}
else return(cor(pTs,field,use=use))
}
cortest.pTs<-function(pTs,field,min.obs=30)
{
#bring both on the same time basis
start<-max(start(pTs)[1],start(field)[1])
end<-min(end(pTs)[1],end(field)[1])
print(paste("Common time period: ",start,end))
pTs<-window(pTs,start,end)
field<-window(field,start,end)
#Filter out data which contain not enough timesteps
n.Time<-length(time(field))
class(field)<-"matrix"
index<-((n.Time-colSums(is.na(field)))>min.obs)
dat<-field[,index]
result<-matrix(NA,2,ncol(field))
tresult<-apply(dat,2,mycor.test,c(pTs))
result[,index]<-tresult
class(field)<-"pField"
return(copyattr(result,field))
}
plotmap.pField<-function(plotdata,main=NULL,zlim=range(plotdata,finite=TRUE),levels=pretty(zlim,nlevels),nlevels=20,palette=NULL,FUN=NULL,shift=F,long=F,xlim=NULL,stype=0,sSub="",set.bg=NULL, ...)
{
temp<-attributes(plotdata)
if (is.null(sSub)) if (time(plotdata) != 9999) sSub<-paste("time:",format(time(plotdata)))
if (is.null(main)) main<-temp$name
gridcolor="lightgray"
if (stype == 1) {
shift=T
xlim=c(-180,180)
if (is.null(palette)) {
palette=colorRampPalette(c("violetred4","blue","steelblue", "lightgreen","white", "yellow","orange","red","brown"))
gridcolor="black"
}
}
if (stype == 2) {
if (is.null(palette)) {
palette=colorRampPalette(c("violetred4","blue","steelblue", "lightgreen","white", "yellow","orange","red","brown"))
gridcolor="black"
}
}
if (is.null(palette)) { palette=rbow;}
tmp<-plot.preparation(plotdata,shift,long)
if (is.null(xlim)) xlim = range(tmp$lon, finite = TRUE)
if (stype == 1)
{
filled.contour.own(tmp$lon,tmp$lat,tmp$data,zlim=zlim,nlevels=nlevels,levels=levels,xlim=xlim,color=palette,set.bg=set.bg,plot.title={
title(main=main,sub=sSub);
addland(col="black");
if (!is.null(FUN)) FUN(tmp$lon,tmp$lat,tmp$data)
},plot.axes=axes.stype(gridcolor,tmp$lat,tmp$lon))
} else
filled.contour.own(tmp$lon,tmp$lat,tmp$data,zlim=zlim,nlevels=nlevels,levels=levels,xlim=xlim,color=palette,set.bg=set.bg,plot.title={
title(main=main,sub=sSub);
addland(col="black"); grid()
if (!is.null(FUN)) FUN(tmp$lon,tmp$lat,tmp$data)
}, ...)
}
filled.contour.own<-function (x = seq(0, 1, len = nrow(z)), y = seq(0, 1, len = ncol(z)),
z, xlim = range(x, finite = TRUE), ylim = range(y, finite = TRUE),
zlim = range(z, finite = TRUE), levels = pretty(zlim, nlevels),
nlevels = 20, color.palette = cm.colors, col = color.palette(length(levels) -
1), plot.title, plot.axes, key.title, key.axes, asp = NA,
xaxs = "i", yaxs = "i", las = 1, axes = TRUE, frame.plot = axes, set.bg = NULL,
...)
{
if (missing(z)) {
if (!missing(x)) {
if (is.list(x)) {
z <- x$z
y <- x$y
x <- x$x
}
else {
z <- x
x <- seq(0, 1, len = nrow(z))
}
}
else stop("no 'z' matrix specified")
}
else if (is.list(x)) {
y <- x$y
x <- x$x
}
if (any(diff(x) <= 0) || any(diff(y) <= 0))
stop("increasing 'x' and 'y' values expected")
mar.orig <- (par.orig <- par(c("mar", "las", "mfrow")))$mar
on.exit(par(par.orig))
w <- (3 + mar.orig[2]) * par("csi") * 2.54
layout(matrix(c(2, 1), nc = 2), widths = c(1, lcm(w)))
par(las = las)
mar <- mar.orig
mar[4] <- mar[2]
mar[2] <- 1
par(mar = mar)
plot.new()
plot.window(xlim = c(0, 1), ylim = range(levels), xaxs = "i",
yaxs = "i")
# rect(0, levels[-length(levels)], 1, levels[-1], col = col)
delta<-(levels[length(levels)]-levels[1])/(length(levels)-1)
breaks<-delta*(0:(length(levels)-1))+levels[1]
rect(0, breaks[-length(levels)], 1, breaks[-1], col = col)
if (missing(key.axes)) {
if (axes)
{ #use modified axes
axis(4,labels=levels,at=breaks)
}
}
else key.axes
box()
if (!missing(key.title))
key.title
mar <- mar.orig
mar[4] <- 1
par(mar = mar)
plot.new()
plot.window(xlim, ylim, "", xaxs = xaxs, yaxs = yaxs, asp = asp)
if (!is.matrix(z) || nrow(z) <= 1 || ncol(z) <= 1)
stop("no proper 'z' matrix specified")
if (!is.double(z))
storage.mode(z) <- "double"
if(!is.null(set.bg)){
usr<-par('usr')
rect(usr[1],usr[3],usr[2],usr[4],col=set.bg)
}
.Internal(filledcontour(as.double(x), as.double(y), z, as.double(levels),
col = col))
if (missing(plot.axes)) {
if (axes) {
title(main = "", xlab = "", ylab = "")
Axis(x, side = 1)
Axis(y, side = 2)
}
}
else plot.axes
if (frame.plot)
box()
if (missing(plot.title))
title(...)
else plot.title
invisible()
}
plot.Polygon<-function(sigline)
{
col="grey60"
for (i in 1:length(sigline)) polygon(sigline[[i]]$x,sigline[[i]]$y,angle=-30,density=30,col=col, border = col)
}
plot.sig<-function(plotmap,sigmap,levels=0.95,...)
{
temp<-plot.preparation(sigmap)
diff.lon<-max(diff(temp$lon))
diff.lat<-max(diff(temp$lat))
len.lon<-length(temp$lon)
len.lat<-length(temp$lat)
new.lon<-c(temp$lon[1]-diff.lon,temp$lon,temp$lon[len.lon]+diff.lon)
new.lat<-c(temp$lat[1]-diff.lat,temp$lat,temp$lat[len.lat]+diff.lat)
empty.row<-matrix(ncol=len.lat)
empty.col<-matrix(nrow=len.lon+2)
new.data<-rbind(empty.row,temp$data)
new.data<-rbind(new.data,empty.row)
new.data<-cbind(empty.col,new.data)
new.data<-cbind(new.data,empty.col)
new.data[is.na(new.data)]<-1
siglines<-contourLines(new.lon,new.lat,1-new.data,levels=levels)
plot(plotmap,FUN=plot.Polygon(siglines),...)
}
filter.pField<-function(field,Filter,f.time,...)
{
result<-apply(field,2,"filter",Filter,...)
newTime<-window(time(field),start(field)[1]+f.time,end(field)[1]-f.time)
newField<-pField(NULL,newTime,getlat(field),getlon(field),paste(getname(field)),gethistory(field),date=FALSE)
for (i in 1:(length(time(field))-2*f.time))
{
newField[i,]<-result[i+f.time,]
}
return(newField)
#return(pField(result,time(data),getlat(data),getlon(data),paste(getname(data),"filtered"),gethistory(data)))
# obiges geht nicht, weil pField nicht mit NA-Werten klarkommt...
}
|
3ce49d4d44857435d27b9a5d4dcad62cce59d9f9 | bc743e2ba35582366ad8dce84feb6638578f5047 | /scripts/data import.R | a58075e00e49e9a2b9e15250204775992d31706f | [] | no_license | antoniojurlina/pdf_to_dataframe | 44423302e35ec446a99d353ff24356589d1f9969 | 4362eb64d8da8088bfc4ffcdec798a33c85359c8 | refs/heads/main | 2023-03-26T11:40:24.647210 | 2021-03-26T00:43:17 | 2021-03-26T00:43:17 | 351,613,023 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 12,534 | r | data import.R | library(stringr)
library(pdftools)
library(rebus)
library(ggplot2)
library(here)
paste0(here(), "/data") %>% setwd()
text <- pdf_text("PUBLICINFO-April-2017-pages-deleted.pdf")
text2 <- strsplit(text, "\n")
text2 <- lapply(text2, function(x) {x[-c(1:4,43:44)]})
text2[[1]] <- text2[[1]][-1]
text2[[118]] <- text2[[118]][-(12:13)]
text3 <- unlist(text2)
public_info <- data.frame(1,2,3,4,5,6,7)
colnames(public_info) <- c("CMP", "Name", "Department", "Title", "Salary", "JobSt", "Bargaining_Unit")
for (i in 1:length(text3)) {
CMP <- str_trim(str_extract(text3[[i]], pattern = START %R% ANY_CHAR %R% optional(one_or_more(WRD))
%R% optional(one_or_more(WRD)) %R% optional(one_or_more(WRD))))
temp.name <- str_extract(text3[[i]], pattern = CMP %R% one_or_more(SPC) %R% one_or_more(WRD) %R% optional(or(SPC, "-", "'")) %R%
zero_or_more(WRD) %R% "," %R% SPC %R% one_or_more(WRD) %R%
optional(SPC) %R% optional(char_class("A-Z")) %R% optional(DOT) %R% zero_or_more(WRD))
temp.name <- str_extract(temp.name, pattern = one_or_more(SPC) %R% one_or_more(WRD) %R% optional(or(SPC, "-", "'")) %R%
zero_or_more(WRD) %R% "," %R% SPC %R% one_or_more(WRD) %R%
optional(SPC) %R% optional(char_class("A-Z")) %R% optional(DOT) %R% zero_or_more(WRD))
Name <- str_trim(temp.name)
temp.vector <- str_extract(text3[[i]], pattern = SPC %R% char_class("A-Z") %R% char_class("A-Z") %R%
char_class("A-Z") %R% optional(char_class("A-Z")) %R% optional(char_class("A-Z"))
%R% optional(char_class("A-Z")) %R% optional(char_class("A-Z")) %R% optional(char_class("A-Z"))
%R% optional(char_class("A-Z")) %R% optional(char_class("A-Z")) %R% optional(char_class("A-Z")))
Department <- str_extract(temp.vector, pattern = char_class("A-Z") %R% char_class("A-Z") %R%
char_class("A-Z") %R% optional(char_class("A-Z")) %R% optional(char_class("A-Z"))
%R% optional(char_class("A-Z")) %R% optional(char_class("A-Z")) %R% optional(char_class("A-Z"))
%R% optional(char_class("A-Z")) %R% optional(char_class("A-Z")) %R% optional(char_class("A-Z")))
temp.vector <- str_extract(text3[[i]], pattern = Department %R% one_or_more(SPC) %R% one_or_more(WRD) %R% optional(SPC) %R%
optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)))
temp.title <- str_extract(temp.vector, pattern = SPC %R% optional(SPC) %R% zero_or_more(SPC) %R%
one_or_more(WRD) %R% optional(SPC) %R%
optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)))
Title <- str_trim(temp.title)
temp.salary <- str_extract(text3[[i]], pattern = DGT %R% optional(DGT) %R% optional(DGT) %R% optional(DGT)
%R% optional(DGT) %R% optional(DGT) %R% DOT %R% DGT %R% DGT)
Salary <- as.numeric(temp.salary)
temp.jobst <- str_extract(text3[[i]], pattern = temp.salary %R% one_or_more(SPC) %R% char_class("A-Z") %R% char_class("A-Z") %R% SPC)
JobSt <- str_trim(str_extract(temp.jobst, pattern = SPC %R% char_class("A-Z") %R% char_class("A-Z") %R% SPC))
temp.bunit <- str_extract(text3[[i]], pattern = JobSt %R% one_or_more(SPC) %R% one_or_more(WRD) %R% optional(or(SPC, "-"))
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC))
temp.bunit <- str_extract(temp.bunit, one_or_more(SPC) %R% one_or_more(WRD) %R% optional(or(SPC, "-"))
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC))
Bargaining_Unit <- str_trim(temp.bunit)
public_info[i,1] <- CMP
public_info[i,2] <- Name
public_info[i,3] <- Department
public_info[i,4] <- Title
public_info[i,5] <- Salary
public_info[i,6] <- JobSt
public_info[i,7] <- Bargaining_Unit
}
public_info[1258, 2] <- "De La Cruz, Gabriel R."
public_info[1259, 2] <- "De Urioste-Stone, Sandra M."
public_info[1388, 2] <- "Esparza-St Louis, Deborah"
public_info[2013, 2] <- "Mahoney-O'Neil, Maryellen"
public_info[2308, 2] <- "Pereira Da Cunha, Mauricio"
public_info[2632, 2] <- "St. Louis, Geoffrey A."
public_info[2633, 2] <- "St. Peter, Pamela A."
public_info[3142, 2] <- "De La Garza, Mario A."
public_info[3600, 2] <- "O'Neil Jr, Richard J."
public_info[3681, 2] <- "Raymond Jr., Robert J."
public_info[4407, 2] <- "St. Michel, Peter"
public_info[4408, 2] <- "St. Peter, John A."
public_info[88, 7] <- "COLT"
public_info[15, 3] <- "ABFSP"
public_info[15, 4] <- "Associate Professor - AY"
public_info[1062, 3] <- "OW"
public_info[1062, 4] <- "Administrative Support Supvsr"
public_info[2737, 3] <- "OFM"
public_info[2737, 4] <- "Mech Specialist Mechanical CL1"
public_info[1857, 3] <- "OSBE"
public_info[1857, 4] <- "Research Associate"
public_info[1858, 4] <- "4-H Science Youth Dev Prof"
public_info[1970, 3] <- "OW"
public_info[1970, 4] <- "Postdoctoral Research Assoc"
public_info[1986, 3] <- "OLY"
public_info[1986, 4] <- "Manager of Circulation"
public_info[2183, 3] <- "OHOUS"
public_info[2183, 4] <- "Facilities Maint Worker CL2"
public_info[2536, 3] <- "OFM"
public_info[2536, 4] <- "Electrical Specialist CL2"
public_info[2772, 3] <- "OHOUS"
public_info[2772, 4] <- "Facilities Maint Worker CL1"
public_info[3027, 3] <- "PMUS"
public_info[3027, 4] <- "Assistant Professor of Music"
public_info[3525, 3] <- "PENG"
public_info[3525, 4] <- "Professor of English"
public_info[3696, 3] <- "PCUST"
public_info[3696, 4] <- "Facilities Maint Worker CL1"
public_info[3730, 3] <- "PLYA"
public_info[3730, 4] <- "Coordinator of Access Services"
public_info[4176, 3] <- "SITCSUMF"
public_info[4176, 4] <- "Technical Lead"
public_info[4197, 3] <- "SITINF"
public_info[4197, 4] <- "Adv Comp Cloud Sys Admin"
public_info[4317, 2] <- "Moszczenski III, Stanley"
public_info[4317, 3] <- "SITCSUMA"
public_info[4317, 4] <- "Mgr of Svc Mgmt & Comm"
for (i in 1:length(text3)) {
temp <- str_extract(public_info$Bargaining_Unit[i], pattern = START %R% one_or_more(WRD) %R% optional(or(SPC, "-"))
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD)) %R% optional(SPC)
%R% optional(one_or_more(WRD)) %R% optional(SPC) %R% optional(one_or_more(WRD))
%R% optional(one_or_more(WRD)))
public_info[i, 7] <- str_trim(temp)
}
replace <- which(str_detect(public_info$Bargaining_Unit, "University"))
for (i in 1:length(replace)) {
public_info[replace[i], 7] <- "University Supervisors"
}
replace <- which(str_detect(public_info$Bargaining_Unit, "Part-Time"))
for (i in 1:length(replace)) {
public_info[replace[i], 7] <- "Part-Time Faculty"
}
replace <- which(str_detect(public_info$Bargaining_Unit, "Service and Maintenance"))
for (i in 1:length(replace)) {
public_info[replace[i], 7] <- "Service and Maintenance"
}
rm(text2, text, text3, Title, temp.vector, temp.title, temp.salary, temp.name, temp.jobst,
temp.bunit, temp, Salary, replace, Name, JobSt, i, Department, CMP, Bargaining_Unit)
save(public_info, file = "public_info.RData")
|
8bd8fde3e7c1f59ce9518cd02e5f434e24c7a570 | 0b551347a29f4e01e9273615ce0c5242f9bdb63a | /pkg/man/change_static_data-methods.Rd | 59395b9637b42e3b8c29291140885e3b329630d8 | [] | no_license | timemod/dynmdl | 8088fecc6c2b84d50ecb7d7b762bddb2b1fcf629 | 8dc49923e2dcc60b15af2ae1611cb3a86f87b887 | refs/heads/master | 2023-04-07T21:30:53.271703 | 2023-03-03T13:02:30 | 2023-03-03T13:02:30 | 148,925,096 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 2,624 | rd | change_static_data-methods.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/DynMdl_doc.R
\name{change_static_data-methods}
\alias{change_static_data-methods}
\alias{change_static_data}
\alias{change_static_endos}
\alias{change_static_exos}
\title{\code{\link{DynMdl}} methods: changes static values of the endogenous or exogenous
model data by applying a function.}
\description{
These methods of R6 class \code{\link{DynMdl}} changes the static values
of the endogenous and/or exogenous model data by applying a function.
}
\section{Usage}{
\preformatted{
mdl$change_static_endos(fun, names, pattern, ...)
mdl$change_static_exos(fun names, pattern, ...)
mdl$change_static_data(fun, names, pattern, ...)
}
\code{mdl} is a \code{\link{DynMdl}} object
}
\section{Arguments}{
\describe{
\item{\code{fun}}{a function applied each model variable specified with
argument \code{names} or \code{pattern}. See Details.}
\item{\code{names}}{a character vector with variable names}
\item{\code{pattern}}{a regular expression for selecting the names
of variables whose values must be changed}
\item{\code{...}}{arguments passed to \code{fun}}
}
If neither \code{names} nor \code{pattern} have been specified,
then the function is applied to all endogenous or exogenous variables.
}
\section{Details}{
The function specified with argument \code{fun} should be a function
with at least one argument, for example \code{fun = function(x) {x + 0.1}}.
The first argument (named \code{x} in the example) will be the model
variable. The function is evaluated for each model variable separately.
The function result must be a vector of length one.
}
\section{Methods}{
\describe{
\item{\code{change_static_endos}}{Changes the static values of endogenous model variables,
including fit instruments and Lagrange multipliers used in the fit method
(if present).}
\item{\code{change_static_exos}}{Changes the static values of exogenous model variables}
\item{\code{change_static_data}}{Changes the static values of endogenous and/or exogenous model variables,
including fit instruments and Lagrange multipliers used in the fit method
(if present).}
}
}
\examples{
mdl <- islm_mdl()
# increase y the static values of y and yd with 10\% for the full data period
mdl$change_static_endos(pattern = "^y.?$", fun = function(x) {x * 1.1})
print(mdl$get_static_endos())
# increase ms with 10
mdl$change_static_exos(names = "ms", fun = function(x, dx) {x + dx},
dx = 10)
print(mdl$get_static_exos())
}
\seealso{
\code{\link{set_static_data}},
\code{\link{set_static_values-methods}} and \code{\link{change_data-methods}}
}
|
c8033da8a39b88ba54c028bd491350bebaeb836a | 07a39081d79b5d49621e930c2926bec84f183c57 | /man/sequences.Rd | cbb8f6012bb44957808efc415d03c26c51447052 | [] | no_license | cran/rbiom | c5f6651d21e823bc5e39871d0b48d7e15f54e819 | 1c5e63055e46beb062889e266b6f0d1d99b1602a | refs/heads/master | 2023-08-28T00:49:57.085746 | 2021-11-05T04:50:02 | 2021-11-05T04:50:02 | 267,133,395 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,427 | rd | sequences.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/accessors.r
\name{sequences}
\alias{sequences}
\title{DNA sequence associated with each taxonomic identifier.}
\usage{
sequences(biom)
}
\arguments{
\item{biom}{A \code{BIOM} object, as returned from \link{read.biom}.}
}
\value{
A named character vector of sequences in \code{biom}. If this data
is not present, then returns \code{NULL}.
}
\description{
DNA sequence associated with each taxonomic identifier.
}
\examples{
library(rbiom)
infile <- system.file("extdata", "hmp50.bz2", package = "rbiom")
biom <- read.biom(infile)
sequences(biom)[1:4]
# Write to a compressed fasta file in the temporary directory:
seqs <- sequences(biom)
conn <- bzfile(file.path(tempdir(), "Sequences.fa.bz2"), "w")
cat(sprintf(">\%s\n\%s", names(seqs), seqs), file=conn, sep="\n")
close(conn)
# You can also use the write.fasta function for this task:
write.fasta(biom, file.path(tempdir(), "Sequences.fa.gz"))
}
\seealso{
Other accessor functions:
\code{\link{counts}()},
\code{\link{info}()},
\code{\link{metadata}()},
\code{\link{nsamples}()},
\code{\link{ntaxa}()},
\code{\link{phylogeny}()},
\code{\link{sample.names}()},
\code{\link{taxa.names}()},
\code{\link{taxa.ranks}()},
\code{\link{taxonomy}()}
}
\concept{accessor functions}
|
53ec5c1a82e48171ff98a6949d9c98cedccf6e9f | 78a8b1cfeda6b23dba4085aa6caf963ae14a7204 | /src/parseCentipedeTop5K.Pwm.v2.gmb.R | 0a0491803c730dddb35b417b6b3515956b2d9e44 | [] | no_license | piquelab/which_gen_vars | 389b95b7f8accdc461b7406202a4b5b3d405c42a | e7b236b283fad2cf15fcac7194a79390f48a8d16 | refs/heads/master | 2020-12-08T19:57:46.849921 | 2016-08-27T17:47:18 | 2016-08-27T17:47:18 | 66,727,747 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 6,399 | r | parseCentipedeTop5K.Pwm.v2.gmb.R |
baseFolder='initial/combo/'
library(centipede)
library(MASS)
cargs<-commandArgs(trail=TRUE);
if(length(cargs)>=1)
pwmName<-cargs[1];
if(length(cargs)>=2)
seedFolder<-cargs[2]; # pwms/seed/
if(length(cargs)>=3)
outFolder<-cargs[3];
system(paste("mkdir -p",outFolder));
aux <- read.table("factorNames.txt",sep="\t",as.is=T)
TfNames <- aux$V2
names(TfNames) <- aux$V1
aux <- read.table("dnase/numReads.txt",sep="\t",as.is=T,quote="")
Nreads <- aux$V2
names(Nreads) <- sub(".x8b.bz2.Qsub.e","",aux$V1)
ii <- pwmName
aux <- paste(baseFolder,"/",ii,'.beta.txt.gz',sep="")
aux <- (read.table(aux,as.is=T,sep="\t"))
sNames <- aux$V1
beta <- aux[,2:5]
rownames(beta) <- sNames
jj <- which.min(beta$V2)
tmax <- sNames[jj]
tmax
Tcut <- (qlogis(0.01)-beta[jj,1])/beta[jj,2]
## Load Sequences
seqFile <- paste(seedFolder,'/pwmScan.seq/',pwmName,'.seq.gz',sep="")
seqs <- scan(gzfile(seqFile),what=character(0), sep="")
seqs <- strsplit(seqs,character(0))
seqs <- t(sapply(seqs,cbind))
Sseqs<-dim(seqs)[2]
## Load model max
myFileName <- paste('initial/',tmax,'/',pwmName,'.Model.Rd',sep="")
load(myFileName)
LogRatio <- c.fit$NegBinLogRatio+c.fit$MultiNomLogRatio
PostPr <- plogis(LogRatio);
PostPr[PostPr<0.90] <- 0.0;
pwmmat2 <- ComputePWM(seqs,PostPr)
pwmmat2 <- apply(pwmmat2+1E-6,2,function(col){col/sum(col)})
bkgModel <- table(seqs[PostPr>0.90,])+1E-6
bkgModel <- bkgModel/sum(bkgModel)
ic <- apply(pwmmat2,2,function(col){sum(col*log2(col/bkgModel))})
pwm.ic.range <- range(which(ic>0.1))
pwm.ic.min <- min(pwm.ic.range)
pwm.ic.max <- max(pwm.ic.range)
new.pwm <- rbind(bkgModel,t(pwmmat2[,pwm.ic.min:pwm.ic.max]),bkgModel)
row.names(new.pwm) <- 1:nrow(new.pwm)
## Recalculate PWMscore with new PWM.
matseq <- cbind(seqs=="A",seqs=="C",seqs=="G",seqs=="T")+0.0;
W2 <- ncol(matseq)
pwmvec2 <- as.numeric(t(pwmmat2))
pwmvec2 <- log2(pwmvec2+1E-6)+2
PwmScore2 <- matseq %*% pwmvec2
bkgModel.vec <- log2(as.numeric(sapply(1:4,function(ii){rep(bkgModel[ii],W2/4)})))+2
PwmScore2b <- matseq %*% (pwmvec2-bkgModel.vec)
rho.0 <- cor.test(anno$PwmScore,LogRatio,method="spearman")
str(rho.0)
rho.1 <- cor.test(PwmScore2,LogRatio,method="spearman")
str(rho.1)
rho.1b <- cor.test(PwmScore2b,LogRatio,method="spearman")
str(rho.1b)
cat("#rho:",pwmName,tmax,rho.0$estimate,rho.1$estimate,rho.1b$estimate,
rho.0$p.value,rho.1$p.value,rho.1b$p.value,"\n",sep="\t")
## Write new PWM model, and logistic
## New logistic seq method
fLogit <- function(BetaLogit,Y,Ez){
-sum(Ez*(Y %*% BetaLogit) - log(1+exp(Y %*% BetaLogit)))
}
gLogit <- function(BetaLogit,Y,Ez){
myPi <- plogis(Y %*% BetaLogit)
-t(Ez-myPi) %*% Y
}
simpleLogit <-
function(X,Ez){
BetaFit <- optim(c(0,0),fLogit,gLogit,Y=as.matrix(data.frame(IntCept=1,X=X)),Ez=Ez,method="BFGS",control=list(maxit=500),hessian=TRUE);
logitSE <- sqrt(diag(ginv(as.matrix(BetaFit$hessian))))
Zlogit <- BetaFit$par/logitSE
c(BetaFit$par,Zlogit)
}
newLogit <- function(X,Ez){
BetaFit0 <- optim(0,fLogit,gLogit,Y=matrix(1,length(Ez),1),Ez=Ez,method="BFGS",control=list(maxit=500),hessian=TRUE);
BetaFit <- optim(c(0,1),fLogit,gLogit,Y=as.matrix(data.frame(IntCept=1,X=X)),Ez=Ez,method="L-BFGS-B",lower=c(-100,0.999),upper=c(0,1.001),control=list(maxit=500));
D <- 2*(BetaFit$value-BetaFit0$value)
c(BetaFit$par,D) ## Not nested model
}
###############################
beta.new2b <- newLogit(PwmScore2b,plogis(LogRatio))
beta.new2 <- newLogit(PwmScore2,plogis(LogRatio))
beta.new0 <- newLogit(anno$PwmScore,plogis(LogRatio))
cat("#Dbeta:",pwmName,tmax,beta.new0[1],beta.new2[1],beta.new2b[1],
beta.new0[3],beta.new2[3],beta.new2b[3],"\n",sep="\t")
tpwm <- function(p,beta){
qlogis(p)-beta[1]/beta[2]
}
p <- c(0.01,0.05,0.1,0.25,0.5,0.75,0.9,0.95,0.99)
Tcut2 <- sapply(p,function(p){tpwm(p,beta.new2)})
Tcut2b <- sapply(p,function(p){tpwm(p,beta.new2b)})
cat("#p.cut",pwmName,tmax,p,"\n",sep="\t")
cat("#p.Tcut2",pwmName,tmax,round(Tcut2,digits=2),"\n",sep="\t")
cat("#p.Tcut2b",pwmName,tmax,round(Tcut2b,digits=2),"\n",sep="\t")
## Output the updated PWM motif model
resFile <- paste(outFolder,pwmName,'.pwm',sep="");
con <- file(resFile,"w");
cat("#",pwmName,"\t",TfNames[pwmName],"\n",sep="",file=con)
cat("#p.cut",pwmName,tmax,p,"\n",sep="\t",file=con)
cat("#p.Tcut2",pwmName,tmax,round(Tcut2,digits=2),"\n",sep="\t",file=con)
cat("#p.Tcut2b",pwmName,tmax,round(Tcut2b,digits=2),"\n",sep="\t",file=con)
write.table(round(new.pwm,digits=8),quote=F,sep="\t",row.names=F,file=con)
close(con)
cat("#COMPLETED.1: ",pwmName,"\n");
#####################
## PLOT NEW LOGO ##
#####################
resFile <- paste(outFolder,"/",pwmName,".logo.png",sep="")
png(resFile);
pwm.v0 <- read.table(paste(seedFolder,"/pwmFiles/",pwmName,".pwm",sep=""),skip=1,as.is=T,sep="\t")
par(mfrow=c(2,1))
pwmLogo(t(new.pwm))
title(main=paste(pwmName," New --",TfNames[pwmName]))
ic2 <- apply(new.pwm,1,function(col){sum(col*log2(col/bkgModel))})
#lines(1:length(ic2),ic2,lwd=2)
pwmLogo(t(pwm.v0))
title(main=paste(pwmName," Old --",TfNames[pwmName]))
dev.off()
########################
## PLOT TOP FOOTPRINT ##
########################
resFile <- paste(outFolder,"/",pwmName,".lambda.png",sep="")
png(resFile);
Mlen <- anno$end[1]-anno$start[1]
par(mfrow=c(1,1))
plotProfile(c.fit$LambdaParList$DNase1,Mlen=Mlen,legTitle=paste(tmax,"\n",pwmName,"--",TfNames[pwmName]))
dev.off()
###########################
## PWM model prediction ##
###########################
resFile <- paste(outFolder,"/",pwmName,".logit.png",sep="")
png(resFile);
x <- seq(0,50,0.1)
plot(NA,xlim=range(x),ylim=c(0,1),xaxs="i",yaxs="i",axes=F,xlab="",ylab="")
ii <- which.min(beta$V2)
mycol <- c("lightblue","blue","red","darkgreen","orange","purple","magenta")
pal <- colorRampPalette(c("purple","blue","light green", "yellow", "orange", "red","darkred"))
o <- order(-beta$V2)
mycol <- pal(length(o))
sapply(1:length(o),function(jj){
ii <- o[jj]
b0 <- beta$V2[ii]; b1 <- beta$V3[ii];
y <- plogis(b0+b1*x);
lines(x,y,col=mycol[jj],lwd=3)
ii
})
b0 <- beta$V2[ii]; b1 <- beta$V3[ii];
y <- plogis(b0+b1*x);
lines(x,y,col='black',lwd=4,lty=3)
abline(v=10,lty=3)
axis(1)
axis(2,las=1)
abline(h=1,lty=3)
title(xlab="log2 PWM score")
title(ylab="Predicted proportion bound")
title(main=paste(pwmName,"--",TfNames[pwmName]))
b0 <- beta.new2b[1]; b1 <- beta.new2b[2];
y <- plogis(b0+b1*x);
lines(x,y,col='black',lwd=4,lty=2)
dev.off() |
15c86b1592dc359c5262255f3d5fe42e2cf0a156 | 0b4e456aed1637f0cb6e08ad49b7392867b9aec8 | /data-raw/makeAmpliciationLookup.R | 86d72e1f14838cc9b522c8ba1958366061e22ae0 | [] | no_license | sherrillmix/ampCountR | 88854a1a9e24f77a27b42a0ee1e9dd7a02bcd3a8 | 2c7eb3a8d19f6221a73459ad6fb81f93e0e18875 | refs/heads/master | 2020-12-25T22:08:22.048533 | 2016-10-21T11:07:32 | 2016-10-21T11:07:32 | 37,539,674 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 366 | r | makeAmpliciationLookup.R | ##File name: makeAmpliciationLookup.R
##Creation date: Aug 31, 2015
##Last modified: Thu Oct 01, 2015 08:00AM
##Created by: scott
##Summary: Generate the lookup table in /data
amplificationLookup<-ampCountR::generateAmplificationTable(300,300)
save(amplificationLookup,file='data/amplificationLookup.RData')
tools::resaveRdaFiles('data/amplificationLookup.RData')
|
bf7d1d50a9063d4e2e69a0ec92457124623587fa | 4647f7b395489d3a5e69d9ee1a1d7de0fb98fdd6 | /220404/Spearman.R | a586980a3a9f4e1b47af6477727f7fa4b53dc2a0 | [] | no_license | IvanWoo22/DayDayUp | 83e60ab63035d6583a4d6af3b4f3118fedd26287 | 1398157f59ef6efde045c0127c4ab6498cc67f8e | refs/heads/master | 2023-08-16T22:27:29.004708 | 2023-08-16T01:12:42 | 2023-08-16T01:12:42 | 152,426,297 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,574 | r | Spearman.R | #!/usr/bin/env Rscript
library(ggplot2)
library(ggsci)
library(gridExtra)
library(foreach)
library(doParallel)
library(readr)
setwd("~/wyf/cancer_DNAm_distance")
Args <- commandArgs(T)
data_path <- Args[1]
output_path <- Args[2]
do_spearman <- function(Site, Exp) {
test_out <- cor.test(
rep((1:7), sum(Exp)),
do.call(c, lapply(as.numeric(colnames(Exp[, Exp == 1])), function(x)
as.numeric(Site[[x]][rownames(Exp), ]))),
conf.level = 0.95,
method = "spearman",
exact = FALSE
)
TP <- test_out$p.value
SIG = 0
if (!is.na(TP)) {
if (TP < 0.05) {
SIG = 1
}
}
TR <- as.numeric(test_out$estimate)
SP <- array(dim = 10)
SR <- array(dim = 10)
SSIG <- NULL
SUM_SIG = 0
for (i in as.numeric(colnames(Exp[, Exp == 1]))) {
test_out <- cor.test(
c(1:7),
as.numeric(Site[[i]][rownames(Exp), ]),
conf.level = 0.95,
method = "spearman",
exact = FALSE
)
SP[i] <- test_out$p.value
SR[i] <- as.numeric(test_out$estimate)
if (!is.na(test_out$p.value)) {
if (test_out$p.value < 0.1) {
SUM_SIG = SUM_SIG + 1
SSIG <- c(SSIG, 0.88)
} else{
SSIG <- c(SSIG, 0.28)
}
} else {
SSIG <- c(SSIG, 0.28)
}
}
if (SUM_SIG > 2 | SIG > 0) {
draw_plot(Site, Exp, SSIG, TP, TR)
}
return(as.data.frame(cbind(
rownames(Exp), sum(Exp), SUM_SIG, t(SP), t(SR), TP, TR
)))
}
draw_plot <- function(Site, Exp, Sig, TP, TR) {
figfile <-
paste("png/Site", rownames(Exp), "_spearman.png", sep = "")
p <- ggplot() +
geom_point(aes(x = rep((1:7), sum(Exp)),
y = do.call(
c, lapply(as.numeric(colnames(Exp[, Exp == 1])), function(x)
as.numeric(Site[[x]][rownames(Exp),]))
))) +
geom_line(aes(
x = rep((1:7), sum(Exp)),
y = do.call(c, lapply(as.numeric(colnames(Exp[, Exp == 1])), function(x)
as.numeric(Site[[x]][rownames(Exp),]))),
size = as.factor(rep(sprintf(
"%02d", as.numeric(colnames(Exp[, Exp == 1]))
), each = 7)),
color = as.factor(rep(sprintf(
"%02d", as.numeric(colnames(Exp[, Exp == 1]))
), each = 7))
)) +
scale_color_jco(name = "Patient") +
scale_x_continuous(
breaks = c(1:7),
limits = c(0.8, 7.2),
expand = c(0, 0),
labels = c("T", "TE", "P5", "P10", "P15", "P20", "PN")
) +
scale_size_manual(values = Sig,
guide = 'none') +
xlab(label = "Location") +
ylab(label = "Beta value") +
ggtitle(label = paste("P-value=", TP, "\nrho=", TR, sep = "")) +
theme(
legend.background = element_blank(),
legend.spacing = unit(0.1, units = "mm"),
legend.key.size = unit(3.2, 0.2, units = "mm"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.background = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "#000000"),
axis.ticks = element_line(colour = "#000000"),
axis.ticks.length.y = unit(2, units = "mm"),
axis.ticks.length.x = unit(1, units = "mm"),
axis.title = element_text(
colour = "#000000",
face = "bold",
size = 14
),
axis.text = element_text(
colour = "#000000",
face = "bold",
size = 12
)
)
png(figfile,
width = 1200,
height = 800,
res = 200)
print(p)
dev.off()
}
write("==> Start read file!", stderr())
point_list <-
read.csv(data_path,
sep = "\t",
header = F,
row.names = 1)
colnames(point_list) <- (1:10)
point_list <-
point_list[order(as.numeric(row.names(point_list))),]
P <- list()
for (i in (1:10)) {
input_file <-
paste("sitefilter15_P", sprintf("%02d", i), ".tsv", sep = "")
dft <- read.csv(input_file,
sep = "\t",
header = F,
row.names = 1)
colnames(dft) <- paste("P", (1:7), sep = "")
P[[i]] <- data.frame(dft)
}
write("==> Start parallel!", stderr())
cl <- makeCluster(20)
registerDoParallel(cl)
temp <- foreach(
ID = rownames(point_list),
.packages = c("dplyr", "ggplot2", "readr", "gridExtra", "ggsci"),
.inorder = F
) %dopar% {
Site <- list()
for (samp in 1:10) {
Site[[samp]] <- round(P[[samp]][ID,], 0)
}
output <-
do_spearman(Site, point_list[ID,])
if (!is.null(output)) {
write_delim(
output,
output_path,
append = T,
col_names = F,
delim = "\t"
)
}
}
quit() |
7d4608d4303ea38cc82a0a428b45c85a647c1610 | 6d750f5a0cc1a77a8638756041b4902c48ed5343 | /server.R | eb1a06ffa8b23286a84e9e6672052dcf3e3efd66 | [] | no_license | sbalandtsc/DevelopingDataProducts | 47b7f6e43f8480449b4d6554ee1c4209b5713166 | 7eb5d5579daf5beab0e036e55a208da4ba0029bc | refs/heads/main | 2023-02-03T21:53:17.897073 | 2020-12-15T22:18:48 | 2020-12-15T22:18:48 | 321,802,390 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,076 | r | server.R | #
# This is the server logic of a Shiny web application. You can run the
# application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
model1 <- lm(mpg~wt, data=mtcars)
model1pred <- reactive({
wtInput <- input$sliderWT
predict(model1, newdata = data.frame(wt=wtInput))
})
output$plot1 <- renderPlot({
wtInput <- input$sliderWT
plot(mtcars$wt, mtcars$mpg, xlab = "Weight (in 1000 lbs)",
ylab = "Miles per gallon (MPG)", bty="n", pch=16,
xlim = c(1, 6), ylim = c(10, 35))
abline(model1, col="green", lwd=2)
legend(25, 250, "Model prediction", pch=16,col="red", bty="n", cex=1.2)
points(wtInput, model1pred(), col="green", pch=16, cex=2)
})
output$pred1 <- renderText({
round(model1pred(), digits=2)
})
})
|
7a0bbff3a28c9cf67399f9782f16a4bc72003d06 | 51a885d284859c96bfb46e1adb8b52005138cab9 | /teaching/teaching_files/CSP519_SP17/labs/Lab5/Lab5.R | 75886b655b7ad7744dfe821399bcc3e0a6e9eae9 | [] | no_license | wbushong/wbushong.github.io | 8ab3411993ec8844a55cb3d0f58eda4b209300c2 | 640539969c63b3f1121d7c4c4b80f1e86a7d7e6d | refs/heads/master | 2022-07-19T12:53:14.737578 | 2022-06-21T16:16:01 | 2022-06-21T16:16:01 | 56,018,765 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 5,473 | r | Lab5.R | #########################
## Lab 5
#########################
# rgl will let us plot in 3 dimensions
library(rgl)
library(ggplot2)
# Load data & inspect
d <- read.csv("InteractionData.csv")
head(d)
summary(d)
#### Categorical x Categorical Interactions ####
# Plotting
# relevel factors
d$Grade <- factor(d$Grade, levels = c("4th grade", "7th grade", "10th grade"))
p.gender.grade <- ggplot(d, aes(x = Grade, y = Self_control, color = Gender, group = Gender)) +
stat_summary(fun.data = "mean_cl_boot", geom = "pointrange") +
stat_summary(fun.y = "mean", geom = "line")
p.gender.grade
# Regressions
# change contrasts
contrasts(d$Gender) <- cbind(females = c(1, -1))
contrasts(d$Grade) <- cbind(grade_4 = c(1, 0, 0), grade_10 = c(0, 0, 1))
# Test interaction
m.gender.grade <- lm(Self_control ~ Gender * Grade, d)
summary(m.gender.grade)
m.gender.noint <- lm(Self_control ~ Gender + Grade, d)
anova(m.gender.grade, m.gender.noint)
# Test simple slope for males' self-control between 4th and 7th grade
# recode gender as dummy
d$Gender.dummy <- d$Gender
contrasts(d$Gender.dummy) <- cbind(females = c(1, 0))
m.gender.ss <- lm(Self_control ~ Gender.dummy * Grade, d)
summary(m.gender.ss)
#### Categorical x Continuous Interactions ####
# Plotting
p.neuro.gender <- ggplot(d, aes(x = Neurot, y = Self_control, color = Gender)) +
stat_summary(fun.y = "mean", geom = "point") +
geom_smooth(method = "lm") # fits an lm to each subset of the data
p.neuro.gender
# Regressions
# center continuous variable
d$Neurot.centered <- d$Neurot - mean(d$Neurot)
# Test interaction
m.neurot.gender <- lm(Self_control ~ Neurot.centered * Gender, d)
summary(m.neurot.gender)
# Simple slope for highly neurotic individuals
d$Neurot.centered.2sds <- d$Neurot - (mean(d$Neurot) + 2*sd(d$Neurot))
m.highneurot.gender <- lm(Self_control ~ Neurot.centered.2sds * Gender, d)
summary(m.highneurot.gender)
#### Continuous x Continuous Interactions ####
# Plotting -- there are many options here. See pdf of Lab 5 for more details!
# Plot of main effects of consci & neurot
p.neurot <- ggplot(d, aes(x = Neurot, y = Self_control)) +
geom_point()
p.neurot
p.consci <- ggplot(d, aes(x = Consci, y = Self_control)) +
geom_point()
p.consci
# Plot interaction using color
p.neurot.consci <- ggplot(d, aes(x = Neurot, y = Consci, color = Self_control)) +
geom_point(size = 5) +
scale_color_gradient(low = "blue", high = "red") +
ggtitle("Scatterplot of Neuroticism x Conscientiousness Interaction")
p.neurot.consci
# Plot interaction using median split
d$Consci.categorical <- ifelse(d$Consci > median(d$Consci), "high", "low")
p.neurot.consci2 <- ggplot(d, aes(x = Neurot, y = Self_control, color = Consci.categorical)) +
geom_point() +
ggtitle("Scatterplot of Neuroticism x Conscientiousness Interaction") +
geom_smooth(method = "lm")
p.neurot.consci2
# 3D plot
p.3d <- plot3d(d[, c("Consci", "Neurot", "Self_control")])
# Regressions
# center our other continuous variable
d$Consci.centered <- d$Consci - mean(d$Consci)
# Test interaction
m.consci.neurot <- lm(Self_control ~ Consci.centered * Neurot.centered, d)
summary(m.consci.neurot)
# Test simple slope of less conscientious than normal people
d$Consci.1sd <- d$Consci - (mean(d$Consci) - sd(d$Consci))
m.neurot.lowconsci <- lm(Self_control ~ Neurot.centered * Consci.1sd, d)
summary(m.neurot.lowconsci)
## Plotting regression predictions (see text for more details)
# Get mean of consci, and +/-1 SD
consci.mean <- mean(d$Consci.centered)
consci.1.below <- consci.mean - sd(d$Consci.centered)
consci.1.above <- consci.mean + sd(d$Consci.centered)
# Create fake data based on this
fake.data <- data.frame(Neurot.centered = rep(range(d$Neurot.centered), 3),
Consci.centered = c(rep(consci.mean, 2), rep(consci.1.below, 2), rep(consci.1.above, 2)))
# Predict values of self-control
fake.data$Self_control <- predict(m.consci.neurot, fake.data)
# Plot!
p.predictions <- ggplot(fake.data, aes(x = Neurot.centered, y = Self_control, color = Consci.centered, group = Consci.centered)) +
geom_point() +
geom_line()
p.predictions
## Plot regression planes in 3D! (talk to me for more details)
# Plot regression plane with NO interaction
m.no.interaction <- lm(Self_control ~ Neurot.centered + Consci.centered, d)
f1 <- function(X, Z) {
r <- coef(m.no.interaction)[1] +
coef(m.no.interaction)[2] * Z +
coef(m.no.interaction)[3] * X
}
plot3d(d[c("Consci.centered", "Neurot.centered", "Self_control")])
plot3d(f1,
xlim = range(d$Consci.centered),
ylim = range(d$Neurot.centered),
add = TRUE, col = "red", alpha = .5)
# Plot regression plane WITH interaction
m.interaction <- lm(Self_control ~ Neurot.centered * Consci.centered, d)
f2 <- function(X, Z) {
r = coef(m.interaction)[1] +
coef(m.interaction)[2] * Z +
coef(m.interaction)[3] * X +
coef(m.interaction)[4] * Z * X
}
plot3d(d[c("Consci.centered", "Neurot.centered", "Self_control")])
plot3d(f2,
xlim = range(d$Consci.centered),
ylim = range(d$Neurot.centered),
add = TRUE, col = "blue", alpha = .5)
# Plot both!
plot3d(d[c("Consci.centered", "Neurot.centered", "Self_control")])
plot3d(f1,
xlim = range(d$Consci.centered),
ylim = range(d$Neurot.centered),
add = TRUE, col = "red", alpha = .5)
plot3d(f2,
xlim = range(d$Consci.centered),
ylim = range(d$Neurot.centered),
add = TRUE, col = "blue", alpha = .5)
|
263afcee2f540baf63b827691736ce1f89e9d2f6 | 4592565db17d3d5a4bfa8fc820d7516beb4fa115 | /demo/seminr-cbsem-cfa-ecsi.R | 71f6ed24c669631e400d7534ea00dac25b7c4c4e | [] | no_license | sem-in-r/seminr | 1b370286c58f4e658a02fb5df21fabe585fcfb4a | ae2524aae5f4f0bda3eb87faf80378af5baccea1 | refs/heads/master | 2023-04-04T00:29:48.969724 | 2022-06-30T17:02:07 | 2022-06-30T17:02:07 | 70,557,585 | 49 | 16 | null | 2022-10-13T15:22:28 | 2016-10-11T04:58:23 | R | UTF-8 | R | false | false | 2,605 | r | seminr-cbsem-cfa-ecsi.R | # Demonstration of specifying and estimating covariance-based models
# - Confirmatory Factor Analysis (CFA) conducted to confirm measurement model
# - Full structural equation model (CBSEM) conducted to confirm structural model
library(seminr)
# Get data from file or elsewhere.
# For this demo, we will use the included mobi dataset.
mobi <- mobi
# Creating measurement mode
# - items can be a list of names: c("CUEX1", "CUEX2", "CUEX3")
# which can be constructed quickly as: multi_items("CUEX", 1:3)
# - interactions between two constructs should be defined as a measurement term
mobi_mm <- constructs(
reflective("Image", multi_items("IMAG", 1:5)),
reflective("Expectation", multi_items("CUEX", 1:3)),
reflective("Loyalty", multi_items("CUSL", 1:3)),
reflective("Value", multi_items("PERV", 1:2)),
reflective("Complaints", single_item("CUSCO"))
)
# Identify any inter-item association parameters to estimate by
# specifying free associations between their errors
mobi_am <- associations(
item_errors(c("PERQ1", "PERQ2"), "CUEX3"),
item_errors("IMAG1", "CUEX2")
)
# CONFIRMATORY FACTOR ANALYSIS
mobi_cfa <- estimate_cfa(mobi, mobi_mm, mobi_am)
summary(mobi_cfa)
# Plot the CFA model
plot(mobi_cfa)
# STRUCTURAL EQUATION MODEL
# First, let's append an interaction onto the measurement model
# - by default, a two-stage approach will be used to create a single item
# interaction from CFA construct scores (ten Berge extraction)
# - we will specify a product indicator interaction method instead
final_mm <- append(
mobi_mm,
interaction_term("Image", "Expectation", method = product_indicator)
)
# Specify the structural model
# - we can create multiple paths from a single `paths()` function
# - Six structural paths are created quickly in two lines!
mobi_sm <- relationships(
paths(from = c("Image", "Expectation"), to = c("Value", "Loyalty")),
paths(from = c("Complaints", "Image*Expectation"), to = "Loyalty")
)
# Estimate the SEM and get results
# - if the measurement model contains composites, use `all.reflective(final_mm)`
# to convert all constructs to reflective measurement
mobi_cbsem <- estimate_cbsem(mobi, final_mm, mobi_sm, mobi_am)
summary(mobi_cbsem)
# Plot the CBSEM Model
plot(mobi_cbsem)
# Examine other interesting results by inspecting the summary object
cbsem_summary <- summary(mobi_cbsem)
# - factor loadings
cbsem_summary$loadings
# - latent variable correlations
cbsem_summary$descriptives$correlations$constructs
# - Check the Variance Inflation Factor (VIF) of each regression
cbsem_summary$quality$antecedent_vifs
|
6609b7a5edc97c986fd33ce8304d3dd8d1c8fde9 | 9cc58a8eb35ba76bfac93e44722d859a10b1f064 | /threeHDP/main/alphaInitgc.R | f07be3edfc89370627ae5e21ea24b85d3e688bd3 | [] | no_license | gradjitta/WorkingCode | 8400a3a7c8cd7b1145d382d381cc5ff8c4b0b289 | 64e07620b5894889b0b6a15d12c311839895ca86 | refs/heads/master | 2020-06-05T12:15:29.651940 | 2014-12-31T20:51:19 | 2014-12-31T20:51:19 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 398 | r | alphaInitgc.R | alphaInitgc <- function(paths, L, lookup, phi, K0) {
emit <- paths$emit
Np <- length(paths$grids)
N0 <- dim(phi)[2] / 2
n1 <- which(paths$grids[[1]] == lookup)
alpha <- lapply(1:Np, function(i) NULL)
for (i in 1:Np) {
nc <- which(paths$grids[i] == lookup)
if (sum(nc) == 0) {
alpha[[i]] <- rep(0, 1)
} else {
alpha[[i]] <- rep(0, K0)
}
}
return(alpha)
}
|
96f9ad8fd4a4982154b97c18efca753d03933fae | 6129f3f9d25c5b3c09b378f46e1550f132be9490 | /man/sumTable.Rd | f3b4e67cb79acb1d7531e5dcae7a58123a5dcd95 | [] | no_license | andreasnovotny/metaphylo | 35c4bbba2f587c915b3ee801cc2b00cea021f58e | 0172b136f48b3e0c2a5534947e5d0521025af888 | refs/heads/master | 2022-04-04T08:51:03.389255 | 2020-02-20T14:34:25 | 2020-02-20T14:34:25 | 142,552,505 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,378 | rd | sumTable.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/code.R
\name{sumTable}
\alias{sumTable}
\title{Construct Summary table for barplots}
\usage{
sumTable(
data,
x = "Genus",
y = "Abundance",
variables = c("Family", "Class", "Order")
)
}
\arguments{
\item{data}{(Required) A phyloseq object or a data frame.}
\item{x}{(Optional, default="Genus") Character string referring to the main explainatory variable.}
\item{y}{(Optional, default="Abundance") Character string reffering to the dependent variable. For phyloseq objects, this is always "Abundance".}
\item{variables}{(optional, default=c("Family", "Class", "Order")) A vector of strings reffereng to any aditional explainatory variable for plotting/colouring/splitting/grouping ect.}
}
\value{
A formated data.frame. The aim of the data frame is to use for plotting in ggplot (or the wrapper metaphylo::barChart)
}
\description{
This function takes a phyloseq as unput (or possibly a tidy data-frame) and transforms it into a summary table.
}
\examples{
data(ps_18S)
ps_18S \%>\%
subset_samples(SORTED_genus=="Synchaeta") \%>\%
subset_samples(MONTH=="aug") \%>\%
subset_taxa(Class!="Rotifera") \%>\%
transform_sample_counts(function(x) (x/sum(x))*100) \%>\%
filter_taxa(function(x) sum(x>1)>=((length(x)*0.5)),TRUE) \%>\%
sumTable(x = "Species", variables = c("Class", "Order"))
}
|
9330c5f0dc09e325fcdfc7a9605ba8b4b557df16 | 384c3dbc571be91c6f743d1427dec00f13e0d8ae | /r/kernels/vladtasca-titanic-random-forest-80/script/titanic-random-forest-80.R | f3bb808efa0707d74964c4944c84c17abb2bbe45 | [] | no_license | helenaK/trustworthy-titanic | b9acdd8ca94f2fa3f7eb965596eed4a62821b21e | ade0e487820cf38974561da2403ebe0da9de8bc6 | refs/heads/master | 2022-12-09T20:56:30.700809 | 2020-09-10T14:22:24 | 2020-09-10T14:22:24 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,559 | r | titanic-random-forest-80.R | # Draft First Attempt -- Random Forest
#Loading many unnecessary libraries
#vis
library('ggplot2') # visualization
library('ggthemes') # visualization
library('ggridges') # visualization
library('ggforce') # visualization
library('ggExtra') # visualization
library('GGally') # visualisation
library('scales') # visualization
library('grid') # visualisation
library('gridExtra') # visualisation
library('corrplot') # visualisation
library('VIM') # missing values
# wrangle
library('dplyr') # data manipulation
library('tidyr') # data manipulation
library('readr') # data input
library('stringr') # string manipulation
library('forcats') # factor manipulation
library('modelr') # factor manipulation
# model
library('randomForest') # classification
library('xgboost') # classification
library('ROCR') # model validation
library('caret')
library('rpart.plot')
library('doSNOW')
#Load 'em babies up
train <- read_csv('../input/train.csv')
test <- read_csv('../input/test.csv')
#Combine 'em
test$Survived <- NA
combined <- rbind(train, test)
tr_idx <- seq(nrow(train)) #train indices, test indices are -tr_idx
#Fixing small error (16 y/o /w 13 y/o son)
combined$SibSp[combined$PassengerId==280] = 0
combined$Parch[combined$PassengerId==280] = 2
combined$SibSp[combined$PassengerId==1284] = 1
combined$Parch[combined$PassengerId==1284] = 1
# Who is missing?
colSums(is.na(combined))
#1xFare, 2xEmbarked, 263xAge
#####
#Replacing FARE
#####
trControl <- trainControl(method = 'repeatedcv',number = 10,repeats = 5)
fareMiss <- which(is.na(combined$Fare)) #missing fare row
model_fare <- train(Fare ~ Pclass + Sex + Embarked + SibSp + Parch, data = combined %>% filter(!is.na(Fare)),trControl = trControl,method = 'rpart',na.action = na.pass,tuneLength = 5)
combined$Fare[fareMiss] = predict(model_fare, combined[fareMiss,]) #predict missing fare
combined$Fare <- as.factor(combined$Fare) #add fare factor column
rpart.plot(model_fare$finalModel)
#####
###Replacing EMBARKED
#####
which(is.na(combined$Embarked))
combined[62, "Embarked"] <- 'C'
combined[830, "Embarked"] <- 'C'
# New Variable: Title
combined$Title <- gsub('(.*, )|(\\..*)', '', combined$Name)
table(combined$Sex, combined$Title)
# Reassign titles
officer <- c('Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev')
royalty <- c('Dona', 'Lady', 'the Countess','Sir', 'Jonkheer')
combined$Title[combined$Title == 'Mlle'] <- 'Miss'
combined$Title[combined$Title == 'Ms'] <- 'Miss'
combined$Title[combined$Title == 'Mme'] <- 'Mrs'
combined$Title[combined$Title %in% royalty] <- 'Royalty'
combined$Title[combined$Title %in% officer] <- 'Officer'
# New Variable: Family Size
combined$FamilySize <- combined$SibSp + combined$Parch + 1
ggplot(combined, aes(Pclass, fill=!is.na(Age))) + geom_bar(position="dodge") + labs(title="Passenger Has Age",fill="Has Age") # We decide at this point to dismiss Age information for Pclass 3. Having to complete a large percentage of missing values may add more noise to the prediction system for a goal of better than 80% accuracy.
ggplot(combined[tr_idx,] %>% filter(Pclass!=3), aes(Age)) + geom_density(alpha=0.5, aes(fill=factor(Survived))) + labs(title="Survival density per Age for Pclass 1 and 2")
child <- 14
combined$Minor <- ifelse(combined$Age<child&combined$Pclass!=3, 1, 0)
combined$Minor <- ifelse(is.na(combined$Minor), 0, combined$Minor)
# Factorise and ready to model
combined$Survived <- as.factor(combined$Survived)
combined$Pclass <- as.factor(combined$Pclass)
combined$Sex <- as.factor(combined$Sex)
combined$Title <- as.factor(combined$Title)
combined$Minor <- as.factor(combined$Minor)
combined$Embarked <- as.factor(combined$Embarked)
combined$Fare <- as.double(combined$Fare)
glimpse(combined)
# Back into train and test
train <- combined[tr_idx,]
test <- combined[-tr_idx,]
# Keep wanted columns
train <- train[, c('Survived', 'Pclass', 'Sex', 'Fare', 'Embarked','Title', 'FamilySize', 'Minor')]
test <- test[, c('Survived', 'Pclass', 'Sex', 'Fare', 'Embarked','Title', 'FamilySize', 'Minor', 'PassengerId')]
#Partition
p_idx <- createDataPartition(train$Survived, p = 0.7, list = F)
p_train <- train[p_idx, ]
p_test <- train[-p_idx, ]
# Model
#cl <- makeCluster(5, type = 'SOCK')
#registerDoSNOW(cl)
glimpse(p_train)
model_rf <- randomForest(Survived ~ ., data=train, importance=TRUE, proximity=TRUE, do.trace=TRUE)
#stopCluster(cl)
summary(model_rf)
test$Survived <- predict(model_rf, test)
submit <- data.frame(PassengerId = test$PassengerId, Survived = test$Survived)
write.csv(submit, 'submit.csv', row.names = F)
|
59940bc0fb0f79a8286e250948b2a4e628bb7031 | b23fe1e6bd8d1ae11b45f74010cdf714da2d77e7 | /plot4.R | ce1788872ee9443ec41687a0fdc74e2bddf4f6c5 | [] | no_license | premziom/ExData_Plotting1 | 606a2f8561e7326fe0706ed3bc68954fcf665acc | 4c6001957539a7b3693e126e9d16b894a0396bb6 | refs/heads/master | 2021-05-07T01:36:01.498747 | 2017-11-11T17:22:41 | 2017-11-11T17:22:41 | 110,364,140 | 0 | 0 | null | 2017-11-11T17:10:47 | 2017-11-11T17:10:46 | null | UTF-8 | R | false | false | 1,580 | r | plot4.R | #downloading zip file
url='https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip'
zipfile='project_w1_data.zip'
file='household_power_consumption.txt'
if (!file.exists(zipfile)){
url
download.file(url,zipfile)
}
#unzipping data file
if (!file.exists(file)) {
unzip(zipfile)
}
#reading data and subsetting
dataIn<-read.table(file,header=TRUE,sep=";",na.strings = "?")
dataIn<-subset(dataIn,dataIn$Date %in% c("1/2/2007","2/2/2007"))
#changing variables to date and time
dataIn$Time<-strptime(paste(as.character(dataIn$Date)," ",as.character(dataIn$Time),sep=""),format="%d/%m/%Y %H:%M:%S")
dataIn$Date<-as.Date(dataIn$Date[1],format="%d/%m/%Y")
#chart4
png('plot4.png',width=480,height=480)
par(mfrow=c(2,2))
plot(dataIn$Time,dataIn$Global_active_power,type="l",ylab="Global Active Power",xlab="")
plot(dataIn$Time,dataIn$Voltage,type="l",ylab="Voltage",xlab="datetime")
plot(dataIn$Time,dataIn$Sub_metering_1,type="l",ylab="Energy sub metering",xlab="")
par(new=T)
plot(dataIn$Time,dataIn$Sub_metering_2,type="l",ylab="Energy sub metering",xlab="", col="red",ylim=c(0,max(dataIn$Sub_metering_1)))
par(new=T)
plot(dataIn$Time,dataIn$Sub_metering_3,type="l",ylab="Energy sub metering",xlab="", col="blue",ylim=c(0,max(dataIn$Sub_metering_1)))
legend("topright",legend=names(dataIn[,7:9]),col=c("black","red","blue"),lwd=1,bty="n")
plot(dataIn$Time,dataIn$Global_reactive_power,type="l",ylab="Global_rective_power",xlab="datetime")
dev.off()
|
01cc205e0bc0332744264608a9aeb870ada00355 | a455c79481abe8622da165a54bce1366474a854a | /.Rprofile | 440f724940952aff14cf8867d56d61a7ebdd3fc5 | [
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | permissive | PERTS/gymnast | 9f6aa7284791320640c8356e425f5309ba62ea6c | 56b76235c9d5c121108b70374dfa0cc9e4b7d456 | refs/heads/master | 2023-06-30T17:30:26.579348 | 2023-06-14T20:14:58 | 2023-06-14T20:14:58 | 46,515,070 | 3 | 1 | NOASSERTION | 2023-08-25T15:51:16 | 2015-11-19T19:24:51 | HTML | UTF-8 | R | false | false | 845 | rprofile | .Rprofile | options(
repos = "http://cran.rstudio.com/", # needed to install any packages
install.packages.check.source = "no" # prefer binary packages
)
if (!"modules" %in% utils::installed.packages()) {
# Without the INSTALL_opts here, some environments using this .Rprofile file
# can get in a recursive loop. R starts a new process to compile/build
# packages (see [source code lines 603-604][1]), which may run this .Rprofile
# script again. Specifying --use-vanilla tells R to ignore this file.
#
# [1]: https://www.rdocumentation.org/packages/utils/versions/3.6.2/source
utils::install.packages("modules", INSTALL_opts="--use-vanilla")
}
if (!exists("import_module")) {
modules::use("R/bootstrap.R")$install_module_imports()
if (Sys.getenv('RSTUDIO') == "1") {
print("gymnast/.Rprofile installed `import_module`.")
}
}
|
671aaa84f31d7460e519695b64fb45e7c3ad590a | 630ffaea8d8b0d2b33d0b22cb079fa65210580ff | /Chapter6.R | 11055503776abac258102e220e2b00f448756e11 | [] | no_license | ayusharora99/AnalyzingBaseballDataWithR | 3865419fcf656223500a03d22aadd43f53c0e3ed | d4eefc56319eed0527cc80a38ac1f9839bc0dca3 | refs/heads/master | 2020-03-23T04:24:54.648990 | 2018-12-24T04:07:03 | 2018-12-24T04:07:03 | 141,082,009 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,367 | r | Chapter6.R | load("~/Desktop/Analyzing Baseball Data with R/baseball_R-master/data/balls_strikes_count.RData")
library(lattice)
sampleRows = sample(1:nrow(verlander),20)
verlander[sampleRows,]
histogram(~ speed, data = verlander)
# Speeds of Verlander's 5 Pitch Types
densityplot(~speed, data=verlander, plot.points=FALSE)
densityplot(~speed | pitch_type, data = verlander, layout = c(1,5), plot.points = FALSE)
densityplot(~speed, data = verlander, groups = pitch_type, plot.points = FALSE, auto.key = TRUE)
# FF's speed throughout the seasons
F4ver1 = subset(verlander, pitch_type == "FF")
F4ver1$gameDay = as.integer(format(F4ver1$gamedate,format="%j"))
dailySpeed = aggregate(speed~gameDay + season, data=F4ver1, FUN=mean)
xyplot(speed ~ gameDay | factor(season), data=dailySpeed,xlab = "day of the year", ylab = "pitch speed (mph)")
# Comparing FF & CH speeds throughout the seasons
speedFC = subset(verlander, pitch_type %in% c("FF","CH"))
avgspeedFC = aggregate(speed ~ pitch_type + season, data=speedFC, FUN=mean)
avgspeedFC = droplevels(avgspeedFC)
avgspeedFC
dotplot(factor(season) ~ speed, groups = pitch_type,data = avgspeedFC, pch = c("C", "F"), cex = 2)
# Comparing FF velocity vs Pitch Count
avgSpeed = aggregate(speed ~ pitches +season, data=F4ver1, FUN = mean)
xyplot(speed~pitches | factor(season), data = avgSpeed)
avgSpeedComb = mean(F4ver1$speed)
avgSpeedComb
panel = function(...){
panel.xyplot(...)
panel.abline(v=100,lty="dotted")
panel.abline(h=avgSpeedComb)
panel.text(25,100,"avg speed")
panel.arrows(25,99.5,0,avgSpeedComb,length = .1)
}
xyplot(speed~pitches | factor(season), data = avgSpeed,panel = function(...){
panel.xyplot(...)
panel.abline(v=100,lty="dotted")
panel.abline(h=avgSpeedComb)
panel.text(25,100,"avg speed")
panel.arrows(25,99.5,0,avgSpeedComb,length = .1)
})
# Verlander's Second No-Hitter (Tigers-Blue Jays on May 7, 2011)
NoHit = subset(verlander, gamedate == "2011-05-07")
xyplot(pz~px | batter_hand, data=NoHit, groups=pitch_type,auto.key=TRUE,aspect="iso",xlim=c(-2.2,2.2),ylim=c(0,5),xlab="Horizontal Location\n(ft. from middle of plate)",ylab="Vertical Location\n(ft. from ground)")
pitchnames = c("change-up", "curveball", "4S-fastball", "2S-fastball", "slider")
myKey = list(space = "right",border = TRUE,cex.title = .8,title = "pitch type",text = pitchnames,padding.text = 4)
topKzone = 3.5
botKzone = 1.6
inKzone = -.95
outKzone = 0.95
xyplot(pz ~ px | batter_hand, data=NoHit, groups=pitch_type,
auto.key = myKey,
aspect = "iso",
xlim = c(-2.2, 2.2),
ylim = c(0, 5),
xlab = "horizontal location\n(ft. from middle of plate)",
ylab = "vertical location\n(ft. from ground)",
main = "Justin Verlanders 2nd Career No-Hitter (v.s. Blue Jays on May 11,2011",
panel = function(...){
panel.xyplot(...)
panel.rect(inKzone, botKzone, outKzone, topKzone,
border = "black", lty = 3)
}
)
# 5 seasons of Miguel Cabrer'as Career Including the 2012 Triple Crown Season
sampleRows <- sample(1:nrow(cabrera), 20)
cabrera[sampleRows,]
install.packages("ggplot2")
library(ggplot2)
# Spray Chart of Cabrera's BIP
p0 = ggplot(data=cabrera,aes(x=hitx,y=hity))
p1 = p0 + geom_point(aes(color=hit_outcome))
p2 = p1 + coord_equal()
p2
p3 = p2 + facet_wrap(~ season)
p3
bases = data.frame(x=c(0, 90/sqrt(2), 0, -90/sqrt(2), 0),
y=c(0,90/sqrt(2), 2*90/sqrt(2), 90/sqrt(2),0))
p4 = p3 + geom_path(aes(x=x,y=y), data=bases)
p4 +
geom_segment(x = 0, xend = 300, y = 0, yend = 300) +
geom_segment(x = 0, xend = -300, y = 0, yend = 300)
p4
cabreraStretch = subset(cabrera,gamedate > "2012-08-31")
p0 <- ggplot(data = cabreraStretch, aes(hitx, hity))
p1 <- p0 + geom_point(aes(shape = hit_outcome, colour = pitch_type
, size = speed))
p2 <- p1 + coord_equal()
p3 <- p2 + geom_path(aes(x = x, y = y), data = bases)
p4 <- p3 + guides(col = guide_legend(ncol = 2))
p4 +
geom_segment(x = 0, xend = 300, y = 0, yend = 300) +
geom_segment(x = 0, xend = -300, y = 0, yend = 300)
kZone <- data.frame(
x = c(inKzone, inKzone, outKzone, outKzone, inKzone)
, y = c(botKzone, topKzone, topKzone, botKzone, botKzone))
ggplot(F4ver1, aes(px, pz)) +
geom_point() +
facet_wrap(~ batter_hand) +
coord_equal() +
geom_path(aes(x, y), data = kZone, lwd = 2, col = "white")
|
985d0a3515722a35fd5273ddf5ae99f3c6424dfc | ebd6f68d47e192da7f81c528312358cfe8052c8d | /swig/Examples/test-suite/r/r_copy_struct_runme.R | deadc61fed8f671d490e49e96fb8c16eb374cf60 | [
"LicenseRef-scancode-swig",
"GPL-3.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-only",
"Apache-2.0"
] | permissive | inishchith/DeepSpeech | 965ad34d69eb4d150ddf996d30d02a1b29c97d25 | dcb7c716bc794d7690d96ed40179ed1996968a41 | refs/heads/master | 2021-01-16T16:16:05.282278 | 2020-05-19T08:00:33 | 2020-05-19T08:00:33 | 243,180,319 | 1 | 0 | Apache-2.0 | 2020-02-26T05:54:51 | 2020-02-26T05:54:50 | null | UTF-8 | R | false | false | 924 | r | r_copy_struct_runme.R | clargs <- commandArgs(trailing=TRUE)
source(file.path(clargs[1], "unittest.R"))
dyn.load(paste("r_copy_struct", .Platform$dynlib.ext, sep=""))
source("r_copy_struct.R")
cacheMetaData(1)
a <- getA()
r = getARef()
unittest(A_d_get(r), 42)
unittest(r$d, 42)
unittest(r$i, 20)
# An error in trying to access a field that doesn't exist.
try(r$foo)
r$d <- pi
unittesttol(r$d, 3.141593, 0.0001)
r$i <- -100
r$ui
r$ui <- 10
# An error since i is unsigned and so must be positive.
try(r$ui <- -10)
a = A()
unittest(a$i,0)
unittest(a$d,0)
unittest(a$ui,0)
a$ui <- 100
unittest(a$ui,100)
a$d = 1
unittest(a$d,1)
d <- bar()
unittest(class(d), "_p_D")
unittest(d$x, 1)
unittest(d$u, 0)
la <- new("A");
la@ui <- as.integer(5)
# Removing the next line makes this fail in R 2.4
la@str <- ""
other = A()
foo <- copyToC(la, other)
aa = A()
aa$i = as.integer(201)
aa$d = pi
aa$str = "foo"
aa$ui = as.integer(0)
copyToR(aa)
|
e6775e3ecaedf2e77fab4e4f29e6ed3394062ac4 | f7fd8f3bf040c655a8b4fa6ba36f0f956c08763d | /Spatial-Data-Analysis/Project-2/Code/code.r | feac921dbcd8cc965bbdbcf9ce4ba0bb7b8ba344 | [] | no_license | CharuSreedharan/Spatial-Data-Analytics-Projects | 1f27bb2b3c75a31d1d37e379618d093f3a09ced4 | a3f2c6adfc6d4ea9a78a07e5943f2cb4b8c62240 | refs/heads/master | 2020-07-25T05:55:26.601928 | 2019-09-13T03:27:11 | 2019-09-13T03:27:11 | 208,187,966 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 8,606 | r | code.r |
require(rgdal)
# Read .shp file from below path
ogShape <- readOGR(dsn = "D:/UPitt/Studies/Sem 2/Spatial DA/Projects/Project 2/OilGasLocationPA/OilGasLocationPA", layer = "OilGasLocationPA")
# Convert SpatialPointsDataFrame object to DataFrame object
coordsdf<-data.frame(coordinates(ogShape))
(1)
require(spatstat)
# x-minimum coordinate
xleft <- apply(ogShape@coords,2,min)[1]
# y-minimum coordinate
ybottom <- apply(ogShape@coords,2,min)[2]
# x-maximum coordinate
xright <- apply(ogShape@coords,2,max)[1]
# y-maximum coordinate
ytop <- apply(ogShape@coords,2,max)[2]
# Convert SpatialPointsDataFrame object to DataFrame object
ogpp <- as.ppp(ogShape@coords, c(xleft-1,xright+1,ybottom-1,ytop+1))
# number of x-quadrats
qX <- 200
# number of y-quadrats
qY <- 100
# quadrat size along x-axis
xcellsize <- (xright-xleft)/qX
# quadrat size along y-axis
ycellsize <- (ytop-ybottom)/qY
# doing regular quadrat count
qC <- quadratcount(ogpp,qX,qY)
# total number of events
n <- nrow(ogShape)
require(DataCombine)
# calling random quadrat count function
randquadcount.data <- randomQuadratCount.ppp(ogpp, coordsdf, qX, qY)
# random quadrat count function. To generate random numbers along x and y-axis and create a quadrat. (x,y) generated is the left-top coordinate.
# We get the rest of the points using xcellsize and ycellsize
randomQuadratCount.ppp <- function(X, coordsdf, nx=5, ny=nx) {
# total number of quadrats
numofquadrats <- nx*ny
# window object of the study region
W <- as.owin(X)
# x-minimum coordinate of the study region
xmin <- W$xrange[1]
# x-maximum coordinate of the study region
xmax <- W$xrange[2]
# y-minimum coordinate of the study region
ymin <- W$yrange[1]
# y-maximum coordinate of the study region
ymax <- W$yrange[2]
# quadrat size in X
xcellsize <- (xmax-xmin)/nx
# quadrat size in Y
ycellsize <- (ymax-ymin)/ny
# changing ymin value to avoid quadrat going outside the study region
ymin <- ymin+ycellsize
# New data frame to store random quadrat count result(set of quadrats)
randquadcount.data <- data.frame(xmin = c(0), xmax = c(0), ymin = c(0),
ymax = c(0), Freq = c(0))
# looping over the number of quadrats to be generated
for (i in 1:numofquadrats){
# random number generator along x-axis
rx <- runif(1, min=xmin, max=xmax)
# random number generator along y-axis
ry <- runif(1, min=ymin, max=ymax)
# stores list of coordinates of quadrat. (rx,ry) corresponds to left top coordinate of quadrat. Generating rest of the co-ordinates using xcellsize & ycellsize
quadrat_list <- list(c(rx,ry),c(rx+xcellsize,ry),c(rx,ry-ycellsize),c(rx+xcellsize,ry-ycellsize))
# counter
quadcount <- 0
# getting only those events which lie between the generated quadrat
dfquad <- coordsdf[coordsdf$coords.x1>=rx & coordsdf$coords.x1<=(rx+xcellsize) &
coordsdf$coords.x2>=(ry-ycellsize) & coordsdf$coords.x2<=ry,]
# looping over the events lying within the quadrat
for(j in 1:nrow(dfquad)) {
# incrementing the counter varible
quadcount <- quadcount+1
}
# creating a new row for a dataframe with the quadrat details
New <- c(xmin = quadrat_list[[3]][1], xmax = quadrat_list[[4]][1], ymin = quadrat_list[[3]][2],
ymax = quadrat_list[[1]][2], Freq = c(quadcount))
# inserting this row into the resultant data frame
randquadcount.data <- InsertRow(randquadcount.data, NewRow = New, RowNum = i)
}
# removing the last NA row
randquadcount.data <- randquadcount.data[-c(nrow(randquadcount.data)), ]
# return the resultant data frame
return(randquadcount.data)
}
# plot all the events
plot(coordsdf, pch=20, col="green", main="OilGasLocationsPA",
xlab="x-coordinate", ylab="y-coordinate")
# call plotting function for regular quadrat method
regplotfn()
library(GISTools)
# plotting function for regular quadrat method
regplotfn <- function() {
lx<-xleft
ly<-ybottom
# looping over the number of quadrats along y-axis. number of lines to be drawn=number of quadrats+1
for(i in 1:qY+1){
# draws lines horizontally
lines(c(xleft,xright),c(ly,ly))
# increments y-value
ly<-ly+ycellsize
}
# looping over the number of quadrats along x-axis. number of lines to be drawn=number of quadrats+1
for(i in 1:qX+1){
# draws lines vertically
lines(c(lx,lx),c(ybottom,ytop))
# increments x-value
lx<-lx+xcellsize
}
# add Legend
legend(120000, 185000, legend=c("OilGasLocations", "Quadrats"),
col=c("green", "black"), pch=c(20, 0), cex=0.8,
title="Legend", text.font=4)
# add North Arrow
north.arrow(100000, 150000, len=10000, lab="N", col="red")
}
plot(coordsdf, pch=20, col="orange", main="OilGasLocationsPA",
xlab="x-coordinate", ylab="y-coordinate")
# call plotting function for regular quadrat method
randplotfn(randquadcount.data)
# plotting function for random quadrat method
randplotfn <- function(randdf) {
# loop over the number of rows of the resultant dataframe generated after random quadrat count function
for(index in 1:nrow(randdf)){
# create a new dataframe of a particular row
rowdf <- randdf[index,]
# draws line base edge of quadrat
lines(c(rowdf["xmin"],rowdf["xmax"]),c(rowdf["ymin"],rowdf["ymin"]))
# draws line left edge of quadrat
lines(c(rowdf["xmin"],rowdf["xmin"]),c(rowdf["ymin"],rowdf["ymax"]))
# draws line top edge of quadrat
lines(c(rowdf["xmin"],rowdf["xmax"]),c(rowdf["ymax"],rowdf["ymax"]))
# draws line right edge of quadrat
lines(c(rowdf["xmax"],rowdf["xmax"]),c(rowdf["ymax"],rowdf["ymin"]))
# add Legend
legend(120000, 185000, legend=c("OilGasLocations", "Quadrats"),
col=c("orange", "black"), pch=c(20, 0), cex=0.8,
title="Legend", text.font=4)
# add North arrow
north.arrow(100000, 150000, len=10000, lab="N", col="red", tcol="red")
}
}
(2)
# Regular Quadrant Sampling
# convert the resultant data frame after regular quadrat count method to data frame
dfexhsch <- as.data.frame(qC)
# sort 'Frequency of events in quadrat' column in ascending order
dfexhsch <- dfexhsch[order(dfexhsch$Freq),]
# mean=(total number of events)/(total number of quadrats)
Mean <- n/(qX*qY)
# call function to compute statistics table
df1.data <- computeStats(dfexhsch, Mean)
View(df1.data)
# Random Quadrat Sampling
# create a new data frame
df2.data <- data.frame(numeric(), numeric(),numeric(), numeric(), numeric())
# sort 'Frequency of events in quadrat' column in ascending order
randquadcount.data <- randquadcount.data[order(randquadcount.data$Freq),]
# mean=(total number of events)/(total number of quadrats)
Mean <- n/(qX*qY)
# call function to compute statistics table
df2.data <- computeStats(randquadcount.data, Mean)
View(df2.data)
# function to compute the statistics table
computeStats <- function(dfexhsch, Mean) {
# create a new data frame
df1.data <- data.frame(numeric(), numeric(),numeric(), numeric(), numeric())
i <- 1
# loop until the number of rows of resultant data frame obtained after quadrat count method
while (i <= nrow(dfexhsch)) {
# count variable to keep track of the number of quadrats corresponding to each event
count <- 1
# To get the number of quadrats having each event. loop till the 2nd-last row and until the n-th row Frequency column=(n+1)-th row Frequency column
while(i <= nrow(dfexhsch)-1 & dfexhsch$Freq[i] == dfexhsch$Freq[i+1]){
# increment count variable
count <- count+1
# increment i
i <- i+1
}
# compute (number of events-mean)
Difference <- (dfexhsch$Freq[i]-Mean)
# create new row
New <- c(dfexhsch$Freq[i], count, Difference, (Difference)^2,
count*(Difference)^2)
# insert this row into df1.data data frame
df1.data <- InsertRow(df1.data, NewRow = New)
i <- i+1
}
colnames(df1.data) <- c("Number of Events(K)","Number of Quadrants(X)", "K-Mean",
"(K-Mean)^2", "X(K-Mean)^2")
return(df1.data)
}
(3)
# call function to compute VMR value in regular quadrat count method
message("VMR Value of Regular Quadrant Sampling Approach is: ", computeVMR(df1.data, n, qX*qY))
# call function to compute VMR value in random quadrat count method
message("VMR Value of Random Quadrant Sampling Approach is: ", computeVMR(df2.data, n, qX*qY))
# compute VMR function
computeVMR <- function(df.data, n, numquads) {
# Mean=number of events/number of quadrats
Mean <- n/numquads
# Variance=X*(K-Mean)^2
Variance <- (sum(df.data[, 5]))/(numquads-1)
# VMR value =Variance/Mean
return(Variance/Mean)
}
|
5aee15a182900d03d77f9597dda169491c57bfa9 | 552268b865147788b76440c8304fa81a68f1f25b | /R/numeral.R | 6039ed44c9ee63c07783f0f07c1082cac6f7d4ee | [
"MIT"
] | permissive | joeroe/numerals | 3b3ff170b26bbaa3120e90344f0844fc7cf8e03d | 1789f221a705163a9166417ccc6bb0ab8d06344f | refs/heads/master | 2023-05-27T05:37:44.480957 | 2023-05-14T11:21:19 | 2023-05-14T11:21:19 | 336,278,911 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,842 | r | numeral.R | # numeral.R
# S3 vector class numeral (numr): numerics in other numeral systems
methods::setOldClass(c("numeral", "vctrs_vctr"))
# Construct ---------------------------------------------------------------
#' Numeral class
#'
#' @description
#' The `numeral` class extends the base numeric vectors with methods for
#' printing them using UTF digits from other numeral systems.
#'
#' @param x A numeric vector.
#' @param system Two-letter language code of the desired numeral system; see
#' details for a list of available systems. Default: `"en"`.
#'
#' @details
#' The following numeral systems are currently supported:
#'
#' * `"en"`: Western Arabic numerals (the default display in base R)
#' * `"ar"`: Eastern Arabic numerals
#' * `"bn"`: Bengali numerals
#' * `"fa"`: Persian numerals
#' * `"my"`: Burmese numerals
#'
#' @return
#' Vector of class `numeral`.
#'
#' @export
#'
#' @examples
#' # Eastern Arabic numerals
#' numeral(1:10, "ar")
#'
#' # Persian numerals
#' numeral(1:10, "fa")
numeral <- function(x = numeric(), system = c("en", "ar", "bn", "fa", "my")) {
x <- vec_cast(x, numeric())
system <- rlang::arg_match(system)
new_numeral(x, system)
}
new_numeral <- function(x = numeric(), system = character()) {
vec_assert(x, numeric())
vec_assert(system, character())
new_vctr(x, system = system, class = "numeral")
}
# Validate ----------------------------------------------------------------
is_numeral <- function(x) {
inherits(x, "numeral")
}
# Print/format ------------------------------------------------------------
#' @export
vec_ptype_abbr.numeral <- function(x, ...) "numr"
#' @export
format.numeral <- function(x, ...) {
out <- format(vec_data(x))
out <- numr_replace(out, numr_system(x))
out
}
# Cast/coerce -------------------------------------------------------------
## Self -------------------------------------------------------------------
#' @export
vec_ptype2.numeral.numeral <- function(x, y, ...) {
new_numeral(system = numr_system(x))
}
#' @export
vec_cast.numeral.numeral <- function(x, to, ...) {
new_numeral(vec_data(x), system = numr_system(to))
}
## Double -----------------------------------------------------------------
#' @export
vec_ptype2.numeral.double <- function(x, y, ...) x
#' @export
vec_ptype2.double.numeral <- function(x, y, ...) y
#' @export
vec_cast.numeral.double <- function(x, to, ...) {
new_numeral(x, system = numr_system(to))
}
#' @export
vec_cast.double.numeral <- function(x, to, ...) {
vec_data(x)
}
## Integer ----------------------------------------------------------------
#' @export
vec_ptype2.numeral.integer <- function(x, y, ...) x
#' @export
vec_ptype2.integer.numeral <- function(x, y, ...) y
#' @export
vec_cast.numeral.integer <- function(x, to, ...) {
new_numeral(vec_cast(x, numeric()), system = numr_system(to))
}
#' @export
vec_cast.integer.numeral <- function(x, to, ...) {
vec_cast(vec_data(x), integer())
}
## Character --------------------------------------------------------------
#' @export
vec_ptype2.numeral.character <- function(x, y, ...) y
#' @export
vec_ptype2.character.numeral <- function(x, y, ...) x
#' @export
vec_cast.numeral.character <- function(x, to , x_arg = "", to_arg = "", ...) {
stop_incompatible_cast(x, to , x_arg = x_arg, to_arg = to_arg)
}
#' @export
vec_cast.character.numeral <- function(x, to, ...) {
numr_replace(as.character(vec_data(x)), numr_system(x))
}
# Arithmetic --------------------------------------------------------------
#' @method vec_arith numeral
#' @export
vec_arith.numeral <- function(op, x, y, ...) {
UseMethod("vec_arith.numeral", y)
}
#' @method vec_arith.numeral default
#' @export
vec_arith.numeral.default <- function(op, x, y, ...) {
stop_incompatible_op(op, x, y)
}
#' @method vec_arith.numeral numeral
#' @export
vec_arith.numeral.numeral <- function(op, x, y, ...) {
new_numeral(vec_arith_base(op, x, y), numr_system(x))
}
#' @method vec_arith.numeral numeric
#' @export
vec_arith.numeral.numeric <- function(op, x, y, ...) {
new_numeral(vec_arith_base(op, x, y), numr_system(x))
}
#' @method vec_arith.numeric numeral
#' @export
vec_arith.numeric.numeral <- function(op, x, y, ...) {
new_numeral(vec_arith_base(op, x, y), numr_system(y))
}
#' @method vec_arith.numeral MISSING
#' @export
vec_arith.numeral.MISSING <- function(op, x, y, ...) {
switch(op,
`-` = x * -1,
`+` = x,
stop_incompatible_op(op, x, y))
}
# Attributes --------------------------------------------------------------
#' Get or set the numeral system of a vector
#'
#' These functions retrieve or replace the `system` attribute of a [numeral]
#' vector.
#'
#' @param x [numeral] vector.
#'
#' @export
#'
#' @examples
#' x <- numeral(1, "ar")
#' numr_system(x)
numr_system <- function(x) {
attr(x, "system")
}
|
089fe8e18ab883182eec7ab46c2d0ffc22d2a8af | 33fbc6c3ee8736c631cee0068168fd8c5c50801f | /env/sea_surface_temperature/visulaize_sst.R | 2f24081a01f64f382874c65d721ef2f14e4a6d8f | [] | no_license | wei51/global-climate-change | 0c76b645a901b346ed7a4ea4646f1c314620798c | b69e1190591a0365a7f05456ae1406d8cf04fb22 | refs/heads/main | 2023-04-23T17:50:17.399481 | 2021-05-03T15:04:40 | 2021-05-03T15:04:40 | 363,795,482 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,822 | r | visulaize_sst.R | library(maps)
library(fields)
rotate <- function(x) t(apply(x, 2, rev))
in_path <- ''
DATRAS_anomaly <- as.matrix(read.table(paste0(in_path,'sst_anomaly_allyear_mean_till_2011.csv'),F,','))
y2 <- seq(49.5,61.75,0.25)
x2 <- seq(-4,12.75,0.25)
jpeg(filename = './output/sst_anomaly_allyear_mean_till_2011.jpg', width=6, height=6, units='in', res=300)
par(mar=c(5,5,2,2))
image(x2, y2,
z = rotate(DATRAS_anomaly),
zlim = c(-1,2),
col = tim.colors(28),
#breaks = zbreaks,
useRaster = TRUE,
xlab = "Longitude",
ylab = "Latitude",
main = "",
#add=TRUE,
axes=FALSE,
xaxs="i",
yaxs="i",
cex.lab=1.3)
map("world",
xlim=c(-4, 12.75),
ylim=c(49.5, 61.75),
col="gray90",
fill=TRUE,
add=TRUE,
type="polygon",
border="grey70")
axis(1, at=c(0,5,10), labels=c('0','5','10'), cex.axis=1.2, lwd=1.5)
axis(2, las=TRUE, at=c(50,55,60), labels=c('50','55','60'), cex.axis=1.2, lwd=1.5)
box(which = "plot", col = "black", lwd = 1.5)
dev.off()
# bar ----
color.bar <- function(lut,
min,
max,
nticks,
ticks=seq(min, max, len=nticks),
title='',
labels) {
scale = (length(lut)-1)/(max-min)
print(ticks)
#dev.new(width=1.75, height=5)
par(mar=c(2,2,5,5))
plot(c(0,0.01),
c(min,max),
type='n',
bty='n',
xaxt='n',
xlab='',
yaxt='n',
ylab='',
xaxs="i",
yaxs="i",
main = title,
cex.main = 1.3)
for (i in 1:(length(lut)-1)) {
y = (i-1)/scale + min
rect(0,y,0.1,y+1/scale, col=lut[i], border=FALSE)
}
axis(4,
at=seq(round(min,1),
round(max,1),
(max-min)/nticks),
las=2,
labels=labels,
cex.axis = 1.2,
tick=FALSE)
box(which = "plot", col = "black", lwd = 1.5)
#box(which = "figure", col = "black", lwd = 1.5)
}
jpeg(filename = './output/2011_bar.jpg', width = 2.5, height = 15, units = 'in', res = 300)
par(mar=c(5,0,1,20))
color.bar(tim.colors(28),
min=-1, #min(DATRAS_anomaly, na.rm = T)
max=2, #max(DATRAS_anomaly, na.rm = T)
nticks=15,
title="SST anomaly",
#labels=seq(min(DATRAS_anomaly, na.rm = T),max(DATRAS_anomaly, na.rm = T),0.2)
labels=seq(-1,2,0.2)
)
dev.off() |
caa7b46e05992ccbe83fb49cbe06de522361865a | 7c72684b7321943f89c6a3134bf0b7cd7012c93c | /emacs/emacs_key.rd | 8e7e44ade60280c75240330fef62ca11da973e34 | [] | no_license | shokichi/memo_rd | a03e9dbce2d8e5fe81f6a4f37729d7617cc7adf7 | 16bb566e9b82575dfc0bdc26fa487e9a5d7d66bd | refs/heads/master | 2016-09-10T19:43:51.201580 | 2015-08-20T06:36:57 | 2015-08-20T06:36:57 | 12,355,412 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,373 | rd | emacs_key.rd | #####################################
# Emacs コマンド集
#
#####################################
=begin
= Emacsコマンド集
Emacsのコマンドをひたすら載せていく
* 書き方
C : Ctrl
M : Alt, Esc, C-3
== 窓の操作
* 縦に分割
C-x 3
* 横に分割
C-x 2
* 削除
* 自分のいるウインドウを削除
C-x 0
* 自分のいるウインドウ以外を削除
C-x 1
* 時計回りに移動
C-o
== ターミナル
emacs上でShellを扱う
* term
M-x term
* shell
M-x shell
* eshell
M-x eshell
自分はeshellがお気に入り
== 編集
* コピー
M-w
* 貼り付け
C-y
* 切り取り
C-w
* 行末まで削除
C-k
* Undo
C-\
* 検索
C-s
* 置換
M-%
* 行の先頭に挿入
C-x rt
* 保存
C-x C-s
* 整列
M-x align
* 一括インデント
C-M-\
== その他
* バッファの先頭に移動
M-<
* バッファの最後尾に移動
M->
* 終了
C-x C-c
* ファイルを開く
C-x C-f
* 行数表示
M-x linum
* Fortranモード
M-x f90-mode
* emacs設定ファイルの変更を反映
C-x C-e
* Elispのインターフェース起動
M-x ielm
* バイトコンパイル
M-x byte-compile-file
== etags
タグジャンプ
M-.
初めにTAGファイルを指定するように言われる
元のところに戻る
M-*
* TAGの作成
$ etags *.rb
$ etags *.rb */*.rb
=end
|
ade52b97b2de44f5319c85f0a5efa507e01f72e8 | 5ce323d11a47f8f5d48376e36800e9d9982dee0c | /R/01_download_data.R | 25887c61dc589c551c9e65df9e271fdf0215ae5d | [] | no_license | jhmatthes/NEON_NScaling | 5dddc5f843beee82c48a5d284e056d6274296bcb | 4c01c67941a4d6cc5b4de794c0691f3261beaacf | refs/heads/master | 2022-07-10T18:59:06.703191 | 2022-06-22T16:00:49 | 2022-06-22T16:00:49 | 223,509,417 | 1 | 1 | null | null | null | null | UTF-8 | R | false | false | 4,210 | r | 01_download_data.R | # This code downloads and stacks 5 NEON data products used in the NEON N Across Scales manuscript.
#
# You will only need to run this code once to download the data and unzip the files
# to stack the data into merged files by data product.
#
# The neonUtilities loadByProduct() function downloads and stacks data products by site x year
#
# You could re-run this code periodically to try to find any updated data products,
# but beware that this might overwrite existing previously downloaded data.
#
# Data products used in this project include:
# canopy foliar chemistry: DP1.10026.001
# soil chemical properties (distributed plots, periodic): DP1.10086.001
# litter chemical properties: DP1.10033.001
# root chemical properties: DP1.10067.001
# NEON token
neonToken <- "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJhdWQiOiJodHRwczovL2RhdGEubmVvbnNjaWVuY2Uub3JnL2FwaS92MC8iLCJzdWIiOiJrZWxsZXJhYkB1bW4uZWR1Iiwic2NvcGUiOiJyYXRlOnB1YmxpYyIsImlzcyI6Imh0dHBzOi8vZGF0YS5uZW9uc2NpZW5jZS5vcmcvIiwiZXhwIjoxNzY2ODk2ODgwLCJpYXQiOjE2MDkyMTY4ODAsImVtYWlsIjoia2VsbGVyYWJAdW1uLmVkdSJ9.L2gHraOdcGLWe1dvJDPxpDymwMusPBCLqutgNP2V9bnV3Aqz0hgGJOqvvVjJgP1Qvjc-JV1GIr_cm-61YGl-0g"
#remove.packages(library(neonUtilities))
#Use github version of neonUtilities to download just needed tables
# library(devtools)
# devtools::install_github('NEONScience/NEON-utilities/neonUtilities', ref='2.0')
# #restart R
#for downloading the neonNTrans package
library(devtools)
#install_github("NEONScience/NEON-Nitrogen-Transformations/neonNTrans", dependencies=TRUE)
#library(neonNTrans)
# Load NEON download/processing R package
library(neonUtilities)
#?loadByProduct
# Download and stack soil chemical properties (distributed plots, periodic): DP1.10078.001
# 26 Oct 20: Bundled into DP1.10086.001
soilCN <- loadByProduct(dpID="DP1.10086.001", site="all", check.size = F,
token = neonToken,
tabl = "sls_soilChemistry")
list2env(soilCN, .GlobalEnv)
#create dataframe to see which sites are acid treatment (no C:N data)
# soilCN_original_info = data.frame(soilCN$sls_soilChemistry)
# head(soilCN_original_info)
# soilCN_original_info = soilCN_original_info %>%
# select(siteID,plotID, acidTreatment,analysisDate) #%>%
# filter(acidTreatment=='Y')
#
# # save to file
# acid_treat_sites<-soilCN_original_info[!duplicated(soilCN_original_info),]
# write.csv(acid_treat_sites,'acid_treated_sites.csv')
# Download and stack Root biochemistry
# 26 Oct 20: Bundled into DP1.10067.001
rootCN <- loadByProduct(dpID="DP1.10067.001", site="all", check.size = F,
token = neonToken,
tabl = "bbc_rootChemistry")
list2env(rootCN, .GlobalEnv)
# Download and stack canopy foliar chemistry: DP1.10026.001
foliarCN <- loadByProduct(dpID="DP1.10026.001", site="all", check.size = F,
token = neonToken, tabl = "cfc_carbonNitrogen")
list2env(foliarCN, .GlobalEnv)
# soil inorganic N: ammonium and nitrate
# inorganicN <- loadByProduct(dpID="DP1.10086.001", site="all", check.size = F,
# token = neonToken, tabl='ntr_externalLab')
#
# list2env(inorganicN, .GlobalEnv)
#
# look <- data.frame(inorganicN[2])
# Didn't run into this issue (JHM, 1/5/21)
#sls_soilChemistry <- soilCN$`1` # fix naming scheme!?!
# Download and stack litter chemical properties: DP1.10031.001
# 26 Oct 20: Bundled into DP1.10033.001
litterCN <- loadByProduct(dpID="DP1.10033.001", site="all", check.size = F,
token = neonToken,
tabl = "ltr_litterCarbonNitrogen")
list2env(litterCN, .GlobalEnv)
# Soil texture
# 09 Dec 20: Bundled into DP1.10047.001
soiltexture <- loadByProduct(dpID = "DP1.10047.001", site = "all",
check.size = F, token = neonToken,
tabl = "spc_particlesize")
list2env(soiltexture, .GlobalEnv)
# # Check if data/ folder exists in path, if not, create it
# if(dir.exists("data/")){
# print("Will download files to data/ folder in the current path.")
# } else{
# dir.create("data/")
# print("Created a data/ folder in the current path to hold downloaded data.")
# }
#done
|
6e76bbf7e54da7ebd0517113b98809160053f63b | fef507ac41bb7749840e7f5141ba87fde26d6f95 | /code/analysis/15_cell_composition/99-archived/Plot_dom_cell.R | 809e3a253a9559c9292d67425d860eaa71566220 | [] | no_license | LieberInstitute/spatialDLPFC | 84bc2f0b694473182d315b4d39ab3d18c2dd3536 | 840700ae86cdd414e024d9658b09dd11712ef470 | refs/heads/main | 2023-08-04T03:37:18.425698 | 2023-07-25T18:27:36 | 2023-07-25T18:27:36 | 314,001,778 | 6 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,914 | r | Plot_dom_cell.R | # Load Packages
library(tidyverse)
library(here)
library(SpatialExperiment)
library(ggpubr)
library(spatialLIBD)
# Load Spe Object
spe_dat <- readRDS(
here(
"processed-data/rdata/spe",
"01_build_spe",
"spe_filtered_final_with_clusters_and_deconvolution_results.rds"
)
)
# Subset
sampleid <- "Br8667_mid"
spe <- spe_dat[, spe_dat$sample_id == "Br8667_mid"]
fnl_dat <- colData(spe) |> data.frame()
# Calculate Total Number of Cells per spot --------------------------------
deconv_comb <- expand_grid(
res = c("broad", "layer"),
deconv = c("tangram", "cell2location", "spotlight")
)
deconv_df <- fnl_dat |>
select(starts_with(c("broad", "layer")))
deconv_com_indx_mat <- deconv_comb |>
pmap_dfc(.f = function(res, deconv) {
str_starts(names(deconv_df), paste(res, deconv, sep = "_")) |>
as.integer() |>
data.frame() |>
set_names(paste(res, deconv, sep = "_"))
}) |>
as.matrix()
# Check if the correct number of colums are detected
stopifnot(
colSums(deconv_com_indx_mat) == ifelse(deconv_comb$res == "broad", 7, 13)
)
deconv_cell_counts <- (deconv_df |> as.matrix()) %*% deconv_com_indx_mat
# Find Dominate Spots -----------------------------------------------------
dom_thres <- 0.5
res <- "broad"
deconv <- "tangram"
c_type_oi <- "excit"
deconv_count <- deconv_cell_counts |>
data.frame() |>
pull(paste(res, deconv, sep = "_"))
coi_perc <- fnl_dat |>
dplyr::select(n_coi = paste(res, deconv, c_type_oi, sep = "_")) |>
cbind(n_cell = deconv_count) |>
mutate(
perc_coi = n_coi / n_cell,
include = perc_coi > dom_thres
)
coi_perc <- coi_perc / deconv_count
coloc_spe <- calc_coloc(spe_dat, "EFNA5", "EPHA5", sample_id = "Br8667_mid")
tmp <- vis_coloc(coloc_spe[, which(coi_perc$include == TRUE)],
"EFNA5", "EPHA5",
sample_id = "Br8667_mid"
)
|
416c2fed3ccaf6cd37976ef30640e8e4f363e703 | 586489bbdd1ce77280e9fc9bece56347aadb2324 | /R/mergeAltLociInfoTables.R | 129d1be0b4d51f453df35c3ce8052b50fd059f0a | [
"CC-BY-4.0"
] | permissive | anykine/asdpex | 4e6eb16a7537ce6db2163c62ede24ea276a97936 | 688a923f297338f0053c94d620a8601b1c4d9203 | refs/heads/master | 2022-12-26T00:26:26.799728 | 2019-12-12T12:36:51 | 2019-12-12T12:36:51 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,110 | r | mergeAltLociInfoTables.R | ##
# Script to combine the tables containing alt loci infos from NCBI into a single one
##
## PATHES
regionPath<- "/home/mjaeger/data/NCBI/HomoSapiens/GRCh38.p2/genomic_regions_definitions.txt"
placementPath<- "/home/mjaeger/data/NCBI/HomoSapiens/GRCh38.p2/all_alt_scaffold_placement.txt"
accessionsPath<- "/home/mjaeger/data/NCBI/HomoSapiens/GRCh38.p2/alts_accessions_GRCh38.p2"
## DATA
regions<- read.table(regionPath,header = T,sep="\t",comment.char = "!")
colnames(regions)<- c("region_name","chromosome","region_start","region_stop")
placement<- read.table(placementPath,header = T,sep="\t",comment.char = "!")
placement<- placement[,c(1,3:4,6:ncol(placement))]
colnames(placement)[1]<- "alt_asm_name"
accessions<- read.table(accessionsPath,header = T,sep="\t",comment.char = "!")
accessions<- accessions[,2:ncol(accessions)]
# combine
dat<- merge(regions,placement,by="region_name")
dat<- merge(dat,accessions,by.x="alt_scaf_acc",by.y="RefSeq.Accession.version")
dat<- dat[order(dat$region_name,dat$alt_asm_name),]
write.table(dat,"../data/combinedAltLociInfo.tsv",row.names=F,sep="\t",quote=F)
|
9fa789076e157c30149d1749d5f49b7b561fa9f0 | 3daa44ce7b08fbb7755a73fe694876883efdcde2 | /plot1.R | abfdd80ca7b31a2fbd39516bbf90a0efc43467d8 | [] | no_license | Sykonba/ExData_Plotting1 | 2d4f961932663bb64e7b15fc733b7ae97a922368 | ce842a9f1fa961c81d28c9208058b35142fe3fa3 | refs/heads/master | 2021-01-19T07:48:28.181620 | 2015-11-08T20:49:14 | 2015-11-08T20:49:14 | 45,792,814 | 0 | 0 | null | 2015-11-08T18:23:22 | 2015-11-08T18:23:22 | null | UTF-8 | R | false | false | 267 | r | plot1.R | source("readFile.R")
png(filename = "plot1.png",
width = 480, height = 480)
hist(subsetDate$Global_active_power,
col = "red",
main = "Global Active Power",
xlab = "Global Active Power (kilowatts)",
breaks = 12, ylim = c(0, 1200))
dev.off() |
6632518a3f1f47a21871918ebc363264e635919e | 3d99ce77bf27d57da08cc0fa472d9a1601d68b90 | /R/makeMulticoreCluster.R | 32856dfa1984de8620fd998f672e4d106986b42d | [] | no_license | shadogray/parallelMap | 5865a2e886211e2b2868118012704c19a25b4d51 | 101b91d904095cf9d4e2da48edb33a86499bac0a | refs/heads/master | 2020-04-29T09:01:36.625362 | 2018-08-14T07:20:26 | 2018-08-14T07:20:26 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 799 | r | makeMulticoreCluster.R | # fake cluster constructor mimicking makeCluster to store some settings.
makeMulticoreCluster = function(mc.preschedule = FALSE, mc.set.seed = TRUE, mc.silent = FALSE, mc.cleanup = TRUE) {
assertFlag(mc.preschedule)
assertFlag(mc.set.seed)
assertFlag(mc.silent)
assertFlag(mc.cleanup)
x = get(".MulticoreCluster", envir = getNamespace("parallelMap"))
x$mc.preschedule = mc.preschedule
x$mc.set.seed = mc.set.seed
x$mc.silent = mc.silent
x$mc.cleanup = mc.cleanup
invisible(TRUE)
}
MulticoreClusterMap = function(FUN, ...) {
opts = as.list(get(".MulticoreCluster", envir = getNamespace("parallelMap")))
mcmapply_fixed(FUN, ...,
mc.preschedule = opts$mc.preschedule,
mc.set.seed = opts$mc.set.seed,
mc.silent = opts$mc.silent,
mc.cleanup = opts$mc.cleanup)
}
|
99bea596893cbc16506f3494988d7764df0f41fe | 91dbaca77d4de370037fe1b2ac61408e9835ee7d | /server.R | 9df9c54d19d22b69666629786c9f480f40f08140 | [] | no_license | zachf1989/Developing-Data-Products | fa6997c4517f15d22c4b41ee1b401afb56c05767 | 0f6749242c353ba4a75534c240dd6a553671fb73 | refs/heads/master | 2020-04-27T22:59:21.870616 | 2015-02-22T17:40:20 | 2015-02-22T17:40:20 | 31,172,123 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 923 | r | server.R | library(shiny)
library(ggplot2)
shinyServer
(
function(input, output)
{
result <- reactive(
{
if (input$to == input$from)
{
input$amt
}
else if (input$to == "EUR")
{
input$amt * 0.88
}
else
{
input$amt * 1.14
}
})
output$text <- renderPrint({paste(input$amt, input$from, "is equal to", result(), input$to)})
months <- seq(1, 23, by=1)
rate <- c(1.3167, 1.2999, 1.3010, 1.3302, 1.3222, 1.3526, 1.3584, 1.3591, 1.3746, 1.3487, 1.3802, 1.3771, 1.3867, 1.3631, 1.3692, 1.3389, 1.3133, 1.2632, 1.2525, 1.2452, 1.2099, 1.1288, 1.1383)
output$plot <- renderPlot(
{
qplot(months, rate, geom="line", main="USD vs EUR", xlab="Month", ylab="Exchange Rate") + scale_x_discrete(breaks=c(1, 8, 16, 23), labels=c("Apr 2013", "Nov 2013", "Jul 2014", "Feb 2015"))
})
}
) |
b09c9fc94db72c7bd7473416fc60496584d3c9b9 | 5f7535a265c288acef289162ebca3b9a3b49ee63 | /R/utils.R | 6de50fb02f297d7af5a5df0bbc0807b88503b606 | [] | no_license | dgarmat/RxNormR | 220b2757cc93c7bc9946b39181a4e61be77bad4f | 2c5cb0e47f505e0c8ac9b63c2ea8177e3853c3f4 | refs/heads/master | 2021-05-31T10:52:20.061321 | 2016-05-13T00:59:55 | 2016-05-13T00:59:55 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 248 | r | utils.R | restBaseURL <- "https://rxnav.nlm.nih.gov/REST/"
# Generic parser function for various response types.
parse_results <- function(result) {
if(status_code(result) != 200){
NULL
} else {
resContent <- content(result)
resContent
}
} |
505e8d85a469c1d5f017b59cdb5693b649a1d330 | 2d34708b03cdf802018f17d0ba150df6772b6897 | /googlecomputealpha.auto/man/ForwardingRulesScopedList.Rd | a5d05adf1412ff97670b73b7f004250be1245360 | [
"MIT"
] | permissive | GVersteeg/autoGoogleAPI | 8b3dda19fae2f012e11b3a18a330a4d0da474921 | f4850822230ef2f5552c9a5f42e397d9ae027a18 | refs/heads/master | 2020-09-28T20:20:58.023495 | 2017-03-05T19:50:39 | 2017-03-05T19:50:39 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,150 | rd | ForwardingRulesScopedList.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/compute_objects.R
\name{ForwardingRulesScopedList}
\alias{ForwardingRulesScopedList}
\title{ForwardingRulesScopedList Object}
\usage{
ForwardingRulesScopedList(ForwardingRulesScopedList.warning = NULL,
ForwardingRulesScopedList.warning.data = NULL, forwardingRules = NULL,
warning = NULL)
}
\arguments{
\item{ForwardingRulesScopedList.warning}{The \link{ForwardingRulesScopedList.warning} object or list of objects}
\item{ForwardingRulesScopedList.warning.data}{The \link{ForwardingRulesScopedList.warning.data} object or list of objects}
\item{forwardingRules}{List of forwarding rules contained in this scope}
\item{warning}{Informational warning which replaces the list of forwarding rules when the list is empty}
}
\value{
ForwardingRulesScopedList object
}
\description{
ForwardingRulesScopedList Object
}
\details{
Autogenerated via \code{\link[googleAuthR]{gar_create_api_objects}}
No description
}
\seealso{
Other ForwardingRulesScopedList functions: \code{\link{ForwardingRulesScopedList.warning.data}},
\code{\link{ForwardingRulesScopedList.warning}}
}
|
47afc271b3a8e45bdb2f4946467b69fe5234d52e | 5b41f1a13aeda422f3ea8aa23e76524bc93b9ef2 | /tests/testthat/test_format_muts.R | f15513690b15625bf6350391bd492b005944bb24 | [] | no_license | reimandlab/ActiveDriverWGSR | d18dce5ca796c23c442bab1a88aad58a7acec90b | 846adf970d31f5ade0815c76c391010ef9472303 | refs/heads/master | 2022-10-04T13:58:22.633394 | 2022-09-03T17:00:00 | 2022-09-03T17:00:00 | 163,240,034 | 3 | 8 | null | 2020-09-07T13:37:22 | 2018-12-27T02:58:28 | R | UTF-8 | R | false | false | 3,365 | r | test_format_muts.R | context("Testing the function of the format_muts function")
# loading mutations
data(cll_mutations)
# Formatting muts
this_genome = BSgenome.Hsapiens.UCSC.hg19::Hsapiens
formatted_muts = format_muts(cll_mutations[1:10,], this_genome = this_genome)
test_that("format_muts returns a data frame with the right columns",{
this_genome = BSgenome.Hsapiens.UCSC.hg19::Hsapiens
expect_output(format_muts(cll_mutations, this_genome = this_genome), "reversing 0 positions")
expect_identical(colnames(formatted_muts)[ncol(formatted_muts)], "tag")
expect_is(formatted_muts[,"chr"], "character")
expect_is(formatted_muts[,"pos1"], "numeric")
expect_is(formatted_muts[,"pos2"], "numeric")
expect_is(formatted_muts[,"ref"], "character")
expect_is(formatted_muts[,"alt"], "character")
expect_is(formatted_muts[,"patient"], "character")
expect_is(formatted_muts[,"tag"], "character")
# Testing that filtering works
some_patients = c("001-0002-03TD", "003-0005-09TD", "012-02-1TD", "125", "128", "141", "178")
this_genome = BSgenome.Hsapiens.UCSC.hg19::Hsapiens
expect_output(format_muts(cll_mutations[cll_mutations$patient %in% some_patients,],
this_genome = this_genome, filter_hyper_MB = 1),
"2 remove hypermut, n= 6709 , 50 %")
# Testing that SNVs only works
this_mutations = cll_mutations[cll_mutations$pos2 == cll_mutations$pos1,]
this_mutations = this_mutations[1:10,]
this_genome = BSgenome.Hsapiens.UCSC.hg19::Hsapiens
test_snvs_only = format_muts(mutations = this_mutations, this_genome = this_genome)
expect_identical(colnames(test_snvs_only)[ncol(test_snvs_only)], "tag")
})
test_that("testing errors on the format muts function",{
# Filtering hypermutated samples
this_genome = BSgenome.Hsapiens.UCSC.hg19::Hsapiens
expect_error(format_muts(mutations = cll_mutations, this_genome = this_genome,
filter_hyper_MB = 0.1),
"No mutations left after filtering hypermutators")
# Testing that mutations in unsequenceable regions are filtered (Part of .get_3n_context_of_mutations)
this_genome = BSgenome.Hsapiens.UCSC.hg19::Hsapiens
this_mutations = data.frame("chr" = "chr1",
"pos1" = 126000000,
"pos2" = 126000000,
"ref" = "C",
"alt" = "A",
"patient" = "Lady Gaga",
stringsAsFactors = F)
this_mutations = rbind(cll_mutations[1:10,], this_mutations)
expect_output(format_muts(mutations = this_mutations, this_genome = this_genome,
filter_hyper_MB = 30),
"Removing 1 invalid SNVs & indels")
# This test doesn't work - I'm not sure why yet
# Testing that mutations outside of ranges do not work (Part of .get_3n_context_of_mutations)
# this_mutations = data.frame("chr" = "chr1",
# "pos1" = 249250621,
# "pos2" = 249250622,
# "ref" = "C",
# "alt" = "A",
# "patient" = "Lady Gaga",
# stringsAsFactors = F)
# expect_error(format_muts(mutations = this_mutations,
# filter_hyper_MB = 30), "")
})
|
251835366ec258bd17a6cc6ae794d0a1cb54dd4a | 969e1c4b5ba41f2a79beac71e0e842adb514f6df | /man/plotIdFDRspace.Rd | d4ae5364e34a93ccf7d1a10a76901b72398fd5b1 | [
"Apache-2.0"
] | permissive | kiahalespractice/CCprofiler | 8f45fdef5593ef1b5d23454c27661fbce9655338 | 60e24828349b7c03bf82d9f178353c0e41a95565 | refs/heads/master | 2023-07-12T10:09:56.710306 | 2021-05-14T11:28:03 | 2021-05-14T11:28:03 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,710 | rd | plotIdFDRspace.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/getBestFeatureParameters.R
\name{plotIdFDRspace}
\alias{plotIdFDRspace}
\title{Plot FDR gridsearch}
\usage{
plotIdFDRspace(grid_search_stats, best_parameters, level = "complex",
id_level = "TP", FDR_cutoff = 0.1,
colour_parameter = "min_feature_completeness", PDF = TRUE,
name = "ID_FDR_plot.pdf")
}
\arguments{
\item{grid_search_stats}{Table of grid search statistics
(obtained from \code{\link{estimateGridSearchDecoyFDR}}).}
\item{best_parameters}{data.table with one row containing the selected parameter set.}
\item{level}{Character string, either 'complex' or 'protein'.
Specifies which feature finding was performed. Defaults to 'complex'.}
\item{id_level}{Character string, either 'TP' or 'P'.
Plot with true-positive numbers or all positives as y axis. Defaults to 'TP'}
\item{FDR_cutoff}{Numeric, the cutoff for the FDR (indicated by a vertical line in the plot).
Defaults to \code{0.1}.}
\item{colour_parameter}{Character string, Which parameter to color. Defaults to 'completeness_cutoff'}
\item{PDF}{Logical, wether to save the plot as a PDF file in working directory.
Defaults to \code{TRUE}.}
\item{name}{Character string, filename of the PDF output.}
}
\value{
Either a plot to the R console or a PDF file in the working directory.
}
\description{
Plot the result of a grid search depending on a specified parameter.
}
\examples{
## NOT RUN
gridStats # see function \\code{\\link{estimateGridSearchDecoyFDR}} to see how to generate this object.
## Plot the result of the grid search depending on the within feature correlation
plotIdFDRspace(gridStats, PDF = F, colour_parameter = "min_peak_corr")
}
|
8923fa5d3a1ca177c05f88cad4cb356753240337 | 90e772dfeb9fc441424dcf5e5beaa545af606f1c | /R/testNeutral.R | 929bda276b639d6e8539d37f0147c89972a4a9fd | [
"GPL-3.0-only"
] | permissive | chenjy327/MesKit | 97d356c8c8ac73493ba6f60488d5a0c6aae23092 | c9eb589fca6471e30e45cb9e03030af5ade69f83 | refs/heads/master | 2021-08-17T07:48:53.618404 | 2021-06-24T06:19:08 | 2021-06-24T06:19:08 | 304,196,319 | 0 | 0 | MIT | 2020-10-15T03:10:38 | 2020-10-15T03:10:37 | null | UTF-8 | R | false | false | 9,744 | r | testNeutral.R | #' testNeutral
#' @description Evaluate whether a tumor follows neutral evolution or under strong selection during the growth based on variant frequency distribution (VAF) of subclonal mutations.
#' The subclonal mutant allele frequencies of a follow a simple power-law distribution predicted by neutral growth.
#'
#' @references Williams, M., Werner, B. et al. Identification of neutral tumor evolution across cancer types. Nat Genet 48, 238-244 (2016)
#'
#' @param maf Maf or MafList object generated by \code{\link{readMaf}} function.
#' @param patient.id Select the specific patients. Default NULL, all patients are included.
#' @param withinTumor Test neutral within tumros in each patients. Default FALSE.
#' @param min.total.depth The minimun total depth of coverage. Defalut 2
#' @param min.vaf The minimum value of adjusted VAF value. Default 0.1
#' @param max.vaf The maximum value of adjusted VAF value. Default 0.3
#' @param R2.threshold The threshod of R2 to decide whether a tumor follows neutral evolution. Default 0.98
#' @param min.mut.count The minimun number of subclonal mutations used to fit model. Default 20
#' @param plot Logical, whether to print model fitting plot of each sample. Default TRUE.
#' @param use.tumorSampleLabel Let Tumor_Sample_Barcode replace Tumor_Sample_Label if Tumor Label is provided in clinical data. Default FALSE.
#' @param ... Other options passed to \code{\link{subMaf}}
#'
#' @return the neutrality metrics and model fitting plots
#'
#' @examples
#' maf.File <- system.file("extdata/", "CRC_HZ.maf", package = "MesKit")
#' clin.File <- system.file("extdata/", "CRC_HZ.clin.txt", package = "MesKit")
#' ccf.File <- system.file("extdata/", "CRC_HZ.ccf.tsv", package = "MesKit")
#' maf <- readMaf(mafFile=maf.File, clinicalFile = clin.File, ccfFile=ccf.File, refBuild="hg19")
#' testNeutral(maf)
#' @importFrom stats approxfun integrate lm
#' @export testNeutral
testNeutral <- function(maf,
patient.id = NULL,
withinTumor = FALSE,
min.total.depth = 2,
min.vaf = 0.1,
max.vaf = 0.3,
R2.threshold = 0.98,
min.mut.count = 20,
plot = TRUE,
use.tumorSampleLabel = FALSE,
...){
result <- list()
processTestNeutral <- function(m){
maf_data <- getMafData(m)
patient <- getMafPatient(m)
if(nrow(maf_data) == 0){
message("Warning: there was no mutation in ", patient, " after filtering.")
return(NA)
}
patient <- unique(maf_data$Patient_ID)
if(! "CCF" %in% colnames(maf_data)){
stop("CCF data ia required for inferring whether a tumor follows neutral evolution.")
}
neutrality.metrics <- data.frame()
if(plot){
model.fitting.plot <- list()
}
if(withinTumor){
ids <- unique(maf_data$Tumor_ID)
}else{
ids <- unique(maf_data$Tumor_Sample_Barcode)
}
processTestNeutralID <- function(id){
if(withinTumor){
subdata <- subset(maf_data, maf_data$Tumor_ID == id & !is.na(maf_data$Tumor_Average_VAF))
subdata$VAF_adj <- subdata$Tumor_Average_VAF
}else{
subdata <- subset(maf_data, maf_data$Tumor_Sample_Barcode == id & !is.na(maf_data$VAF_adj))
}
## warning
if(nrow(subdata) < min.mut.count){
warning(paste0("Eligible mutations of sample ", id, " from ", patient, " is not enough for testing neutral evolution."))
return(NA)
}
vaf <- subdata$VAF_adj
breaks <- seq(max.vaf, min.vaf, -0.005)
mut.count <- unlist(lapply(breaks,function(x,vaf){length(which(vaf > x))},vaf = vaf))
vafCumsum <- data.frame(count = mut.count, f = breaks)
vafCumsum$inv_f <- 1/vafCumsum$f - 1/max.vaf
vafCumsum$n_count <- vafCumsum$count/max(vafCumsum)
vafCumsum$t_count <- vafCumsum$inv_f/(1/min.vaf - 1/max.vaf)
## area of theoretical curve
theoryA <- stats::integrate(stats::approxfun(vafCumsum$inv_f,vafCumsum$t_count),
min(vafCumsum$inv_f),
max(vafCumsum$inv_f),stop.on.error = FALSE)$value
# area of emprical curve
dataA <- stats::integrate(approxfun(vafCumsum$inv_f,vafCumsum$n_count),
min(vafCumsum$inv_f),
max(vafCumsum$inv_f),stop.on.error = FALSE)$value
# Take absolute difference between the two
area <- abs(theoryA - dataA)
# Normalize so that metric is invariant to chosen limits
area<- area / (1 / min.vaf - 1 / max.vaf)
## calculate mean distance
meandist <- mean(abs(vafCumsum$n_count - vafCumsum$t_count))
## calculate kolmogorovdist
n = length(vaf)
cdfs <- 1 - ((1/sort(vaf) - 1/max.vaf) /(1/min.vaf - 1/max.vaf))
dp <- max((seq_len(n)) / n - cdfs)
dn <- - min((0:(n-1)) / n - cdfs)
kolmogorovdist <- max(c(dn, dp))
## R squared
lmModel <- stats::lm(vafCumsum$count ~ vafCumsum$inv_f + 0)
lmLine = summary(lmModel)
R2 = lmLine$adj.r.squared
if(withinTumor){
test.df <- data.frame(
Patient_ID = patient,
Tumor_ID = id,
Eligible_Mut_Count = nrow(subdata),
Area = area,
Kolmogorov_Distance = kolmogorovdist,
Mean_Distance = meandist,
R2 = R2,
Type = dplyr::if_else(
R2 >= R2.threshold,
"neutral",
"non-neutral")
)
}else{
test.df <- data.frame(
Patient_ID = patient,
Tumor_Sample_Barcode = id,
Eligible_Mut_Count = nrow(subdata),
Area = area,
Kolmogorov_Distance = kolmogorovdist,
Mean_Distance = meandist,
R2 = R2,
Type = dplyr::if_else(
R2 >= R2.threshold,
"neutral",
"non-neutral")
)
}
if(plot){
p <- plotPowerLaw(vafCumsum = vafCumsum, test.df = test.df, id = id,
max.vaf = max.vaf, lmModel = lmModel, patient = patient)
model.fitting.plot[[id]] <- p
}
return(list(test.df = test.df, p = p))
}
id_result <- lapply(ids, processTestNeutralID)
idx <- which(!is.na(id_result))
id_result <- id_result[idx]
neutrality.metrics <- lapply(id_result, function(x)x$test.df) %>% dplyr::bind_rows()
model.fitting.plot <- lapply(id_result, function(x)x$p)
names(model.fitting.plot) <- ids[idx]
if(nrow(neutrality.metrics) == 0){
return(NA)
}
if(plot){
return(list(
neutrality.metrics = neutrality.metrics,
model.fitting.plot = model.fitting.plot
))
}else{
return(neutrality.metrics)
}
}
if(min.vaf <= 0){
stop("'min.vaf' must be greater than 0")
}
if(max.vaf < min.vaf){
stop("'max.vaf' must be greater than min.vaf")
}
maf_input <- subMaf(maf,
min.vaf = min.vaf,
max.vaf = max.vaf,
min.total.depth = min.total.depth,
clonalStatus = "Subclonal",
mafObj = TRUE,
patient.id = patient.id,
use.tumorSampleLabel = use.tumorSampleLabel,
...)
result <- lapply(maf_input, processTestNeutral)
result <- result[!is.na(result)]
if(length(result) > 1){
return(result)
}else if(length(result) == 0){
return(NA)
}else{
return(result[[1]])
}
}
# if(plot){
# ## combind data of all patients
# violin.data <- do.call(dplyr::bind_rows, testNeutral.out$neutrality.metrics)
# if(nrow(violin.data) != 0){
# y.min <- floor(min(violin.data$R2)*10)/10
# breaks.y <- seq(y.min, 1, (1-y.min)/3)
# p.violin <- ggplot(data = violin.data,aes(x = Patient, y = R2, fill = Patient))+
# geom_violin(trim=T,color="black")+
# geom_boxplot(width=0.05,position=position_dodge(0.9))+
# geom_hline(yintercept = R2.threshold,linetype = 2,color = "red")+
# theme_bw() +
# ylab(expression(italic(R)^2))+
# scale_y_continuous(breaks = breaks.y, labels = round(breaks.y,3),
# limits = c(breaks.y[1],1))+
# ## line of axis y
# geom_segment(aes(y = y.min ,
# yend = 1,
# x=-Inf,
# xend=-Inf),
# size = 1.5)+
# theme(axis.text.x=element_text(vjust = .3 ,size=10,color = "black",angle = 90),
# axis.text.y=element_text(size=10,color = "black"),
# axis.line.x = element_blank(),
# axis.ticks.x = element_blank(),
# axis.ticks.length = unit(.25, "cm"),
# axis.line.y = element_blank(),
# axis.ticks.y = element_line(size = 1),
# axis.title.y=element_text(size = 15),
# axis.title.x=element_blank(),
# panel.border = element_blank(),axis.line = element_line(colour = "black",size=1),
# legend.text=element_text( colour="black", size=10),
# legend.title= element_blank(),
# panel.grid.major = element_line(linetype = 2),
# panel.grid.minor = element_blank())
# testNeutral.out$R2.values.plot <- p.violin
# }
# else{
# p.violin <- NA
# }
#
# } |
71dbdbd059c3923adb690e3d18dbc83f8b47a098 | 7b97530578050b52cedf88f1314a91610b3fb510 | /R/estFixeff_adptGH.r | 8df779164606929b527ea101722fe5984c9f48c9 | [] | no_license | oliviayu/HHJMs | 8a1637ddb842556d417a496316e6e0a3fa0783e4 | 34e3cfb99b736947500f2925921824f942a211cb | refs/heads/master | 2021-01-01T03:32:51.818731 | 2020-03-25T23:19:54 | 2020-03-25T23:19:54 | 57,276,395 | 1 | 2 | null | null | null | null | UTF-8 | R | false | false | 6,685 | r | estFixeff_adptGH.r |
# This function estimates the fixed parameters in the
# joint models, by maximizing the profile h-likelihood function.
### Gradient OK. (Jan 24, 2017)
estFixeff_adptGH <- function(RespLog=list(Jlik1, Jlik2),
fixed=names(fixedest0), # pars to be estimated
str_val=fixedest0, # starting values of fixed pars
Dpars=Jraneff,
idVar,
long.data, surv.data, # dataset
GHsample,
GHzsamp,
invSIGMA0,
uniqueID,
ghsize,
ParVal=NULL, # other par values, given
lower, # lower/upper bound for dispersion parameters
upper,
Silent=T){
# derive -H matrix, where H is defined in the adjusted profile h-likelihood
q <- length(Dpars)
p <- length(fixed)
n = nrow(surv.data)
L2 <- strMat(q)
q0 <- length(L2$Mpar)
weights = GHzsamp$weights
# xx=str_val
ff <- function(xx){
fy <- numeric(1)
# assign values to parameters
par.val <- Vassign(fixed, xx[1:p])
par.val <- data.frame(c(par.val, ParVal))
# invmat=SIGMA;
Lval <- Vassign(L2$Mpar, xx[-(1:p)])
invmat <- evalMat(as.list(L2$M), q, par.val=Lval)
invSIGMA <- solve(invmat)
# evaluate approximate log-likelihood
fn = rep(NA, n)
for(i in 1:n){
# i=1
subdat1 = subset(long.data, long.data[,idVar]==uniqueID[i])
subdat2 = subset(surv.data, surv.data[,idVar]==uniqueID[i])
samples = as.data.frame(GHsample[[i]]$points)
names(samples)=Dpars
likefn = rep(NA, ghsize^q)
for(j in 1:ghsize^q){
# j=2
lhlike1 = with(subdat1, with(par.val, with(samples[j,], eval(parse(text=RespLog[[1]])))))
lhlike2 = with(subdat2, with(par.val, with(samples[j,], eval(parse(text=RespLog[[2]])))))
lhlike3 = exp(-as.matrix(samples[j,])%*%invSIGMA%*%t(samples[j,])/2+sum(GHzsamp$points[j,]^2))
likefn[j] = exp(sum(lhlike1)+lhlike2)*lhlike3
}
fn[i] = log(sum(likefn*weights))
}
fy = sum(fn) + n/2*log(det(invSIGMA))
# print(n/2*log(det(invSIGMA)))
# print(sum(fn))
return(-fy)
}
gr.long <- deriv(formula(paste("~", RespLog[[1]])), fixed)
gr.surv <- deriv(formula(paste("~", RespLog[[2]])), fixed)
gr <- function(xx){
fy <- numeric(p+q0)
# assign values to parameters
par.val <- Vassign(fixed, xx[1:p])
par.val <- data.frame(c(par.val, ParVal))
# invmat=SIGMA;
Lval <- Vassign(L2$Mpar, xx[-(1:p)])
invmat <- evalMat(as.list(L2$M), q, par.val=Lval)
invSIGMA <- solve(invmat)
gn = matrix(NA, nrow=n, ncol=p+q0)
for(i in 1:n){
# i=1
subdat1 = subset(long.data, long.data[,idVar]==uniqueID[i])
subdat2 = subset(surv.data, surv.data[,idVar]==uniqueID[i])
samples = as.data.frame(GHsample[[i]]$points)
names(samples)=Dpars
likefn = rep(NA, ghsize^q)
gri = matrix(NA, ghsize^q, p+q0)
norm_term = 0
for(j in 1:ghsize^q){
# j=1
lhlike1 = with(subdat1, with(par.val, with(samples[j,], eval(parse(text=RespLog[[1]])))))
lhlike2 = with(subdat2, with(par.val, with(samples[j,], eval(parse(text=RespLog[[2]])))))
lhlike3 =exp(-as.matrix(samples[j,])%*%invSIGMA%*%t(samples[j,])/2)
lhlike_all =exp(sum(lhlike1)+lhlike2)*lhlike3
likefn[j] = lhlike_all*exp(sum(GHzsamp$points[j,]^2))
norm_term = norm_term+lhlike_all
val1 = with(par.val, with(subdat1, with(samples[j,], attr(eval(gr.long),"gradient"))))
val2 = with(par.val, with(subdat2, with(samples[j,], attr(eval(gr.surv), "gradient"))))
## derivative w.r.t parameters in cov(b)
## check, correct!
fy2 <- rep(NA, q0)
for(s in 1:q0){
dM <- L2$dM[,,s]
dM_val <- evalMat(dM, q, par.val=Lval)
fy2[s] <- -0.5* matrix.trace(invSIGMA%*%dM_val)+
0.5*diag(as.matrix(samples[j,])%*%invSIGMA%*%dM_val%*%invSIGMA%*%t(as.matrix(samples[j,])))
}
gri[j,] = c(apply(val1,2,sum)+val2, fy2)*likefn[j]
}
gn[i,] = as.vector(t(gri)%*%weights)/norm_term
}
fy = apply(gn,2,sum)*det(invSIGMA0)^{-1/2}*2^{q/2}
return(-fy)
}
## start iteration
str_val0 = str_val
Alower = c(lower, rep(0,q0))
Aupper = c(upper, rep(pi, q0))
# print(ff(c(str_val0, runif( q0, 0, pi))))
# print(gr(c(str_val0, runif( q0, 0, pi))))
message <- -1
M <- 1
if(Silent==F) check=0 else check=1
# start iteration
while(message != 0 & M<50){
result <- try(optim(par=c(str_val0, runif( q0, 0, pi)), fn=ff, gr=gr,
method="L-BFGS-B",
lower=Alower,
upper=Aupper,
control = list(
trace=1-check,
maxit=500
), hessian=F),
silent=T)
# result
error_mess <- attr(result, "class")
if(length(error_mess)!=0 ){
message = -1
} else {
message <- result$convergence
}
str_val0 <- sapply(str_val, function(x)x+rnorm(1,0, min(1, abs(x/2))))
if(Silent==F){ print(message); print(M); print(result) }
M <- M +1
}
if(message==0){
gamma <- result$par[1:p]
names(gamma) <- fixed
fval <- result$value
Lval <- Vassign(L2$Mpar, result$par[-(1:p)])
invmat <- evalMat(as.list(L2$M), q, par.val=Lval)
mat <- solve(invmat) # invSIGMA
# str_val0 <- sapply(str_val0, function(x)x+rnorm(1,0, min(1, abs(x/5))))
# gamma=str_val0
# gamma=xx
# myGR = gr(gamma)
# cat("my gr:", myGR, '\n')
# eps=10^{-10}
# numGr <- c()
# for(i in 1:length(gamma)){
# dist <- rep(0, length(gamma))
# dist[i] <- eps
# numGr <- c(numGr, (ff(gamma+dist)-ff(gamma))/eps)
# cat("i=",i,'\n')
# }
# cat("numerical gr:", numGr, '\n')
# #
# plot(myGR, ylim=range(c(myGR, numGr)))
# points(numGr, pch=6, col="red")
# myGR-numGr
} else {
stop("Iteration stops because fixed parameters can not be successfully estimated.")
}
return(list(gamma=gamma, fval=fval, invSIGMA=mat,
Lval=Lval))
}
|
c9fc9dec5026dfe0adc4461ee0b88f0f99d2bdd4 | ec52b16379ae82af0357468a63aa2259282b8436 | /Excercise 2 Stochastic gradient descent/stochastic gradient descent/gradient descent functions.R | 54c41de76c5700ac7ca0b5561db72b59a2e631c4 | [] | no_license | yinanzhu12/SDS385-Statistical-Models-for-Big-Data | 17b7c0d02e85d243070ce690234c8047d942682c | d08d647efe4259876bab1be8a83247701359e40d | refs/heads/master | 2021-08-30T12:31:08.237655 | 2017-12-18T00:17:46 | 2017-12-18T00:17:46 | 103,061,247 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 2,109 | r | gradient descent functions.R | omega=function(X,beta){
return=as.vector(1/(exp(-X%*%beta)+1))
}
grad=function(omega,y,X){
return=as.vector(crossprod(omega-y,X))
}
nllh=function(omega,y){
r=0
for(i in 1:length(y)){
if(y[i]==1)r=r-log(omega[i])
else r=r-log(1-omega[i])
}
return=r
}
#run stochastic gradient decent on training data X y and test data testX,testY using with
# iterations number=ite and step size=eps
# evaluate the moving average of negative loglikelihood with exponential decay rate alpha
stochasticgradientdescent=function(X,y,testX,testy,beta0,eps,ite,alpha){
beta=beta0
nllh=as.vector(matrix(nrow=ite))
tnllh=as.vector(matrix(nrow=ite))
nllhaverage=as.vector(matrix(nrow=ite))
for(i in 1:ite){
# draw the index of direction
r=sample(length(y),1)
og=omega(X,beta)
testog=omega(testX,beta)
# we still compute total negative loglikelihood at each step for reference, this is not
# necessary in practice
nllh[i]=nllh(og,y)/length(y)
tnllh[i]=nllh(testog,testy)/length(testy)
beta=beta-eps*grad(og[r],y[r],X[r,])
if(i==1)nllhaverage[i]=nllh(og[r],y[r])
else nllhaverage[i]=nllh(og[r],y[r])*alpha+nllhaverage[i-1]*(1-alpha)
}
return=list(beta=beta,negloglikelihood=nllh,testnegloglikelihoood=tnllh,averagenegloglikelihood=nllhaverage)
}
#run stochastic gradient decent with vary steps, the steps are computed using Robbins Monro rule
# step size at t=C/(t0+t)^decay
varyingstepsgradientdescent=function(X,y,testX,testy,beta0,ite,alpha,decay,t0,C){
beta=beta0
nllh=as.vector(matrix(nrow=ite))
tnllh=as.vector(matrix(nrow=ite))
nllhaverage=as.vector(matrix(nrow=ite))
for(i in 1:ite){
r=sample(length(y),1)
og=omega(X,beta)
testog=omega(testX,beta)
nllh[i]=nllh(og,y)/length(y)
tnllh[i]=nllh(testog,testy)/length(testy)
eps=C/((t0+i)^decay)
beta=beta-eps*grad(og[r],y[r],X[r,])
if(i==1)nllhaverage[i]=nllh(og[r],y[r])
else nllhaverage[i]=nllh(og[r],y[r])*alpha+nllhaverage[i-1]*(1-alpha)
}
return=list(beta=beta,negloglikelihood=nllh,testnegloglikelihoood=tnllh,averagenegloglikelihood=nllhaverage)
} |
6e49c3ad947e5a19c33948700275e65f6d5b9bde | 5ccd04c7de5ddf0d8b413b31a98ffd8a46a62d6e | /R/velocity.R | a04547c2b035e96fa43dcd6d62e8c1960030307f | [] | no_license | davidecannatanuig/openFaceR | 3e812e37a1ace99e07574f9e6448eaaa6ccfd17a | b041319a77baf70eb1ff7427759085ff3e32f2fd | refs/heads/master | 2023-04-27T14:40:24.224616 | 2023-04-13T10:58:49 | 2023-04-13T10:58:49 | 283,229,605 | 7 | 1 | null | 2020-10-19T21:52:49 | 2020-07-28T14:03:03 | R | UTF-8 | R | false | false | 366 | r | velocity.R | #' Calculate velocity.
#' calculate the difference of values in each ordered value of an array
#' @param x The array to transform
#' @return an array of same length (first value is NA)
#' @examples
#' moving_difference(c(1,4,-2, 2))
moving_difference <- function(x){
y <- array()
for (i in 1:(length(x)-1)){
y[i] = x[i+1] - x[i]
}
return(c(NA, y))
}
|
2769d8b271cee836dd8a4cb334a78f5c0ef5a859 | 6a28ba69be875841ddc9e71ca6af5956110efcb2 | /Linear_Algebra_And_Its_Applications_by_David_C._Lay/CH1/EX1.17/Ex1.17.R | 0190b57af0350f835921aab184dfe5a2106b536f | [] | permissive | FOSSEE/R_TBC_Uploads | 1ea929010b46babb1842b3efe0ed34be0deea3c0 | 8ab94daf80307aee399c246682cb79ccf6e9c282 | refs/heads/master | 2023-04-15T04:36:13.331525 | 2023-03-15T18:39:42 | 2023-03-15T18:39:42 | 212,745,783 | 0 | 3 | MIT | 2019-10-04T06:57:33 | 2019-10-04T05:57:19 | null | UTF-8 | R | false | false | 502 | r | Ex1.17.R | #Chapter 1 - Linear Equations In Linear Algebra
#General solution of the system
#Page No.35 / 1-23
#Prob 13
#1.5.13
#clear console
cat("\014")
#clear variables
rm(list=ls(all=TRUE))
xv<-c(5,-2,0)
x=matrix(xv,
nrow=3,
ncol=1,
byrow=TRUE)
x1v<-c(4,-7,1)
x1=matrix(x1v,
nrow=3,
ncol=1,
byrow=TRUE)
print(x)
print(x1)
print('=p+x3*q')
cat('geometrically the solution set is the line through [', x ,'] parallel to [',x1,']') |
748b0944339f31a9a5490405ec77ba483b64eb65 | 620877d62aa98a958b59dc70b727e3e323072475 | /Chapter 6 Inference for Numerical Data.R | 424387d97738a2ed088d5b9dfc68151686f1cd07 | [] | no_license | JoshuaHaden/Data-Analysis-and-Statistical-Inference-Data-Camp | 0cade99eb3e8689313fe0e8f1e97c6b6a4f860c7 | 1de7cae8234619e6ffb2db021343cb2423334bd1 | refs/heads/master | 2021-01-23T12:05:00.645205 | 2017-09-06T18:38:55 | 2017-09-06T18:38:55 | 102,644,877 | 1 | 1 | null | null | null | null | UTF-8 | R | false | false | 4,199 | r | Chapter 6 Inference for Numerical Data.R | ###Chapter 6 Inference for Numerical Data
###North Carolina Births
# Load your dataset:
load(url("http://assets.datacamp.com/course/dasi/nc.Rdata"))
# List the variables in the dataset:
names(nc)
###A First Analysis
# The nc data frame is already loaded into the workspace
# Compute summaries of the data:
summary(nc)
# Use visualization and summary statistics to view the data for gained:
summary(nc$gained)
hist(nc$gained)
boxplot(nc$gained)
###Cleaning Your Data
# The 'nc' data frame is already loaded into the workspace
# Create a clean version fo your data set:
gained_clean <- na.omit(nc$gained)
# Set 'n' to the length of 'gained_clean':
n <- length(gained_clean)
###The Bootstrap
# The 'nc' data frame is already loaded into the workspace
# Initialize the 'boot_means' object:
boot_means <- rep(NA, 100)
# Insert your for loop:
for(i in 1:100){
boot_sample <- sample(gained_clean, n, replace = TRUE)
boot_means[i] <- mean(boot_sample)
}
# Make a histogram of 'boot_means':
hist(boot_means)
###The Inference Function
# The 'nc' data frame is already loaded into the workspace
# Load the 'inference' function:
load(url("http://assets.datacamp.com/course/dasi/inference.Rdata"))
# Run the inference function:
inference(nc$gained, type="ci", method="simulation", conflevel=0.9, est="mean", boot_method="perc")
###Setting the Confidence Interval
# The 'nc' data frame and the 'inference' function are already loaded into the workspace
# Adapt the inference function:
inference(nc$gained, type="ci", method="simulation", conflevel=0.95, est="mean", boot_method="perc")
###Choosing a Bootstrap Method
# The 'nc' data frame and the 'inference' function are already loaded into the workspace
# Adapt the inference function:
inference(nc$gained, type="ci", method="simulation", conflevel=0.95, est="mean", boot_method="se")
###Setting the Parameter of Interest
# The 'nc' data frame and the 'inference' function are already loaded into the workspace
# Adapt the inference function:
inference(nc$gained, type="ci", method="simulation", conflevel=0.95, est="median", boot_method="se")
###Father's Age
# The 'nc' data frame and the 'inference' function are already loaded into the workspace
# Adapt the inference function to create a 95% bootstrap interval for the mean age of fathers:
inference(nc$fage, type="ci", method="simulation", conflevel=0.95, est="mean", boot_method="se")
###Relationships Between Two Variables
# The 'nc' data frame is already loaded into the workspace
# Draw your plot here:
plot(nc$weight ~ nc$habit)
###The by Function
# The 'nc' data frame is already loaded into the workspace
# Use the 'by' function here:
by(nc$weight, nc$habit, mean)
###Conditions for Inference
# The 'nc' data frame is already loaded into the workspace
# Use the 'by' function here:
by(nc$weight,nc$habit,length)
###More Inference
# The 'nc' data frame is already loaded into the workspace
# The code:
inference(y = nc$weight, x = nc$habit, est = "mean", type = "ht", null = 0, alternative = "twosided", method = "theoretical")
###Changing the Order
# The 'nc' data frame is already loaded into the workspace
# Add the 'order' argument to the 'inference' function:
inference(y = nc$weight, x = nc$habit, est = "mean", type = "ht", null = 0, alternative = "twosided", method = "theoretical", order = c("smoker","nonsmoker"))
###The General Social Survey
# Load the 'gss' data frame:
load(url("http://assets.datacamp.com/course/dasi/gss.Rdata"))
head(gss$wordsum)
head(gss$class)
###Analyze the Variables
# The 'gss' data frame is already loaded into the workspace
# Numerical and visual summaries of 'wordsum' and 'class':
summary(gss$wordsum)
summary(gss$class)
hist(gss$wordsum)
boxplot(gss$wordsum)
# Numerical and visual summaries of their relations:
by(gss$wordsum, gss$class, mean)
boxplot(gss$wordsum ~ gss$class)
###ANOVA Test
# The 'gss' data frame is already loaded into the workspace
# The test:
inference(y = gss$wordsum, x = gss$class, est = "mean", method = "theoretical", type = "ht", alternative = "greater")
|
b47b9d4cf82c6831d9b2f522b6da48d5cf85feb8 | 2fac645ca865f8cbe2f680332e54dba56419cbb6 | /forecast_tobacco_gpr/05_graph_results_logit.R | bde72431ee64c88a0d859b7393a95a6682896059 | [] | no_license | reedblog/work | a833a3a9e86839594d2f5904ffa5a569f5accac7 | 4395b4346c721f504dccd28cdf7330c2d4d07758 | refs/heads/master | 2021-01-01T05:35:46.136469 | 2015-04-17T00:23:19 | 2015-04-17T00:23:19 | 31,869,279 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,983 | r | 05_graph_results_logit.R | #
# 05_graph_results.R
# Graph the output of spacetime GPR
#
# Reed Sorensen, March 2015
#
require(dplyr)
require(data.table)
require(ggplot2)
require(boot)
project_name <- "forecast_tobacco_gpr"
output_name <- "logit_rescaled_l2_o05_z99_1333_bothsexes"
adjustment <- 1.333333
out_of_sample <- FALSE
oos <- ifelse(out_of_sample, "_outofsample_test", "")
jpath <- ifelse(Sys.info()[["sysname"]] == "Windows", "J:/", "/home/j/")
hpath <- ifelse(Sys.info()[["sysname"]] == "Windows", "H:/", "/homes/rsoren/")
data_dir <- paste0(hpath, "prog/data/", project_name, "/")
codes188 <- readRDS(paste0(data_dir, "codes188.RDS"))
df.in <- fread(paste0(
hpath, "prog/data/", project_name ,"/",
output_name, "/gpr_output", oos, ".csv"))
df <- df.in %>%
mutate(
observed_data2 = inv.logit(observed_data) * 1/adjustment,
stage1_prediction2 = inv.logit(stage1_prediction) * 1/adjustment,
st_prediction2 = inv.logit(st_prediction) * 1/adjustment,
gpr_mean2 = inv.logit(gpr_mean) * 1/adjustment,
gpr_lower2 = inv.logit(gpr_lower) * 1/adjustment,
gpr_upper2 = inv.logit(gpr_upper) * 1/adjustment,
cohort = as.factor(year - age ) )
df2 <- df %>%
filter(year %in% 1980:2040) %>%
select(iso3, year, sex, age, smoking_prev = gpr_mean2) %>%
arrange(iso3, year, sex, age, smoking_prev)
df2 <- df2[!duplicated(subset(df2, select = c(iso3, year, sex, age)))]
add_ages <- expand.grid(
unique(df2$iso3),
unique(df2$year),
unique(df2$sex),
c(0, 0.01, 0.1, 1, 5)
)
names(add_ages) <- c("iso3", "year", "sex", "age")
add_ages$smoking_prev <- 0
add_ages <- add_ages[names(df2)]
df3 <- rbind(df2, add_ages) %>%
arrange(iso3, year, sex, age)
write.csv(df3, paste0(data_dir, "smoking_prev_1980_2040_logit_rescaled_l2_o05_z99_1333.csv"))
x <- rbindlist(lapply(split(df2, paste0(df2$iso3, df2$sex, df2$year)) function(x) {
tmp <- subset(df, iso3 == "USA" & sex == "male" & year == 2008)
# df <- subset(df, sex == "female")
# pdf(paste0(hpath, "prog/tmp/gpr_tobacco/fit_logit_bycohort_1980_to_2013.pdf"))
pdf(paste0(data_dir, output_name, "/cohort_graphs_", output_name, ".pdf"))
lapply(split(df, df$iso3), function(df_tmp) {
df_tmp <- subset(df, iso3 == "USA")
y.lim <- max(df_tmp$gpr_upper2)
insample_only <- TRUE
if (insample_only) { df_tmp <- subset(df_tmp, year %in% 1980:2013) }
ggplot(df_tmp, aes(x = age, y = gpr_mean2,
group = cohort, color = cohort)) +
xlab("Age") +
ylab("Smoking prevalence") +
ggtitle(codes188[codes188$iso3 == unique(df_tmp$iso3), "location_name"]) +
geom_line(cex = 0.75) +
geom_point(
data = df_tmp,
aes(x = age, y = observed_data2, group = cohort, fill = cohort),
color = "black", pch = 21, cex = 4.5) +
theme(legend.position = "none")
})
dev.off()
###################
pdf(paste0(data_dir, output_name, "/forecast_", output_name, ".pdf"))
lapply(split(df, df$iso3), function(df_tmp) {
# df_tmp <- subset(df, iso3 == "DEU")
df_tmp$age <- as.factor(df_tmp$age)
y.lim <- max(df_tmp$gpr_upper2)
ggplot(df_tmp, aes(x = year, y = gpr_mean2,
group = age, color = age)) +
xlab("Year") +
ylab("Smoking prevalence") +
ggtitle(codes188[codes188$iso3 == unique(df_tmp$iso3), "location_name"]) +
geom_line(cex = 1.5) +
geom_vline(xintercept = 2012) +
facet_wrap(~ age) +
geom_point(
aes(x = year, y = observed_data2, group = age, fill = age),
color = "black", cex = 1) +
geom_line(
data = subset(df_tmp, year %in% 2012:2040),
aes(x = year, y = gpr_lower2, group = age, color = age)) +
geom_line(
data = subset(df_tmp, year %in% 2012:2040),
aes(x = year, y = gpr_upper2, group = age, color = age)) +
geom_line(
aes(x = year, y = stage1_prediction2, group = age, fill = age),
color = "black", cex = 0.5, lty = 2) +
geom_line(
aes(x = year, y = st_prediction2, group = age, fill = age),
color = "black", cex = 0.5) +
theme(legend.position = "none")
})
dev.off()
|
776accab544d647b67e5a4027e2d1207d7c1cc99 | 61f270f58408435d53b9892cf9b7ec7847b33e3d | /R/biADMM.speed.R | 7601b9da9bbd62ae6bb2a103cca29578458f4291 | [] | no_license | sakuramomo1005/biADMM | 37cfcea1a41c946a3324d20edbf9ecfc1ccdae58 | 6c2612137c9435cc37bd1d3610e01b22497535b6 | refs/heads/master | 2023-03-26T22:36:07.944591 | 2021-03-22T15:48:05 | 2021-03-22T15:48:05 | 350,109,657 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,384 | r | biADMM.speed.R | #' bi-ADMM: a Biclustering Algorithm for the General Model (faster version)
#'
#' Same algorithm as \code{biADMM}. Call python code to speed up the running time.
#' @param X The data matrix to be clustered. The rows are the samples, and the columns are the features.
#' @param nu1 A regularization parameter for row shrinkage
#' @param nu2 A regularization parameter for column shrinkage
#' @param gamma_1 A regularization parameter for row shrinkage
#' @param gamma_2 A regularization parameter for column shrinkage
#' @param m m-nearest-neighbors in the weight function
#' @param phi The parameter phi in the weight function
#' @param prox The proximal maps. Could calculate L1 norm, L2 norm, or L-infinity, use "l1", "l2", or "l-inf", respectively.
#' @param niters Iteraion times
#' @param tol Stopping criterion
#' @param output When output = 1, print the results at each iteration. No print when output equals other value.
#'
#'
#' @return A list of results, containing matrix of A, v, z, lambda1, and lambda2
#' @export
#'
#' @examples
#' # generate dataset
#' set.seed(123)
#' X = data_gen(n = 100, p = 80)
#' # set parameters
#' nu1 = nu2 = gamma_1 = gamma_2 = 0.1
#' m = 5
#' phi = 0.5
#' # biADMM algorithm
#' res2 = biADMM.speed(X, nu1, nu2, gamma_1, gamma_2,
#' m, phi, niter = 10, tol = 0.0001, output = 0)
#' dim(res2$A)
biADMM.speed = function(X,nu1,nu2, gamma_1, gamma_2, m, phi, prox = 'l2', niters = 10, tol = 0.1, output = 1){
require(reticulate)
require(cvxbiclustr)
require(cvxclustr)
require(Matrix)
require(MASS)
path <- paste(system.file(package="biADMM"), "biADMM.python.py", sep="/")
source_python(path)
n <- dim(X)[1]
p <- dim(X)[2]
k_row <- m; k_col <- m
w_row <- kernel_weights(t(X), phi/p)
w_col <- kernel_weights(X, phi/n)
w_row <- knn_weights(w_row, k_row, n)
w_col <- knn_weights(w_col, k_col, p)
w_row <- w_row/sum(w_row)
w_col <- w_col/sum(w_col)
w_row <- w_row/sqrt(p)
w_col <- w_col/sqrt(n)
w_l <- w_row
u_k <- w_col
w_l <- matrix(w_l, length(w_l),1)
u_k <- matrix(u_k, length(u_k),1)
res <- biADMM_python(X, nu1, nu2, gamma_1, gamma_2,
w_l, u_k,
prox,
niters, tol, output = output)
result <- list(A = res[[1]], v = res[[2]], z = res[[3]], lambda_1 = res[[4]], lambda_2 = res[[5]], iters = res[[6]])
return(result)
}
|
7730bfcc4866b836f6669828bc33e44bdf256dea | 3265b0e5b9a4b19e6c2988867d04b6ad19e882bb | /R/clean_colvals.R | bd2f0cdeb1f61d12fd521f24b0caace06b1eb213 | [] | no_license | DrMattG/happypillpain | 6f4a81c53ba0fe7a8cf440e0bdeda98e8f5d1158 | c1acfca9b438291581f07e8d369c2ad678960b1f | refs/heads/master | 2023-05-03T13:26:42.300131 | 2021-05-18T06:40:34 | 2021-05-18T06:40:34 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 382 | r | clean_colvals.R | #' Convert a column to clean-names equivalent
#'
clean_colvals <- function(df, col) {
cleaned_col <-
df %>%
select({{col}}) %>%
# select(Scale) %>%
mutate(junk = 1) %>%
pivot_wider(
names_from = {{col}},
values_from = junk
) %>%
clean_names() %>%
colnames()
df %>%
mutate(
{{col}} := cleaned_col
)
} |
998fb7d4f9e4a41f2db90652a0aafc5edba32d2d | 1f64458f1ef776d15aabea3c91145e487580a2aa | /R/progression-tables.R | 20ae8062e58de9e546031bbca2aeb772d3d4e085 | [
"MIT"
] | permissive | Ed-Rubi0/STM | bf9973f3eeafa2f2eb44d01eeb4b904e23a67c45 | e3a99179ccaa09181cf133f9c84c05eb4df90584 | refs/heads/main | 2023-01-05T01:22:44.974434 | 2020-10-29T16:13:09 | 2020-10-29T16:13:09 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 14,267 | r | progression-tables.R | #' Generic progression table
#'
#' Generic progression tables allow for custom progressions using
#' \code{rep_start}, \code{rep_step}, \code{inc_start}, and
#' \code{inc_step} parameters. For more information check the
#' 'Strength Training Manual' Chapter 6.
#'
#' @param reps Number of reps
#' @param step Progression step. Default is 0. Use negative numbers (i.e., -1, -2)
#' @param rep_start Used to define intensive, normal, and extensive progression.
#' \code{rep_start} defines the adjustment for the first rep
#' @param rep_step Used to define intensive, normal, and extensive progression.
#' \code{rep_step} defines the adjustment as rep number increases
#' @param inc_start Defines the progression for \code{step} for single rep
#' @param inc_step Defines the progression for \code{step} for rep increase
#' For example, lower reps can have bigger jumps than high reps.
#' @param adjustment Additional adjustment. Default is 0.
#' @param func_max_perc_1RM What max rep table should be used?
#' Default is \code{\link{get_max_perc_1RM}}
#' @param ... Forwarded to \code{func_max_perc_1RM}. Used to differentiate between
#' 'grinding' and 'ballistic' max reps schemes.
#'
#' @return List with two elements: \code{adjustment} and \code{perc_1RM}
#' @name generic_progression_table
NULL
#' @describeIn generic_progression_table RIR Increment generic table
#' @export
#' @examples
#' RIR_increment_generic(10, step = seq(-3, 0, 1))
#' RIR_increment_generic(5, step = seq(-3, 0, 1), type = "ballistic")
RIR_increment_generic <- function(reps,
step = 0,
rep_start = 2,
rep_step = ((6 - 2) / 11),
inc_start = 1,
inc_step = ((2 - 1) / 11),
adjustment = 0,
func_max_perc_1RM = get_max_perc_1RM,
...) {
rep_RIR <- rep_start + (reps - 1) * rep_step
step_RIR <- -1 * step * (inc_start + (reps - 1) * inc_step)
adjustment <- rep_RIR + step_RIR + adjustment
perc_1RM <- func_max_perc_1RM(
max_reps = reps,
RIR = adjustment,
...
)
return(list(
adjustment = adjustment,
perc_1RM = perc_1RM
))
}
#' @describeIn generic_progression_table Percent Drop generic table
#' @export
#' @examples
#' perc_drop_generic(10, step = seq(-3, 0, 1))
#' perc_drop_generic(5, step = seq(-3, 0, 1), type = "ballistic")
perc_drop_generic <- function(reps,
step = 0,
rep_start = -0.05,
rep_step = ((-0.1 - -0.05) / 11),
inc_start = -0.025,
inc_step = ((-0.05 - -0.025) / 11),
adjustment = 0,
func_max_perc_1RM = get_max_perc_1RM,
...) {
rep_perc_drop <- rep_start + (reps - 1) * rep_step
step_perc_drop <- -1 * step * (inc_start + (reps - 1) * inc_step)
perc_1RM <- func_max_perc_1RM(
max_reps = reps,
RIR = 0,
...
)
adjustment <- rep_perc_drop + step_perc_drop + adjustment
return(list(
adjustment = adjustment,
perc_1RM = perc_1RM + adjustment
))
}
#' Progression table
#'
#' Progression table explained in the 'Strength Training Manual' Chapter 6.
#'
#' @param reps Number of reps
#' @param step Progression step. Default is 0. Use negative numbers (i.e., -1, -2)
#' @param volume Character string: 'intensive', 'normal' (Default), or 'extensive'
#' @param type Type of max rep table. Options are grinding (Default) and ballistic.
#' @param adjustment Additional adjustment. Default is 0.
#' @param func_max_perc_1RM What max rep table should be used?
#' Default is \code{\link{get_max_perc_1RM}}
#' @return List with two elements: \code{adjustment} and \code{perc_1RM}
#' @name progression_table
NULL
#' @describeIn progression_table RIR Increment progression table. This is the original
#' progression table from the Strength Training Manual
#' @export
#' @examples
#' RIR_increment(10, step = seq(-3, 0, 1))
#' RIR_increment(10, step = seq(-3, 0, 1), volume = "extensive")
#' RIR_increment(5, step = seq(-3, 0, 1), type = "ballistic")
RIR_increment <- function(reps,
step = 0,
volume = "normal",
type = "grinding",
adjustment = 0,
func_max_perc_1RM = get_max_perc_1RM) {
params <- data.frame(
volume = c("intensive", "normal", "extensive", "intensive", "normal", "extensive"),
type = c("grinding", "grinding", "grinding", "ballistic", "ballistic", "ballistic"),
rep_start = c(0, 1, 2, 0, 1, 2),
rep_step = c(0, ((3 - 1) / 11), ((6 - 2) / 11), 0, 0.2, 0.4),
inc_start = c(1, 1, 1, 1, 1, 1),
inc_step = c(((2 - 1) / 11), ((2 - 1) / 11), ((2 - 1) / 11), 0.2, 0.2, 0.2)
)
params <- params[params$volume == volume, ]
params <- params[params$type == type, ]
RIR_increment_generic(
reps = reps,
step = step,
rep_start = params$rep_start[1],
rep_step = params$rep_step[1],
inc_start = params$inc_start[1],
inc_step = params$inc_step[1],
adjustment = adjustment,
func_max_perc_1RM = func_max_perc_1RM,
type = type
)
}
#' @describeIn progression_table Fixed 2 RIR Increment progression table. This variant have fixed RIR
#' increment across reps from phases to phases (2RIR) and 2RIR difference between extensive, normal, and
#' intensive schemes
#' @export
#' @examples
#' RIR_increment(10, step = seq(-3, 0, 1))
#' RIR_increment(10, step = seq(-3, 0, 1), volume = "extensive")
#' RIR_increment(5, step = seq(-3, 0, 1), type = "ballistic")
RIR_increment_fixed_2 <- function(reps,
step = 0,
volume = "normal",
type = "grinding",
adjustment = 0,
func_max_perc_1RM = get_max_perc_1RM) {
params <- data.frame(
volume = c("intensive", "normal", "extensive", "intensive", "normal", "extensive"),
type = c("grinding", "grinding", "grinding", "ballistic", "ballistic", "ballistic"),
rep_start = c(0, 2, 4, 0, 2, 4),
rep_step = c(0, 0, 0, 0, 0, 0),
inc_start = c(2, 2, 2, 2, 2, 2),
inc_step = c(0, 0, 0, 0, 0, 0)
)
params <- params[params$volume == volume, ]
params <- params[params$type == type, ]
RIR_increment_generic(
reps = reps,
step = step,
rep_start = params$rep_start[1],
rep_step = params$rep_step[1],
inc_start = params$inc_start[1],
inc_step = params$inc_step[1],
adjustment = adjustment,
func_max_perc_1RM = func_max_perc_1RM,
type = type
)
}
#' @describeIn progression_table Fixed 4 RIR Increment progression table. This variant have fixed RIR
#' increment across reps from phases to phases (4RIR) and 4RIR difference between extensive, normal, and
#' intensive schemes
#' @export
#' @examples
#' RIR_increment(10, step = seq(-3, 0, 1))
#' RIR_increment(10, step = seq(-3, 0, 1), volume = "extensive")
#' RIR_increment(5, step = seq(-3, 0, 1), type = "ballistic")
RIR_increment_fixed_4 <- function(reps,
step = 0,
volume = "normal",
type = "grinding",
adjustment = 0,
func_max_perc_1RM = get_max_perc_1RM) {
params <- data.frame(
volume = c("intensive", "normal", "extensive", "intensive", "normal", "extensive"),
type = c("grinding", "grinding", "grinding", "ballistic", "ballistic", "ballistic"),
rep_start = c(0, 4, 8, 0, 4, 8),
rep_step = c(0, 0, 0, 0, 0, 0),
inc_start = c(4, 4, 4, 4, 4, 4),
inc_step = c(0, 0, 0, 0, 0, 0)
)
params <- params[params$volume == volume, ]
params <- params[params$type == type, ]
RIR_increment_generic(
reps = reps,
step = step,
rep_start = params$rep_start[1],
rep_step = params$rep_step[1],
inc_start = params$inc_start[1],
inc_step = params$inc_step[1],
adjustment = adjustment,
func_max_perc_1RM = func_max_perc_1RM,
type = type
)
}
#' @describeIn progression_table Percent Drop progression table. This is the original
#' progression table from the Strength Training Manual
#' @export
#' @examples
#' perc_drop(10, step = seq(-3, 0, 1))
#' perc_drop(10, step = seq(-3, 0, 1), volume = "extensive")
#' perc_drop(5, step = seq(-3, 0, 1), type = "ballistic")
perc_drop <- function(reps,
step = 0,
volume = "normal",
type = "grinding",
adjustment = 0,
func_max_perc_1RM = get_max_perc_1RM) {
params <- data.frame(
volume = c("intensive", "normal", "extensive", "intensive", "normal", "extensive"),
type = c("grinding", "grinding", "grinding", "ballistic", "ballistic", "ballistic"),
rep_start = c(0, -0.025, -0.05, 0, -0.025, -0.05),
rep_step = c(0, ((-0.05 - -0.025) / 11), ((-0.1 - -0.05) / 11), 0, -0.0025, -0.005),
inc_start = c(-0.025, -0.025, -0.025, -0.025, -0.025, -0.025),
inc_step = c(((-0.05 - -0.025) / 11), ((-0.05 - -0.025) / 11), ((-0.05 - -0.025) / 11), -0.005, -0.005, -0.005)
)
params <- params[params$volume == volume, ]
params <- params[params$type == type, ]
perc_drop_generic(
reps = reps,
step = step,
rep_start = params$rep_start[1],
rep_step = params$rep_step[1],
inc_start = params$inc_start[1],
inc_step = params$inc_step[1],
adjustment = adjustment,
func_max_perc_1RM = func_max_perc_1RM,
type = type
)
}
#' @describeIn progression_table 5% Fixed Percent Drop progression table. This variant have fixed percent
#' drops across reps from phases to phases (5%) and 5% difference between extensive, normal, and
#' intensive schemes
#' @export
#' @examples
#' perc_drop_fixed_5(10, step = seq(-3, 0, 1))
#' perc_drop_fixed_5(10, step = seq(-3, 0, 1), volume = "extensive")
#' perc_drop_fixed_5(5, step = seq(-3, 0, 1), type = "ballistic")
perc_drop_fixed_5 <- function(reps,
step = 0,
volume = "normal",
type = "grinding",
adjustment = 0,
func_max_perc_1RM = get_max_perc_1RM) {
params <- data.frame(
volume = c("intensive", "normal", "extensive", "intensive", "normal", "extensive"),
type = c("grinding", "grinding", "grinding", "ballistic", "ballistic", "ballistic"),
rep_start = c(0, -0.05, -0.01, 0, -0.05, -0.1),
rep_step = c(0, 0, 0, 0, 0, 0),
inc_start = c(-0.05, -0.05, -0.05, -0.05, -0.05, -0.05),
inc_step = c(0, 0, 0, 0, 0, 0)
)
params <- params[params$volume == volume, ]
params <- params[params$type == type, ]
perc_drop_generic(
reps = reps,
step = step,
rep_start = params$rep_start[1],
rep_step = params$rep_step[1],
inc_start = params$inc_start[1],
inc_step = params$inc_step[1],
adjustment = adjustment,
func_max_perc_1RM = func_max_perc_1RM,
type = type
)
}
#' @describeIn progression_table 2.5% Fixed Percent Drop progression table. This variant have fixed percent
#' drops across reps from phases to phases (2.5%) and 2.5% difference between extensive, normal, and
#' intensive schemes
#' @export
#' @examples
#' perc_drop_fixed_25(10, step = seq(-3, 0, 1))
#' perc_drop_fixed_25(10, step = seq(-3, 0, 1), volume = "extensive")
#' perc_drop_fixed_25(5, step = seq(-3, 0, 1), type = "ballistic")
perc_drop_fixed_25 <- function(reps,
step = 0,
volume = "normal",
type = "grinding",
adjustment = 0,
func_max_perc_1RM = get_max_perc_1RM) {
params <- data.frame(
volume = c("intensive", "normal", "extensive", "intensive", "normal", "extensive"),
type = c("grinding", "grinding", "grinding", "ballistic", "ballistic", "ballistic"),
rep_start = c(0, -0.025, -0.05, 0, -0.025, -0.05),
rep_step = c(0, 0, 0, 0, 0, 0),
inc_start = c(-0.025, -0.025, -0.025, -0.025, -0.025, -0.025),
inc_step = c(0, 0, 0, 0, 0, 0)
)
params <- params[params$volume == volume, ]
params <- params[params$type == type, ]
perc_drop_generic(
reps = reps,
step = step,
rep_start = params$rep_start[1],
rep_step = params$rep_step[1],
inc_start = params$inc_start[1],
inc_step = params$inc_step[1],
adjustment = adjustment,
func_max_perc_1RM = func_max_perc_1RM,
type = type
)
}
#' @describeIn progression_table Generates progression tables
#' @param progression_table Progression table function to use. Default is
#' \code{\link{RIR_increment}}
#' @export
#' @examples
#' generate_progression_table()
#'
#' generate_progression_table(type = "grinding", volume = "normal")
#'
#' generate_progression_table(
#' reps = 1:5,
#' step = seq(-5, 0, 1),
#' type = "grinding",
#' volume = "normal"
#' )
generate_progression_table <- function(type = c("grinding", "ballistic"),
volume = c("intensive", "normal", "extensive"),
reps = 1:12,
step = seq(-3, 0, 1),
func_max_perc_1RM = get_max_perc_1RM,
progression_table = RIR_increment) {
params <- expand.grid(
type = type,
volume = volume,
reps = reps,
step = step,
stringsAsFactors = FALSE
)
val_adj <- numeric(nrow(params))
val_perc <- numeric(nrow(params))
for (i in seq_len(nrow(params))) {
val <- progression_table(
reps = params$reps[i],
step = params$step[i],
volume = params$volume[i],
type = params$type[i],
func_max_perc_1RM = func_max_perc_1RM
)
val_adj[i] <- val$adjustment
val_perc[i] <- val$perc_1RM
}
data.frame(
params,
adjustment = val_adj,
perc_1RM = val_perc)
}
|
7d3fbb5be8f83ad740100c083ca7e8d7f3878b89 | 83ba6ec557810c39d713f11c1e6a46bc22a24a0f | /tests/testthat/test-handle.R | 67b3460eb0f31f17f86f6b68cf434319f3d419de | [
"MIT"
] | permissive | paleolimbot/grd | 65ae5142eac0d339a8c150b64b81102ce8177b76 | d83e27d82b126e12649fbceb2830be80bffdae81 | refs/heads/master | 2023-08-22T02:05:21.121156 | 2021-10-16T00:04:59 | 2021-10-16T00:04:59 | 415,056,175 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,508 | r | test-handle.R |
test_that("wk_handle() works for grd_rct", {
expect_identical(
wk_handle(grd(nx = 1, ny = 1), wk::wkt_writer()),
wkt("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))")
)
})
test_that("wk_handle() works for grd_xy", {
expect_identical(
wk_handle(grd(nx = 1, ny = 1, type = "centers"), wk::wkt_writer()),
wkt("POINT (0.5 0.5)")
)
})
test_that("as_xy() works for grd objects", {
grid_empty <- grd(nx = 0, ny = 0)
expect_identical(as_xy(grid_empty), xy(crs = NULL))
grid1 <- grd(nx = 1, ny = 1)
expect_identical(as_xy(grid1), xy(0.5, 0.5))
data <- matrix(0:5, nrow = 2, ncol = 3)
grid <- grd_xy(data)
# order should match the internal ordering of data
# (column major unless specified)
expect_identical(
as_xy(grd_xy(data)),
c(
xy(0, 1),
xy(0, 0),
xy(1, 1),
xy(1, 0),
xy(2, 1),
xy(2, 0)
)
)
# order should still be top left -> bottom right
# even with flipped initial bbox
expect_identical(
as_xy(grd_xy(data, rct(0, 0, -2, -1))),
c(
xy(-2, 0),
xy(-2, -1),
xy(-1, 0),
xy(-1, -1),
xy(0, 0),
xy(0, -1)
)
)
expect_identical(as_xy(as_grd_rct(grid)), as_xy(grid))
})
test_that("as_xy() works for row-major grd objects", {
grid_empty <- grd(nx = 0, ny = 0)
attr(grid_empty$data, "grd_data_order") <- c("x", "y")
expect_identical(as_xy(grid_empty), xy(crs = NULL))
data <- matrix(0:5, nrow = 2, ncol = 3)
grid <- grd_xy(data)
attr(grid$data, "grd_data_order") <- c("x", "y")
expect_identical(
as_xy(grid),
c(
xy(0, 1),
xy(1, 1),
xy(2, 1),
xy(0, 0),
xy(1, 0),
xy(2, 0)
)
)
expect_identical(as_xy(as_grd_rct(grid)), as_xy(grid))
})
test_that("as_xy() works for flipped grd objects", {
data <- matrix(0:5, nrow = 2, ncol = 3)
grid <- grd_xy(data)
attr(grid$data, "grd_data_order") <- c("-y", "-x")
expect_identical(
as_xy(grid),
c(
xy(2, 0),
xy(2, 1),
xy(1, 0),
xy(1, 1),
xy(0, 0),
xy(0, 1)
)
)
attr(grid$data, "grd_data_order") <- c("-x", "-y")
expect_identical(
as_xy(grid),
c(
xy(2, 0),
xy(1, 0),
xy(0, 0),
xy(2, 1),
xy(1, 1),
xy(0, 1)
)
)
})
test_that("as_rct() works for grd objects", {
grid_empty <- grd(nx = 0, ny = 0)
expect_identical(as_rct(grid_empty), rct(crs = NULL))
data <- matrix(0:5, nrow = 2, ncol = 3)
grid <- grd_rct(data)
# order should match the internal ordering of data
# (column major unless specified)
expect_identical(
as_rct(grid),
c(
rct(0, 1, 1, 2),
rct(0, 0, 1, 1),
rct(1, 1, 2, 2),
rct(1, 0, 2, 1),
rct(2, 1, 3, 2),
rct(2, 0, 3, 1)
)
)
expect_identical(
as_rct(grd_rct(data, rct(0, 0, -3, -2))),
c(
rct(-3, -1, -2, 0),
rct(-3, -2, -2, -1),
rct(-2, -1, -1, 0),
rct(-2, -2, -1, -1),
rct(-1, -1, 0, 0),
rct(-1, -2, 0, -1)
)
)
expect_identical(as_rct(as_grd_xy(grid)), as_rct(grid))
})
test_that("as_rct() works for row-major grd objects", {
grid_empty <- grd(nx = 0, ny = 0)
attr(grid_empty$data, "grd_data_order") <- c("x", "y")
expect_identical(as_rct(grid_empty), rct(crs = NULL))
data <- matrix(0:5, nrow = 2, ncol = 3)
grid <- grd_rct(data)
attr(grid$data, "grd_data_order") <- c("x", "y")
# order should match the internal ordering of data
# (row major unless specified)
expect_identical(
as_rct(grid),
c(
rct(0, 1, 1, 2),
rct(1, 1, 2, 2),
rct(2, 1, 3, 2),
rct(0, 0, 1, 1),
rct(1, 0, 2, 1),
rct(2, 0, 3, 1)
)
)
expect_identical(as_rct(as_grd_xy(grid)), as_rct(grid))
})
test_that("as_rct() works for flipped grd objects", {
data <- matrix(0:5, nrow = 2, ncol = 3)
grid <- grd_rct(data)
attr(grid$data, "grd_data_order") <- c("-y", "-x")
# order should match the internal ordering of data
# (row major unless specified)
expect_identical(
as_rct(grid),
c(
rct(2, 0, 3, 1),
rct(2, 1, 3, 2),
rct(1, 0, 2, 1),
rct(1, 1, 2, 2),
rct(0, 0, 1, 1),
rct(0, 1, 1, 2)
)
)
attr(grid$data, "grd_data_order") <- c("-x", "-y")
# order should match the internal ordering of data
# (row major unless specified)
expect_identical(
as_rct(grid),
c(
rct(2, 0, 3, 1),
rct(1, 0, 2, 1),
rct(0, 0, 1, 1),
rct(2, 1, 3, 2),
rct(1, 1, 2, 2),
rct(0, 1, 1, 2)
)
)
})
|
4f5e61d208582844b606627037460c01f5a69476 | b2f61fde194bfcb362b2266da124138efd27d867 | /code/dcnf-ankit-optimized/Results/QBFLIB-2018/A1/Database/Kronegger-Pfandler-Pichler/dungeon/dungeon_i10-m5-u10-v0.pddl_planlen=23/dungeon_i10-m5-u10-v0.pddl_planlen=23.R | a76024434b69f620cbbd72f48585e2ef4682c528 | [] | no_license | arey0pushpa/dcnf-autarky | e95fddba85c035e8b229f5fe9ac540b692a4d5c0 | a6c9a52236af11d7f7e165a4b25b32c538da1c98 | refs/heads/master | 2021-06-09T00:56:32.937250 | 2021-02-19T15:15:23 | 2021-02-19T15:15:23 | 136,440,042 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 89 | r | dungeon_i10-m5-u10-v0.pddl_planlen=23.R | 85f810d7c745dc152af008ed46786529 dungeon_i10-m5-u10-v0.pddl_planlen=23.qdimacs 4915 12944 |
7009161d9dd65a272bc80af2aaa6370748686568 | 35c741fe1331be9fd2214c7b2cc3e5bcaddba833 | /simmen/man/SNF.Rd | 87d854b617903d8a254469fb812823a52ba58ed9 | [] | no_license | ctszkin/simmen | 717d73f06572ee3cc78fb82670966098b61fa330 | 3a08eae0a3385f2b810991cff575d19722302289 | refs/heads/master | 2020-05-17T05:44:58.805273 | 2014-06-17T11:04:11 | 2014-06-17T11:04:11 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 809 | rd | SNF.Rd | % Generated by roxygen2 (4.0.1): do not edit by hand
\name{SNF}
\alias{SNF}
\alias{SNF.dynamic.mcmc}
\alias{SNF.static.maxLik}
\alias{SNF.static.mcmc}
\title{SNF}
\usage{
SNF(data, method = c("static.maxLik", "static.mcmc", "dynamic.mcmc"), ...)
SNF.static.maxLik(data, ...)
SNF.static.mcmc(data, m = 1000, last_estimation, ...)
SNF.dynamic.mcmc(m, data, last_estimation, update_tau = TRUE, tau = 0.005)
}
\arguments{
\item{data}{data}
\item{method}{Estimation method, either "static.maxLik","static.mcmc","dynamic.mcmc". Default is "static.maxLik"}
\item{m}{m}
\item{last_estimation}{last_estimation}
\item{update_tau}{update_tau}
\item{tau}{tau}
\item{...}{others argument.}
}
\value{
SNF object
}
\description{
Strategy Network Formation
}
\author{
TszKin Julian Chan \email{ctszkin@gmail.com}
}
|
abca92736c4f0173417e62014841930ee42464c6 | df0f07dfc35171966e0e481bad72596ca8a80a06 | /run_analysis.R | e4a5858fe603ad43f5cb5bc30f95134479b4d9ab | [] | no_license | aniketks/cleaningDataAssignment | 883f527f45a91a4b28c45a7c9ba0b2d2e87b886b | 1c920289c8c3d4e135cd8456e63c2b34ec8a3e71 | refs/heads/master | 2020-04-01T19:22:37.229017 | 2018-10-18T02:40:02 | 2018-10-18T02:40:02 | 153,550,472 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 5,722 | r | run_analysis.R | library(dplyr)
library(plyr)
###1:Merges the training and the test sets to create one data set.
#Dowload files
download.file('https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip',
'/Users/aniketkumar/Downloads/zip.zip')
#Unzip the file and store in folder 'data'
unzip(zipfile = '/Users/aniketkumar/Downloads/zip.zip', exdir = '/Users/aniketkumar/Downloads/')
###Create a dataframe for 'test'
##Subjects data frame
subjectsTest <- read.csv('/Users/aniketkumar/Downloads/UCI HAR Dataset/test/subject_test.txt',
header = FALSE, sep = "")
colnames(subjectsTest) <- c('subject')
##X_test dataframe
x_test <- read.csv('/Users/aniketkumar/Downloads/UCI HAR Dataset/test/X_test.txt',
header = FALSE, sep = "")
#Get feature names
features <- read.csv('/Users/aniketkumar/Downloads/UCI HAR Dataset/features.txt',
header = FALSE, sep = "")
#Extract feature names and place them in vector to rename columns for x_test
feature_vector <- features$V2
colnames(x_test) <- feature_vector
##Y-test dataframe
y_test <- read.csv('/Users/aniketkumar/Downloads/UCI HAR Dataset/test/Y_test.txt',
header = FALSE, sep = "")
colnames(y_test) <- c('label')
##Combine all of these using cbind to create test_df
test_df <- cbind(subjectsTest, x_test, y_test)
##Remove the unneeded dataframes
rm(features, subjectsTest, x_test, y_test)
##Similarly, create dataset for train
#Subject dataframe
subjectsTrain <- read.csv('/Users/aniketkumar/Downloads/UCI HAR Dataset/train/subject_train.txt',
header = FALSE, sep = "")
colnames(subjectsTrain) <- c('subject')
#X-train dataframe
x_train <- read.csv('/Users/aniketkumar/Downloads/UCI HAR Dataset/train/X_train.txt', header = FALSE, sep = "")
colnames(x_train) <- feature_vector
#Y-train dataset
y_train <- read.csv('/Users/aniketkumar/Downloads/UCI HAR Dataset/train/Y_train.txt', header = FALSE, sep = "")
colnames(y_train) <- c('label')
#Combine all of these using cbind to create train_df
train_df <- cbind(subjectsTrain, x_train, y_train)
#Remove the unneeded dataframes
rm(feature_vector, subjectsTrain, x_train, y_train)
#Create one dataset mergin test_df on train_df
final_df <- rbind(test_df, train_df)
#Remove unused datasets
rm(test_df, train_df)
###2.Extracts only the measurements on the mean and standard deviation for each measurement
colInd <- append(grep("mean|std", colnames(final_df)), c(1, 563))
final_df1 <- final_df[,colInd]
remColInd <- grep(pattern = "^((?!Freq).)*$", colnames(final_df1), perl = T)
final_df1 <- final_df1[,remColInd]
final_df <- final_df1
rm(colInd, remColInd, final_df1)
###3. Uses descriptive activity names to name the activities in the data set
activityLab <- read.csv('/Users/aniketkumar/Downloads/UCI HAR Dataset/activity_labels.txt',
header = FALSE, sep = "")
final_df1 <- merge(x = final_df, y = activityLab, by.x = 'label', by.y = 'V1')
final_df <- final_df1
rm(final_df1, activityLab)
final_df <- final_df[,-1]
###4. Appropriately labels the data set with descriptive variable names.
namesColFin <- c("bodyAccel_mean_X", "bodyAccel_mean_Y", "bodyAccel_mean_Z",
"bodyAccel_std_X", "bodyAccel_std_Y", "bodyAccel_std_Z",
"gravityAccel_mean_X", "gravityAccel_mean_Y", "gravityAccel_mean_Z",
"gravityAccel_std_X", "gravityAccel_std_Y", "gravityAccel_std_Z",
"bodyAccelJerk_mean_X", "bodyAccelJerk_mean_Y", "bodyAccelJerk_mean_Z",
"bodyAccelJerk_std_X", "bodyAccelJerk_std_Y", "bodyAccelJerk_std_Z",
"bodyGyro_mean_X", "bodyGyro_mean_Y", "bodyGyro_mean_Z",
"bodyGyro_std_X", "bodyGyro_std_Y", "bodyGyro_std_Z",
"bodyGyromJerk_mean_X", "bodyGyromJerk_mean_Y", "bodyGyromJerk_mean_Z",
"bodyGyromJerk_std_X", "bodyGyromJerk_std_Y", "bodyGyromJerk_std_Z",
"bodyAccelMagn_mean", "bodyAccelMagn_std", "gravityAccelMagn_mean",
"gravityAccelMagn_std", "bodyAccelJerkMagn_mean", "bodyAccelJerkMagn_std",
"bodyGyroMagn_mean", "bodyGyroMagn_std", "bodyGyroJerkMagn_mean",
"bodyGyroJerkMagn_std", "freqBodyAccel_mean_X", "freqBodyAccel_mean_Y",
"freqBodyAccel_mean_Z", "freqBodyAccel_std_X", "freqBodyAccel_std_Y",
"freqBodyAccel_std_Z", "freqBodyAccelJerk_mean_X", "freqBodyAccelJerk_mean_Y",
"freqBodyAccelJerk_mean_Z", "freqBodyAccelJerk_std_X", "freqBodyAccelJerk_std_Y",
"freqBodyAccelJerk_std_Z", "freqBodyGyro_mean_X", "freqBodyGyro_mean_Y",
"freqBodyGyro_mean_Z", "freqBodyGyro_std_X", "freqBodyGyro_std_Y",
"freqBodyGyro_std_Z", "freqBodyAccelMagn_mean", "freqBodyAccelMagn_std",
"freqBodyAccJerkMagn_mean", "freqBodyAccJerkMagn_std", "freqBodyGyroMagn_mean",
"freqBodyGyroMagn_std", "freqBodyGyroJerkMagn_mean", "freqBodyGyroJerkMagn_std",
"subject", "activity")
colnames(final_df) <- namesColFin
rm(namesColFin)
###5. From the data set in step 4, creates a second, independent tidy data set
### with the average of each variable for each activity and each subject.
final_df_summ <- aggregate(final_df, by = list(final_df$activity, final_df$subject), FUN = mean)
final_df_summ <- final_df_summ[,-c(69, 70)]
final_df_summ <- rename(x = final_df_summ, replace = c('Group.1' = 'activity', 'Group.2' = 'subject'))
|
c53d7a211c6e8c577fb41b0e3fc69b90bf499080 | db459f039af619335e884887a143fce550d884f5 | /baseline-spon.R | e099522244ee00678c538bc68091b4ba66b2d661 | [] | no_license | cx749/Thesis-statistic-in-R | d39dde0ea8a6edd3a2f71dd66ce8fbe0167869c5 | fc7f08c44ce55d6f60150b8be38264aefcfe3004 | refs/heads/master | 2020-04-17T17:23:25.332031 | 2019-01-21T09:10:18 | 2019-01-21T09:10:18 | 166,780,447 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,488 | r | baseline-spon.R | .libPaths("O:/paths") #set library path
library(tidyverse)
library(ggpubr)
library(ggsignif)
#import csv file of results
baseline <- read_csv("raw_baseline-spon.csv")
baseline <- baseline %>%
mutate(age = as.factor(age))
#create default boxplot function
default.single.boxplot <- list(geom_boxplot(aes(fill = age)),
# geom_point(aes(colour = age)),
theme(plot.title = element_text(size=11, face='bold',hjust=0.5),
axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)),
axis.title.x = element_text(margin = margin(t = 20, r = 0, b = 0, l = 0)),
axis.title = element_text(size=24, face='bold'),
axis.text = element_text(size=20, face='bold', color = 'black'),
plot.margin = unit(c(1,0,1,0), "cm"),
panel.spacing = unit(0, "lines"),
panel.border = element_blank(),
panel.background = element_rect(fill = "white"),
panel.grid.major.y = element_line(size = 0.5, linetype = 'solid',colour = "grey"),
legend.position = 'none'),
scale_fill_brewer(palette='Set1'))
#raw basleines (spon) - whole cortex
ggplot(baseline, aes(age,raw_baseline)) +
default.single.boxplot +
scale_y_continuous(limits = c(0, NA)) +
labs(x = 'Postnatal day', y = 'Baseline fluorescence')
#+
# stat_compare_means(label = 'p.signif', comparisons = list(c('1', '5')), face = 'bold')
ggsave("raw_baseline-spon.png", width = 15, height = 15, units = "cm")
shapiro.test(baseline$raw_baseline)
a <- aov(raw_baseline~age, data = baseline)
summary(a)
TukeyHSD(a)
#raw basleines (spon) - barrel
ggplot(baseline, aes(age,barrel_baselines)) +
default.single.boxplot +
scale_y_continuous(limits = c(0, NA)) +
labs(x = 'Postnatal day', y = 'Baseline fluorescence')
#+
# stat_compare_means(label = 'p.signif', comparisons = list(c('1', '5')), face = 'bold')
ggsave("raw_barrel-baseline-spon.png", width = 15, height = 15, units = "cm")
shapiro.test(baseline$barrel_baselines)
a <- aov(barrel_baselines~age, data = baseline)
summary(a)
TukeyHSD(a)
|
5e1063042181f57d617a6b6732336e588e3e5722 | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/Morpho/R/plot.normals.r | 8074c6f1218dbd8a5891f78ad6dd8fe172d222b6 | [] | 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,600 | r | plot.normals.r | #' plots the normals of a triangular surface mesh.
#'
#' visualises the vertex normals of a triangular surface mesh of class mesh3d.
#' If no normals are contained, they are computed.
#'
#'
#' @param x object of class "mesh3d"
#' @param length either a single numeric value or a numeric vector defining per-normals lenght (default is 1)
#' @param lwd width of the normals
#' @param col color of the normals
#' @param ... addtional parameters, currently not in use.
#' @author Stefan Schlager
#'
#' @examples
#'
#' \dontrun{
#' require(rgl)
#' data(nose)
#' plotNormals(shortnose.mesh,col=4,long=0.01)
#' shade3d(shortnose.mesh,col=3)
#' }
#'
#' @export
plotNormals <- function(x,length=1,lwd=1,col=1,...) {
if ( ! "mesh3d" %in% class(x))
stop("please provide object of class mesh3d")
args <- list(...)
print(args)
if("long" %in% names(args)) {
length <- args$long
warning("argument 'long' is deprecated, please use 'length' instead")
}
if (is.null(x$normals)) {
if (!is.null(x$it))
x <- vcgUpdateNormals(x)
else
stop("mesh has neither normals nor faces")
}
n.mesh <- list()
lvb <- dim(x$vb)[2]
vb <- x$vb
vb.norm <- vb[1:3,,drop=FALSE]+t(length*t(x$normals[1:3,,drop=FALSE]))
vb <- cbind(vb[1:3,,drop=FALSE],vb.norm)
vb <- rbind(vb,1)
it <- rbind(1:lvb,1:lvb,(1:lvb)+lvb)
n.mesh$vb <- vb
n.mesh$it <- it
class(n.mesh) <- c("mesh3d","shape3d")
# n.mesh$primitivetype <- "triangle"
wire3d(n.mesh,color=col,lwd=lwd,lit=FALSE)
}
|
4075c4df21d3ebfe8876b814cd0befb2acbb64fd | b92ecd58bdcb74bcadb9b4050de8314352c80d71 | /data/popMT.R | a105b807fa0193defb48c4089eb7036cbfcdd503 | [] | no_license | cran/wpp2017 | 2fb52509372d113a7958429778fadc429e9e5b22 | 391e4b09a612b5f6c583ad282080fa2182993175 | refs/heads/master | 2020-12-03T05:11:27.249976 | 2020-02-10T05:10:02 | 2020-02-10T05:10:02 | 95,742,096 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 701 | r | popMT.R | # Total male population (observed)
# This dataset is created on the fly as a sum of the age-specific population estimates popM
popMT <- local({
source('popM.R')
#suppressPackageStartupMessages(library(data.table))
sum.by.country <- function(dataset) {
year.cols <- grep('^[0-9]{4}', colnames(dataset), value = TRUE)
name.col <- grep('^name$|^country$', colnames(dataset), value=TRUE)
data.table::setnames(dataset, name.col, "name") # rename if necessary
dataset[, c("country_code", "name", year.cols),
with = FALSE][,lapply(.SD, sum, na.rm = TRUE),
by = c("country_code", "name")]
}
as.data.frame(sum.by.country(data.table::as.data.table(popM)))
}) |
978463728b3f4f2e90e3f0b83e350929b59e0a6f | ce8ec3a112edfb9865f04c321261da5aac2f9082 | /man/kth.Rd | 51ac5171ba7f7db57676fd238fab24affff81ccc | [
"MIT"
] | permissive | DrRoad/mapsRinteractive | 14c7c01756bcd4a4dcf74af3bdb7b0448db92cef | 5ac39688187556379ae58cf419a4015d3c1f2654 | refs/heads/master | 2022-04-10T09:24:25.159197 | 2020-03-05T19:28:57 | 2020-03-05T19:28:57 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,586 | rd | kth.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/kth.R
\name{kth}
\alias{kth}
\title{kth}
\usage{
kth(x = NULL, k = 2, highest = TRUE, index = FALSE,
unique = FALSE, multiple = FALSE)
}
\arguments{
\item{x}{Numeric vector.}
\item{k}{Positive integer. The order of the value to find. Default = 2,
which means that the next highest/lowest values is identified.}
\item{highest}{Logical. TRUE means that the kth highest value(s) is/are
identified. FALSE means that the kth lowest value(s) is/are identified.
Default = TRUE.}
\item{index}{Logical. TRUE means that the index/indices of the kth highest/lowest
value(s) is/are returned. FALSE means that the kth highest/lowest value
itself is returned. If ties exist and argument multiple = TRUE, the returned value is a vector, else
it is a value. Default=FALSE.}
\item{unique}{Logical. TRUE means that duplicates are removed before the
identification of the kth highest/lowest value(s). Default=FALSE}
\item{multiple}{Logical. TRUE means that, If ties exist a vector of
all values in x that are equal to the kth highest/lowest values is returned.
FALSE means that one random value from the vector of index values is
returned. Default=FALSE}
}
\value{
If index = FALSE: the kth highest/lowest value is returned.
If index = TRUE: the index of the kth highest/lowest value (s) is/are
returned.
}
\description{
Identification of the kth highest/lowest value(s).
}
\details{
NA values are removed.
}
\examples{
kth(x=1:20, k=3, highest=FALSE)
}
|
ae21c2f2a3b01d2a68896182d0898c1524d40a9d | fa6240c6abdee96162077168aab4c5dba78fa46f | /man/predict.hierNet.logistic.Rd | a96c4c0aac42049d60601a256d3b187670b827eb | [] | no_license | cran/hierNet | da43557ed794998e74d5be0f6f5535171cdf26b5 | e9b755972191f85113df8f60aaddcd9b394e009e | refs/heads/master | 2021-01-21T12:35:51.742237 | 2020-02-05T12:10:20 | 2020-02-05T12:10:20 | 17,696,644 | 4 | 1 | null | null | null | null | UTF-8 | R | false | false | 1,560 | rd | predict.hierNet.logistic.Rd | \name{predict.hierNet.logistic}
\alias{predict.hierNet.logistic}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{Prediction function for hierNet.logistic.}
\description{
A function to perform prediction, using an x matrix and the output of
the "hierNet.logistic" function or "hierNet.logistic.path".
}
\usage{
\method{predict}{hierNet.logistic}(object, newx, newzz=NULL,...)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{object}{The results of a call to the "hierNet.logistic" or "hierNet.logistic.path" or
function. The
coefficients that are part of this object will be used for
making predictions.}
\item{newx}{The new x at which predictions should be made. Can be a
vector
or a matrix (one observation per row).}
\item{newzz}{Optional matrix of products of columns of newx, computed by compute.interactions.c}
\item{...}{additional arguments (not currently used)}
}
\value{
\item{yhat}{Matrix of predictions (probabilities), one row per observation}
}
\references{Bien, J., Taylor, J., Tibshirani, R., (2013) "A Lasso for Hierarchical Interactions." Annals of Statistics. 41(3). 1111-1141.}
\author{Jacob Bien and Robert Tibshirani}
\seealso{\link{hierNet.logistic}, \link{hierNet.logistic.path} }
\examples{
set.seed(12)
x=matrix(rnorm(100*10),ncol=10)
x=scale(x,TRUE,TRUE)
y=x[,1]+2*x[,2]+ x[,1]*x[,2]+3*rnorm(100)
y=1*(y>0)
newx=matrix(rnorm(100*10),ncol=10)
fit=hierNet.logistic(x,y,lam=5)
yhat=predict(fit,newx)
fit=hierNet.logistic.path(x,y)
yhat=predict(fit,newx)
}
|
c67a82fc8dc9d42cc667580a05fad9e2c6a6fb70 | b946f5bea65aa485a7b70d8a83ba5a0a9815cdd1 | /prep_discharge_loc_gis.R | e4d502f41d2a2068ec22f11bb33913a5eb8f9eef | [] | no_license | mgayte/Scripts | 741fb0b98ccb7b16cc72e00af20bdfc2a9c32ad6 | c20da91d665334c98b4ec83dc03f8bf02d3325b0 | refs/heads/main | 2023-03-13T16:44:22.751903 | 2021-03-05T03:32:29 | 2021-03-05T03:32:29 | 344,633,897 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,601 | r | prep_discharge_loc_gis.R | #############################################
# #
# Prep discharge data #
# for #
# map arcgis #
# #
#############################################
#Read discharge table and delete rainfall stations
discharge_table <- read.csv("C:/Users/mgayt/Documents/Rainfall_peakflow_project/Discharge_information/Discharge_stations.csv", header = T)
discharge_table <- discharge_table[-c(162:189),]
##Get stations with only data from 2000-01-01 to 2019-12-31 and with at least three years of data---------------
#Change format of start end end dates to date format
discharge_table$start_date <- as.Date(discharge_table$start_date, format = "%m/%d/%Y")
discharge_table$end_date <- as.Date(discharge_table$end_date, format = "%m/%d/%Y")
#Stations with data for three years at least
discharge_table <- discharge_table[discharge_table$length_date >= 365*3,]
#Stations with end date later than 12-31-2003 (at least three years after 2000)
discharge_table <- discharge_table[!is.na(discharge_table$length_date),]
discharge_table <- discharge_table[discharge_table$end_date >= "2003-12-31",]
##END OF get stations with only data from 2000-01-01 to 2019-12-31 and with at least three years of data-----------------------
#Export the table to use in gis
write.csv(discharge_table, "C:/Users/mgayt/Documents/Rainfall_peakflow_project/Discharge_information/2000_discharge_stations.csv", row.names = F)
|
4268892f887e6d2eeab8a85f4e55307f402a1f5b | 0a90eb1dcd39493a432098a6ff58f97231ef75d1 | /funcionesAmpliaQueries.R | 1edc45136970ad4e03bae1d5249fce9b63131cab | [] | no_license | FerDoranNie/geodataLimpiezaSismo | b426162b08b30958cc3ce4cbe2a6589599f10442 | 3295b44ed620eded5e912f6cbca149dd08766678 | refs/heads/master | 2021-07-04T19:07:30.194507 | 2017-09-25T23:11:24 | 2017-09-25T23:11:24 | 104,497,405 | 3 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,801 | r | funcionesAmpliaQueries.R | library(RJSONIO)
library(RCurl)
source("api_key.R")
urlRev <- "https://maps.googleapis.com/maps/api/geocode/json?latlng="
getGeoData <- function(location){
location <- gsub(' ','+',location)
geo_data <- getURL(paste("https://maps.googleapis.com/maps/api/geocode/json?address=",
location,"&key=", api_key,
sep=""))
raw_data_2 <- fromJSON(geo_data)
return(raw_data_2)
}
# getGeoDataReversa <- function(latitud, longitud){
# latitud <- as.numeric(latitud)
# longitud <- as.numeric(longitud)
# reversa <- getURL(paste(urlRev, latitud, ",", longitud, "&key=", api_key,
# sep=""))
#
# data <- fromJSON(reversa)
# data <- data$results[[1]]
# x <- data
# direccion <- as.character(x$formatted_address)
# numero <- as.character(x$address_components[[1]]$long_name)
# calle <- as.character(x$address_components[[2]]$long_name)
# cp <- tryCatch(as.character(x$address_components[[9]]$long_name),
# error=function(e){character(0)})
# colonia <- as.character(x$address_components[[3]]$long_name)
# ciudad <- as.character(x$address_components[[6]]$long_name)
# estado <- as.character(x$address_components[[7]]$long_name)
# pais <- tryCatch(as.character(x$address_components[[8]]$long_name),
# error=function(e){character(0)})
#
# direccion <- ifelse(identical(direccion, character(0)), NA, direccion)
# calle <- ifelse(identical(calle, character(0)), NA, calle)
# numero <- ifelse(identical(numero, character(0)), NA, numero)
# cp <- ifelse(identical(cp, character(0)), NA, cp)
# colonia <- ifelse(identical(colonia, character(0)), NA, colonia)
# ciudad <- ifelse(identical(ciudad, character(0)), NA, ciudad)
# estado <- ifelse(identical(estado, character(0)), NA, estado)
# pais <- ifelse(identical(pais, character(0)), NA, pais)
# X <- data.frame(direccion, calle, numero, colonia, cp,
# ciudad_municipio= ciudad, estado, pais,
# lat = latitud, long= longitud )
# nombres <- names(X)
# nombres <- sapply(nombres, paste, "_", "Verificado", sep="")
# names(X) <- nombres
# print(paste(urlRev, latitud,",", longitud, "&key=", api_key,
# sep=""))
# print(c(latitud, longitud))
# return(X)
# }
getGeoDataReversa <- function(latitud, longitud){
latitud <- as.numeric(latitud)
longitud <- as.numeric(longitud)
reversa <- getURL(paste(urlRev, latitud, ",", longitud, "&key=", api_key,
sep=""))
data <- fromJSON(reversa)
data <- data$results[[1]]
direcciones <- data$address_components
direccion <- lapply(1:length(direcciones), function(d){
z <- direcciones[[d]]
z <- unlist(z)
z <- z[1:3]
x <- names(z)
y <- unname(z)
x <- gsub("[0-9]", "", x)
y <- data.frame(y[1], y[2], y[3])
names(y) <- x
return(y)
}) %>%
do.call("rbind", .) %>%
data.frame
dir <- as.character(data$formatted_address)
dir <- ifelse(identical(dir, character(0)), NA, dir)
print(class(direccion))
print(c(latitud, longitud))
cp <- as.character(direccion[direccion$types=="postal_code",]$long_name)
cp <- ifelse(identical(cp, character(0)), NA, cp)
calle <- as.character(direccion[direccion$types=="route",]$long_name)
calle <- ifelse(identical(calle, character(0)), NA, calle)
numero <- as.character(direccion[direccion$types=="street_number",]$long_name)
numero <- ifelse(identical(numero, character(0)), NA, numero)
colonia <- as.character(direccion[direccion$types=="political",]$long_name)
colonia <- ifelse(identical(colonia, character(0)), NA, colonia)
ciudad <- as.character(direccion[direccion$types=="locality",]$long_name)
ciudad <- ifelse(identical(ciudad, character(0)), NA, ciudad)
estado <- as.character(direccion[direccion$types=="administrative_area_level_1",]$long_name)
estado <- ifelse(identical(estado, character(0)), NA, estado)
pais <- as.character(direccion[direccion$types=="country",]$long_name)
pais <- ifelse(identical(pais, character(0)), NA, pais)
X <- data.frame(direccion = dir, calle, numero, colonia, cp,
ciudad_municipio= ciudad, estado, pais,
lat = latitud, long= longitud )
X[X=="integer(0)"]<- NA
# for(i in 1:length(direcciones)){
# # postal_code <- route <- NULL
# z <- direcciones[[i]]
# z <- unlist(z)
# z <- z[1:3]
# x <- names(z)
# y <- unname(z)
# x <- gsub("[0-9]", "", x)
# y <- (rbind(x,y))
# print(y)
#
# }
nombres <- names(X)
nombres <- sapply(nombres, paste, "_", "Verificado", sep="")
names(X) <- nombres
return(X)
}
.contadorQueries <- 0
trace(getGeoDataReversa,
tracer=function() .contadorQueries<<- .contadorQueries+1)
|
8d3ed54eb159b478a12dbfc171a638aaf480901a | 0e16e28b012e001afa50498e97ad3bcf4e370b5e | /MLR.R | 54b8256386197240a43b6f95a64a30e035218e0b | [] | no_license | lucci-leo/Carl-De-Leo | 1f125e31233e7640c0443005640ba60ebae650c3 | 001ba9c7eee0edb1d982865c9c6c1829d4307863 | refs/heads/master | 2021-01-11T02:08:45.066303 | 2016-11-01T07:37:26 | 2016-11-01T07:37:26 | 70,827,446 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 6,143 | r | MLR.R | ## Question 3:
## Install Bioconductor
source("https://bioconductor.org/biocLite.R")
biocLite()## Question 1: Done online
## Install DNAshapeR
biocLite("DNAshapeR")
## Install Caret
install.packages("caret")
## Question 4: Included in the Code Below
## Initialization
library(DNAshapeR)
library(caret)
workingPath <- "/Users/Carl/Desktop/BISC481m/gcPBM/"
## Predict DNA shapes Using DNAshapeR (Mad: 1-mer+shape)
fn_fasta <- paste0(workingPath, "Mad.txt.fa")
pred <- getShape(fn_fasta)
## Encode feature vectors
featureType <- c("1-mer", "1-shape")
featureVector <- encodeSeqShape(fn_fasta, pred, featureType)
head(featureVector)
## Build MLR model by using Caret
## Data preparation
fn_exp <- paste0(workingPath, "Mad.txt")
exp_data <- read.table(fn_exp)
df <- data.frame(affinity=exp_data$V2, featureVector)
## Arguments setting for Caret
trainControl <- trainControl(method = "cv", number = 10, savePredictions = TRUE)
## Prediction without L2-regularized
model <- train (affinity~ ., data = df, trControl=trainControl,
method = "lm", preProcess=NULL)
summary(model)
## Prediction with L2-regularized
model2 <- train(affinity~., data = df, trControl=trainControl,
method = "glmnet", tuneGrid = data.frame(alpha = 0, lambda = c(2^c(-15:15))))
model2
result <- model2$results$Rsquared[1]
## Predict DNA shapes Using DNAshapeR (Mad: 1-mer)
fn_fasta <- paste0(workingPath, "Mad.txt.fa")
pred <- getShape(fn_fasta)
## Encode feature vectors
featureType <- c("1-mer")
featureVector <- encodeSeqShape(fn_fasta, pred, featureType)
head(featureVector)
## Build MLR model by using Caret
## Data preparation
fn_exp <- paste0(workingPath, "Mad.txt")
exp_data <- read.table(fn_exp)
df <- data.frame(affinity=exp_data$V2, featureVector)
## Arguments setting for Caret
trainControl <- trainControl(method = "cv", number = 10, savePredictions = TRUE)
## Prediction without L2-regularized
model <- train (affinity~ ., data = df, trControl=trainControl,
method = "lm", preProcess=NULL)
summary(model)
## Prediction with L2-regularized
model2 <- train(affinity~., data = df, trControl=trainControl,
method = "glmnet", tuneGrid = data.frame(alpha = 0, lambda = c(2^c(-15:15))))
model2
result <- model2$results$Rsquared[1]
## Predict DNA shapes Using DNAshapeR (Max: 1-mer+shape)
fn_fasta <- paste0(workingPath, "Max.txt.fa")
pred <- getShape(fn_fasta)
## Encode feature vectors
featureType <- c("1-mer", "1-shape")
featureVector <- encodeSeqShape(fn_fasta, pred, featureType)
head(featureVector)
## Build MLR model by using Caret
## Data preparation
fn_exp <- paste0(workingPath, "Max.txt")
exp_data <- read.table(fn_exp)
df <- data.frame(affinity=exp_data$V2, featureVector)
## Arguments setting for Caret
trainControl <- trainControl(method = "cv", number = 10, savePredictions = TRUE)
## Prediction without L2-regularized
model <- train (affinity~ ., data = df, trControl=trainControl,
method = "lm", preProcess=NULL)
summary(model)
## Prediction with L2-regularized
model2 <- train(affinity~., data = df, trControl=trainControl,
method = "glmnet", tuneGrid = data.frame(alpha = 0, lambda = c(2^c(-15:15))))
model2
result <- model2$results$Rsquared[1]
## Predict DNA shapes Using DNAshapeR (Max: 1-mer)
fn_fasta <- paste0(workingPath, "Max.txt.fa")
pred <- getShape(fn_fasta)
## Encode feature vectors
featureType <- c("1-mer")
featureVector <- encodeSeqShape(fn_fasta, pred, featureType)
head(featureVector)
## Build MLR model by using Caret
## Data preparation
fn_exp <- paste0(workingPath, "Max.txt")
exp_data <- read.table(fn_exp)
df <- data.frame(affinity=exp_data$V2, featureVector)
## Arguments setting for Caret
trainControl <- trainControl(method = "cv", number = 10, savePredictions = TRUE)
## Prediction without L2-regularized
model <- train (affinity~ ., data = df, trControl=trainControl,
method = "lm", preProcess=NULL)
summary(model)
## Prediction with L2-regularized
model2 <- train(affinity~., data = df, trControl=trainControl,
method = "glmnet", tuneGrid = data.frame(alpha = 0, lambda = c(2^c(-15:15))))
model2
result <- model2$results$Rsquared[1]
## Predict DNA shapes Using DNAshapeR (Myc: 1-mer+shape)
fn_fasta <- paste0(workingPath, "Myc.txt.fa")
pred <- getShape(fn_fasta)
## Encode feature vectors
featureType <- c("1-mer", "1-shape")
featureVector <- encodeSeqShape(fn_fasta, pred, featureType)
head(featureVector)
## Build MLR model by using Caret
## Data preparation
fn_exp <- paste0(workingPath, "Myc.txt")
exp_data <- read.table(fn_exp)
df <- data.frame(affinity=exp_data$V2, featureVector)
## Arguments setting for Caret
trainControl <- trainControl(method = "cv", number = 10, savePredictions = TRUE)
## Prediction without L2-regularized
model <- train (affinity~ ., data = df, trControl=trainControl,
method = "lm", preProcess=NULL)
summary(model)
## Prediction with L2-regularized
model2 <- train(affinity~., data = df, trControl=trainControl,
method = "glmnet", tuneGrid = data.frame(alpha = 0, lambda = c(2^c(-15:15))))
model2
result <- model2$results$Rsquared[1]
## Predict DNA shapes Using DNAshapeR (Myc: 1-mer)
fn_fasta <- paste0(workingPath, "Myc.txt.fa")
pred <- getShape(fn_fasta)
## Encode feature vectors
featureType <- c("1-mer")
featureVector <- encodeSeqShape(fn_fasta, pred, featureType)
head(featureVector)
## Build MLR model by using Caret
## Data preparation
fn_exp <- paste0(workingPath, "Myc.txt")
exp_data <- read.table(fn_exp)
df <- data.frame(affinity=exp_data$V2, featureVector)
## Arguments setting for Caret
trainControl <- trainControl(method = "cv", number = 10, savePredictions = TRUE)
## Prediction without L2-regularized
model <- train (affinity~ ., data = df, trControl=trainControl,
method = "lm", preProcess=NULL)
summary(model)
## Prediction with L2-regularized
model2 <- train(affinity~., data = df, trControl=trainControl,
method = "glmnet", tuneGrid = data.frame(alpha = 0, lambda = c(2^c(-15:15))))
model2
result <- model2$results$Rsquared[1] |
744c9b62bb580c72ac0ae302055d55bed392528d | 67c4da4303daa228a90f50bf346da0e1f0420926 | /scripts/03_Plots.R | 240d34af76d1e42bbb454c5e2ab457167484b974 | [] | no_license | troettge/ItalianFinalLengthening | 432a6dc3b98190adaaedd30fcd6df3876fa71691 | 6d8f46e354a0b304371cc81c0118c904a8824d78 | refs/heads/master | 2020-04-21T12:45:58.382993 | 2019-02-07T15:59:22 | 2019-02-07T15:59:22 | 169,574,183 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 7,167 | r | 03_Plots.R | ## Project: Final Lengthening in Italian
## Description: Plot results
## Author: Timo Roettger
## Contact: timo.b.roettger@gmail.com
## Date: 07/02/19
## Code book:
# processed_Italian_QS.csv
# Speaker: Unique Speaker IDs (n = 16)
# Rand: Randomisation list (rand1, rand2, rand3, rand4)
# Pros: Prosodic condition (Query vs. Stat(ement))
# Word: Lexical item in phrase-final position (n = 32)
# Durw: Word duration in seconds
# Fvowel: Quality of final vowel (' indicated stress)
# DurFvowel: Duration of final vowel
# Stress: Whether final syllable is stressed or not (1 vs. 0)
# processed_Italian_list.csv
# Speaker: Unique Speaker IDs (n = 16)
# Rand: Randomisation list (rand1, rand2, rand3, rand4)
# Position: Position in list (prefinal vs. final)
# Word: Lexical item in phrase-final position (n = 32)
# Durw: Word duration in seconds
# vowel: Quality of final vowel
# DurFvowel: Duration of final vowel
# stress: Whether final syllable is stressed or not (1 vs. 0)
## load in packages
library(tidyverse)
library(rstudioapi)
library(brms)
library(bayesplot)
library(ggbeeswarm)
## Getting the path of your current open file
current_path = rstudioapi::getActiveDocumentContext()$path
setwd(dirname(current_path))
setwd("../data/")
xdata_qs <- read_csv("processed_Italian_QS.csv")
xdata_list <- read_csv("processed_Italian_list.csv")
load("Bayesian_models_Italian.RData")
load("Posteriors_Italian.RData")
## plot results
# Preprocess
xdata_qs$stress <- as.factor(as.character(xdata_qs$stress))
xdata_list$stress <- as.factor(as.character(xdata_list$stress))
posteriors_qs$Stress <- as.factor(as.character(posteriors_qs$Stress))
posteriors_list$Stress <- as.factor(as.character(posteriors_list$Stress))
levels(xdata_qs$stress) <- c("trochee", "iambus")
levels(posteriors_qs$Stress) <- c("iambus", "trochee")
levels(xdata_list$stress) <- c("trochee", "iambus")
levels(posteriors_list$Stress) <- c("iambus", "trochee")
xdata_qs$Pros <- as.factor(xdata_qs$Pros)
levels(xdata_qs$Pros) <- c("Question", "Statement")
levels(posteriors_qs$Function) <- c("Question", "Statement")
xdata_list$Position <- as.factor(xdata_list$Position)
levels(xdata_list$Position) <- c("Final", "Prefinal")
# aggregate
xagg_qs <- xdata_qs %>%
group_by(Pros, Speaker, stress) %>%
summarise(mean_dur = mean(DurFvowel)) %>%
rename(Stress = stress, Function = Pros)
xagg_qs$Function <- as.factor(xagg_qs$Function)
levels(xagg_qs$Function) <- c("Question", "Statement")
xagg_list <- xdata_list %>%
group_by(Position, Speaker, stress) %>%
summarise(mean_dur = mean(Durvowel)) %>%
rename(Stress = stress, Function = Position)
xagg_list$Function <- as.factor(xagg_list$Function)
levels(xagg_list$Function) <- c("Final", "Prefinal")
xagg_qs$Stress <- factor(xagg_qs$Stress,levels(xagg_qs$Stress)[c(2,1)])
xagg_list$Stress <- factor(xagg_list$Stress,levels(xagg_list$Stress)[c(2,1)])
# plot Figure_qs
results_plot_qs <-
ggplot(xagg_qs) +
#geom_hline(aes(yintercept = 0.5), colour = "grey", lty = "dashed") +
geom_errorbar(data = posteriors_qs, aes(x = Function, ymin = lci, ymax = uci,
group = interaction(Stress, Function)),
colour = "black", position = position_dodge(width = 1), width = 0.2) +
geom_point(data = posteriors_qs, aes(x = Function, y = mean, fill = Stress), colour = "black",
size = 4, pch = 21,
position = position_dodge(width = 1)) +
geom_quasirandom(aes(x = Function, y = mean_dur, colour = Stress),
alpha = 0.3, size = 3, dodge.width = 1) +
ylab("Vowel duration in seconds\n") +
xlab("\n") +
scale_colour_manual(values = c("#0072B2", "#D55E00")) +
scale_fill_manual(values = c("#0072B2", "#D55E00")) +
scale_y_continuous(expand = c(0, 0), breaks = (c(0,0.1,0.2,0.3,0.35)), limits = c(0,0.35)) +
labs(title = "Duration of final vowel",
subtitle = "posterior means and 95% credible intervals\nsemitransparent dots are speaker averages") +
theme_bw() +
theme(legend.position = "right",
legend.key.height = unit(2,"line"),
legend.title = element_text(size = 18, face = "bold"),
legend.text = element_text(size = 16),
legend.background = element_rect(fill = "transparent"),
strip.background = element_blank(),
strip.text = element_text(size = 18, face = "bold"),
panel.spacing = unit(2, "lines"),
plot.background = element_rect(fill = "transparent", colour = NA),
panel.background = element_rect(fill = "transparent"),
axis.line.x = element_blank(),
axis.text = element_text(size = 16),
axis.title = element_text(size = 18, face = "bold"),
plot.title = element_text(size = 18, face = "bold"),
plot.margin = unit(c(0.2,0.1,0.2,0.1),"cm"))
# plot Figure_list
results_plot_list <-
ggplot(xagg_list) +
#geom_hline(aes(yintercept = 0.5), colour = "grey", lty = "dashed") +
geom_errorbar(data = posteriors_list, aes(x = Function, ymin = lci, ymax = uci,
group = interaction(Stress, Function)),
colour = "black", position = position_dodge(width = 1), width = 0.2) +
geom_point(data = posteriors_list, aes(x = Function, y = mean, fill = Stress), colour = "black",
size = 4, pch = 21,
position = position_dodge(width = 1)) +
geom_quasirandom(aes(x = Function, y = mean_dur, colour = Stress),
alpha = 0.3, size = 3, dodge.width = 1) +
ylab("Vowel duration in seconds\n") +
xlab("\n") +
scale_colour_manual(values = c("#0072B2", "#D55E00")) +
scale_fill_manual(values = c("#0072B2", "#D55E00")) +
scale_y_continuous(expand = c(0, 0), breaks = (c(0,0.1,0.2,0.25)), limits = c(0,0.25)) +
labs(title = "Duration of final vowel",
subtitle = "posterior means and 95% credible intervals\nsemitransparent dots are speaker averages") +
theme_bw() +
theme(legend.position = "right",
legend.key.height = unit(2,"line"),
legend.title = element_text(size = 18, face = "bold"),
legend.text = element_text(size = 16),
legend.background = element_rect(fill = "transparent"),
strip.background = element_blank(),
strip.text = element_text(size = 18, face = "bold"),
panel.spacing = unit(2, "lines"),
plot.background = element_rect(fill = "transparent", colour = NA),
panel.background = element_rect(fill = "transparent"),
axis.line.x = element_blank(),
axis.text = element_text(size = 16),
axis.title = element_text(size = 18, face = "bold"),
plot.title = element_text(size = 18, face = "bold"),
plot.margin = unit(c(0.2,0.1,0.2,0.1),"cm"))
setwd("../plots/")
ggsave(filename = "results_plot_qs.png",
plot = results_plot_qs,
width = 150,
height = 150,
units = "mm",
#bg = "transparent",
dpi = 500)
ggsave(filename = "results_plot_list.png",
plot = results_plot_list,
width = 150,
height = 150,
units = "mm",
#bg = "transparent",
dpi = 500)
|
0cc9ec19684518e0758fdc47d4c5be1e2e006e71 | fce169786d16e6a4145dd47da96aa43fda44b32f | /Creating_multiple_pop-up_window.R | 351c127a50384200e8d5adbe3adeae222ce58d56 | [] | no_license | ramnithish/R-Shiny | 38095d898d99a1747fdae6fbd62ab4a78cfc9903 | 2db69ea4dfe4702ab60fd530b1a2b641260d76b5 | refs/heads/master | 2020-04-07T12:40:55.406285 | 2019-01-10T03:16:49 | 2019-01-10T03:16:49 | 158,376,718 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,576 | r | Creating_multiple_pop-up_window.R | library(shiny)
library(ggplot2) # used to plot ggplot2 graphs
##ui code begin here
ui <- fluidPage(
h4("PLOT of MTCARS"),
# sidebarPanel(
# selectInput('xCol', 'X', names(mtcars)),
# selectInput('yCol', 'Y', names(mtcars))),
#
# Shows the plot in mainpanel
mainPanel(plotOutput('plot',click = "clicks")),
verbatimTextOutput("rt")
)
### server side code begins here ###
server <- function(input, output, session){
# scatter plot the mtcars dataset - mpg vs hp
output$plot <- renderPlot({
ggplot(data = mtcars, aes(x = mpg, y = hp)) +
geom_point()
})
## It prints selected points in main window
output$rt <- renderPrint({
ss<- nearPoints(mtcars,input$clicks, "mpg", "hp")
st= as.data.frame(ss)
st
})
observeEvent(input$clicks,{showModal(modalDialog(
plotOutput("plt2",click = "clicks1")
))
## It add plot to pop-up window.
output$plt2<-renderPlot({
##subsetting and changing to data frame
ss<- nearPoints(mtcars,input$clicks, "mpg", "hp")
st= as.data.frame(ss)
st
ggplot(data=st, aes(x = mpg, y = hp)) +
geom_point()})
observeEvent(input$clicks1, {
showModal(modalDialog(
plotOutput("plt3")
))
output$plt3<-renderPlot({
##subsetting and changing to data frame
ss<- nearPoints(mtcars,input$clicks, "mpg", "hp")
st= as.data.frame(ss)
st
ggplot(data=st, aes(x = mpg, y = hp)) +
geom_boxplot()})
})
})
}
shinyApp(ui = ui, server = server)
|
b5a5fa73e34c13d708b66a1bd539676b2e584446 | 300250b64edf0ed40e7f120647a3226197032297 | /problemadamochila.r | 540ffaf9a9e227505f086b0d54dda1515d816360 | [] | no_license | brunamagrinidacruz/semcomp22-algoritmos-evolutivos | cbcba323b1108604081411bad7914a6d88dac07b | f57c04a4c987ebf706809454ce35980ccb526117 | refs/heads/master | 2022-03-21T09:42:01.693418 | 2019-10-01T03:12:12 | 2019-10-01T03:12:12 | 211,992,711 | 1 | 0 | null | null | null | null | ISO-8859-1 | R | false | false | 6,235 | r | problemadamochila.r | # Uma mochila suporta 15kg
# Temos a possibilidade de fazer a combinacao entre os pesos e o ganho:
# Valor: 2 Peso: 1
# Valor: 4 Peso: 12
# Valor: 2 Peso: 2
# Valor: 1 Peso: 1
# Valor: 10 Peso: 4
capacidade = 15
valor = c(2, 4, 2 , 1, 10)
peso = c(1, 12, 2, 1, 4)
mochila <- function(cromossomo) {
valor_mochila = 0
peso_mochila = 0
# Para i de 1 ate o tamanho do cromossomo
for(i in 1:length(cromossomo)) {
# Se o valor da posicao do cromossomo for 1, pega o valor e o peso daquele item
# Exemplo: 1 1 0 1 0
# Pegaria o valor: 2 (1º), 4 (2º), 1 (4º) = 7
# Pegaria o peso: 1 (1º), 12 (2º), 1 (4º) = 14
if(cromossomo[i] == 1) {
valor_mochila = valor_mochila + valor[i]
peso_mochila = peso_mochila + peso[i]
}
}
# Estamos verificando se o peso estourou a capacidade da mochila
if(peso_mochila > capacidade) {
return(0)
} else {
return (valor_mochila)
}
}
# Temos uma aplicacao totalmente diferente do cromossomo em relacao ao AlgortimosEvolutivos-v3, mas o restante e identico:
# Entrada:
# - tamanho da populacao
# - tamanho do cromosssomo
# - numero de geracoes
# Saida:
# - media e desvio do fitness da populacao final
ae_mochila <- function(tamanho_populacao, tamanho_cromossomo, numero_de_geracoes) {
# A funcao round(numero, casa) arredonda um numero para uma quantia de casa decimais. Por definicao, casa = 0
# Exemplo: round(123.546, 2) = 123.54 ou round(123.546) = 123
# A funcao runinf(n) cria n valores aleatorios entre 0 e 1
# Quanto ruinf(n, a, b) ela cria n valores aleatorios entre a e b
# Cria a populacao de invidivuos. Cada cromossomo e uma linha da matriz
populacao <- matrix(round(runif(tamanho_populacao * tamanho_cromossomo)),
nrow = tamanho_populacao)
# Cria uma matriz com n valores de 0 e 1 (gerando valores entre 0 e 1 com o ruinf e arredondando com round)
# O n tem tamanho tamanho_populacao * tamanho_cromossomo (se tiver 3 individuos, cada qual com 5 de tamanho, será necessario 3*5 = 15 valores)
# Alem disso, a matriz tem tamanho_população de linhas
# Array que armazenara as aptidoes
fitness = c()
# Avalia cada individuo
# Neste exemplo, a aptidao e exatamente o valor da soma dos bits
for(i in 1:nrow(populacao)) { # Interar na quantidade de individuos. Poderia ser tamanho_populacao
# 1º Modificacao: fitness sera o valor dentro da mochila
fitness = c(fitness, mochila(populacao[i,]))
}
# A funcao max(vetor), mean(vetor) e min(vetor) retorna respectivamente o maior, do meio e minino elemento do vetor
# Imprime a aptidao do melhor individuo, do pior e a media
cat("Indice \t Maximo \t Media \t Minimo \n")
cat(0, "\t", max(fitness), "\t", mean(fitness), "\t", min(fitness), "\n")
# Inicio do processo evolutivo
for(i in 1:numero_de_geracoes) {
# A funcao sample(numero, quantidade) gera quantidade de valores entre 1 ate numero de forma aleatoria
# Exemplo sample(5) = 5 2 3 4 1 ou sample(5, 2) = 2 4
# Seleciona dois reprodutores
reprodutores = sample(tamanho_populacao, 2, replace = FALSE)
# Aqui, a funcao sample vai escrever 2 indices entre o tamanho_populacao
# Os individuos que forem tiverem esse indice, sao os selecionados para serem reprodutores
# Seleciona um ponto para ocorrer o crossover (nesse ponto o vetor pai1 e pai2 serao cortados)
ponto_de_crossover = sample(tamanho_cromossomo-2, 2) + 1
# Exclui os pontos das extremidades (2: comeco e fim) e soma 1, para nao ficar no inicio
# Isso ocorre porque se nao o ponto de crossover poderia ser o 1 ou tamanho_cromossomo, nao gerando modificacoes no cromossomo filho
# Criando os dois filhos
filho1 = c(populacao[reprodutores[1], 1:ponto_de_crossover], # Pega os valores do cromossomo reprodutor1 do inicio ate o ponto de crossover
populacao[reprodutores[2], (ponto_de_crossover+1):tamanho_cromossomo]) # Pega os valores do cromossomo reprodutor2 do ponto de crossover ate o fim do cromossomo
# Assim, gera-se um novo cromossomo com parte do corpo do reprodutor 1 e a outra parte do reprodutor 2
filho2 = c(populacao[reprodutores[2], 1:ponto_de_crossover],
populacao[reprodutores[1], (ponto_de_crossover+1):tamanho_cromossomo])
# Seleciona os pontos para occorer a mutacao
ponto_de_mutacao1 = sample(tamanho_cromossomo, 1, replace = TRUE)
ponto_de_mutacao2 = sample(tamanho_cromossomo, 1, replace = TRUE)
# Aplica mutacao nos dois filhos gerados
filho1[ponto_de_mutacao1] = !filho1[ponto_de_mutacao1]
filho2[ponto_de_mutacao2] = !filho2[ponto_de_mutacao2]
# 2º Modificacao: Calcula o fitness de cada filho
fitness_filho1 = mochila(filho1)
fitness_filho2 = mochila(filho2)
# A funcao order(vetor) retorna um vetor com as posicoes para que vetor fique em ordem crescente
# Exemplo: order(7, 5, 4) = 3, 2, 1 pois o item 3, item 2 e item 1 nessa sequencia tornaria o vetor ordenado
# Escrevendo order(vetor)[a:b] retorna um vetor de a ate b
# Devolve o indice dos individuos com piores soma (fitness) da populacao
inferiores_populacao <- order(fitness)[1:2]
# Se o filhos tem melhor fitness que os dois piores individuos, realiza a substituicao
if(fitness_filho1 > fitness[inferiores_populacao[1]]) {
populacao[inferiores_populacao[1], ] <- filho1 # Agora, o pior individuo e substituido pelo filho 1
fitness[inferiores_populacao[1]] = fitness_filho1 # Atualizando fitness
}
if(fitness_filho2 > fitness[inferiores_populacao[2]]) {
populacao[inferiores_populacao[2], ] <- filho2
fitness[inferiores_populacao[2]] = fitness_filho2
}
# Imprime a aptidao do melhor individuo, do pior e a media
cat(i, "\t", max(fitness), "\t", mean(fitness), "\t", min(fitness), "\n")
}
cat("\n População final:\n")
print(populacao)
# Retorna o valor da media e do desvio-padrao
return(c(mean(fitness), sd(fitness)))
}
|
9e64ccbe281708b0ff978bcaff85764a17f942b9 | 38dea308be807a700802b877178bf6a41aac63ce | /man/show.project.Rd | d130ee4e46e0e4f53897e7aee41e4a66b2e4811a | [] | no_license | jeromyanglim/ProjectTemplate | 84e8e745da052007562b7ee40af63f939da71518 | 2b23b98718dde14c1e4161d05ed841dffabd49b4 | refs/heads/master | 2021-01-24T11:39:27.413553 | 2018-02-25T20:18:29 | 2018-02-25T20:18:29 | 70,218,773 | 2 | 2 | null | 2016-10-07T05:43:39 | 2016-10-07T05:43:38 | null | UTF-8 | R | false | true | 1,006 | rd | show.project.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/show.project.R
\name{show.project}
\alias{show.project}
\title{Show information about the current project.}
\usage{
show.project()
}
\value{
No value is returned; this function is called for its side effects.
}
\description{
This function will show the user all of the information that
ProjectTemplate has about the current project. This information is
gathered when \code{\link{load.project}} is called. At present,
ProjectTemplate keeps a record of the project's configuration settings,
all packages that were loaded automatically and all of the data sets that
were loaded automatically. The information about autoloaded data sets
is used by the \code{\link{cache.project}} function.
}
\examples{
library('ProjectTemplate')
\dontrun{load.project()
show.project()}
}
\seealso{
\code{\link{create.project}}, \code{\link{load.project}},
\code{\link{get.project}}, \code{\link{cache.project}}
}
|
070dd2fb8de9df0b7e5411dc880a744e84be7fb9 | 86a0e477dbfcf3319b6884a151c829182060ec5a | /MUSIC_results/MUSIC.R | 0fcf8dc9d0425e5ff20d8f9b5a2c0888630095de | [] | no_license | JuanruMaryGuo/perturb | 4af31c8ad5c924967071fbc243745be7eaf2c533 | 920e82ed6d9335e671f120dfd6ce27960779ffa6 | refs/heads/main | 2023-02-04T15:07:36.181815 | 2020-12-21T13:08:54 | 2020-12-21T13:08:54 | 303,863,707 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 5,299 | r | MUSIC.R | library(Biostrings)
library(clusterProfiler)
library(devtools)
library(SAVER)
library(MUSIC)
library(Seurat)
setwd("/Users/guojuanru/Desktop/Yale/MUSIC/mock")
crop_seq_list_mock<-Input_preprocess_10X_modified("/Users/guojuanru/Desktop/Yale/MUSIC/mock/")
save(crop_seq_list_mock,file = "crop_seq_list_mock.Rdata")
expression_profile = crop_seq_list_mock$expression_profile
perturb_information = crop_seq_list_mock$perturb_information
dim(expression_profile)
expression_profile[1:3,1:3]
# cell quality control
crop_seq_qc<-Cell_qc_modified(crop_seq_list_mock$expression_profile,crop_seq_list_mock$perturb_information,plot=T)
save(crop_seq_qc,file = "crop_seq_qc.Rdata")
# data imputation, it may take a little long time without parallel computation.
crop_seq_imputation<-Data_imputation(crop_seq_qc$expression_profile,crop_seq_qc$perturb_information,cpu_num=5)# cell filtering, it may take a little long time without parallel computation.
save(crop_seq_imputation,file = "crop_seq_imputation.Rdata")
crop_seq_filtered<-Cell_filtering_modified(crop_seq_imputation$expression_profile,crop_seq_imputation$perturb_information,cpu_num=6,cell_num_threshold = 15,plot = TRUE)# obtain highly dispersion differentially expressed genes.
save(crop_seq_filtered,file = "crop_seq_filtered.Rdata")
crop_seq_vargene<-Get_high_varGenes_modified(crop_seq_filtered$expression_profile,crop_seq_filtered$perturb_information,plot=T)# get topics.
save(crop_seq_vargene,file = "crop_seq_vargene.Rdata")
topic_model_list<-Get_topics_modified(crop_seq_vargene$expression_profile,crop_seq_vargene$perturb_information,topic_number=c(4:6))
save(topic_model_list,file = "topic_model_list.Rdata")
# select the optimal topic number.
optimalModel<-Select_topic_number(topic_model_list$models,plot=T)
#If you just calculated one topic number, you can skip this step, just run the following:
optimalModel<-topic_model_list$models[[1]]
save(optimalModel,file = "optimalModel.Rdata")
# calculate topic distribution for each cell.
distri_diff<-Diff_topic_distri_modified(optimalModel,topic_model_list$perturb_information,plot=T)
write.csv(distri_diff, file = "distri_diff.csv")
# calculate the overall perturbation effect ranking list without "offTarget_Info".
rank_overall_result<-Rank_overall_modified(distri_diff)
write.csv(rank_overall_result, file = "rank_overall_result.csv")
# calculate the topic-specific ranking list.
rank_topic_specific_result<-Rank_specific_modified(distri_diff)
write.csv(rank_topic_specific_result, file = "rank_topic_specific_result.csv")
# calculate the perturbation correlation.
perturb_cor<-Correlation_perturbation(distri_diff,plot=T)
write.csv(perturb_cor, file = "perturb_cor.csv")
setwd("/Users/guojuanru/Desktop/Yale/MUSIC/sars2_result")
crop_seq_list_sars<-Input_preprocess_10X_modified("/Users/guojuanru/Desktop/Yale/MUSIC/sars2")
save(crop_seq_list_sars,file = "crop_seq_list_sars.Rdata")
expression_profile = crop_seq_list_sars$expression_profile
perturb_information = crop_seq_list_sars$perturb_information
dim(expression_profile)
expression_profile[1:3,1:3]
# cell quality control
crop_seq_qc<-Cell_qc_modified(crop_seq_list_sars$expression_profile,crop_seq_list_sars$perturb_information,plot=T)
save(crop_seq_qc,file = "crop_seq_qc.Rdata")
# data imputation, it may take a little long time without parallel computation.
crop_seq_imputation<-Data_imputation(crop_seq_qc$expression_profile,crop_seq_qc$perturb_information,cpu_num=4)# cell filtering, it may take a little long time without parallel computation.
save(crop_seq_imputation,file = "crop_seq_imputation.Rdata")
crop_seq_filtered<-Cell_filtering_modified(crop_seq_imputation$expression_profile,crop_seq_imputation$perturb_information,cpu_num=4,cell_num_threshold = 15,plot = TRUE)# obtain highly dispersion differentially expressed genes.
save(crop_seq_filtered,file = "crop_seq_filtered.Rdata")
crop_seq_vargene<-Get_high_varGenes_modified(crop_seq_filtered$expression_profile,crop_seq_filtered$perturb_information,plot=T)# get topics.
save(crop_seq_vargene,file = "crop_seq_vargene.Rdata")
topic_model_list<-Get_topics_modified(crop_seq_vargene$expression_profile,crop_seq_vargene$perturb_information,topic_number=c(4:6))
save(topic_model_list,file = "topic_model_list.Rdata")
# select the optimal topic number.
optimalModel<-Select_topic_number(topic_model_list$models,plot=T)
#If you just calculated one topic number, you can skip this step, just run the following:
optimalModel<-topic_model_list$models[[1]]
save(optimalModel,file = "optimalModel.Rdata")
# calculate topic distribution for each cell.
distri_diff<-Diff_topic_distri_modified(optimalModel,topic_model_list$perturb_information,plot=T)
write.csv(distri_diff, file = "distri_diff.csv")
# calculate the overall perturbation effect ranking list without "offTarget_Info".
rank_overall_result<-Rank_overall_modified(distri_diff)
write.csv(rank_overall_result, file = "rank_overall_result.csv")
# calculate the topic-specific ranking list.
rank_topic_specific_result<-Rank_specific_modified(distri_diff)
write.csv(rank_topic_specific_result, file = "rank_topic_specific_result.csv")
# calculate the perturbation correlation.
perturb_cor<-Correlation_perturbation(distri_diff,plot=T)
write.csv(perturb_cor, file = "perturb_cor.csv")
|
655e5cd2715c4d5abd5c33b3a6a90b9110a8f96a | f4fe6046e22427afe038f136f8383ecbab7accae | /cart/02-custom-metric.R | 5a3b09c53693b2f067b14c068b149ff86de643ff | [] | no_license | anhnguyendepocen/rexamples | 73a91d71bf7d1fa5f88f2539cd6471b413e882f5 | 9ef0e4676ac6486b369e9fee407d928655e72337 | refs/heads/master | 2021-10-08T23:00:13.762527 | 2018-12-18T20:33:12 | 2018-12-18T20:33:12 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,049 | r | 02-custom-metric.R | # @ ?train (see Examples section)
### include
library(caret)
library(plyr)
library(ggplot2)
### data
data(iris)
iris <- subset(iris, Species == "setosa")
str(iris)
X <- subset(iris, select = c("Sepal.Length", "Petal.Length"))
Y <- subset(iris, select = "Petal.Width")
# See the reasoning for the model by plotting
# qplot(Sepal.Length, Petal.Length, data = iris, color = Species, size = Petal.Width)
### split data into T/V
ind.tr <- 1:30
Y.tr <- Y[ind.tr, ]
Y.val <- Y[-ind.tr, ]
X.tr <- X[ind.tr, ]
X.val <- X[-ind.tr, ]
### summary function
madSummary <- function(data, lev = NULL, model = NULL)
{
out <- mad(data$obs - data$pred, na.rm = TRUE)
names(out) <- "RMSEsum"
out
}
#####
### fit a model
trControl <- trainControl(summaryFunction = madSummary)
tuneGrid <- expand.grid(.size = c(1, 2), .decay = c(0, 1e-4, 0.01))
fit <- train(X.tr, Y.tr,
preProcess = c("center", "scale"),
trControl = trControl, metric = "RMSEsum", maximize = FALSE,
method = "nnet", tuneGrid = tuneGrid,
trace = FALSE)
fit
plot(fit)
|
68672daf67ec2b86482671d8200da51847fc66fb | 0c980239ec00947f41822ff21c24c838f27882ef | /R/euterpe.R | 7bacf30af7eb9b59d16618c1119ced1ea5f51464 | [] | no_license | AndreaSanchezTapia/spfilt | 0f1c2f5eec2b10c63c0045700d6d68ee7804d0fc | 837abc10da176c0670ca365a458ece799269f76a | refs/heads/master | 2020-04-01T18:13:44.034430 | 2019-09-06T06:10:00 | 2019-09-06T06:10:00 | 153,479,998 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 286 | r | euterpe.R | #' Euterpe edulis occurrence data.
#' @description Distribution data for Euterpe edulis (a widely distributed palm, occurring continuously throughout the Atlantic Forest). Downloaded from GBIF with the gbif function from dismo package.
#' @references \url{http://www.gbif.org}
"euterpe" |
d706ff9ea42ab9b09c705abbcaa7f4fb0774febb | 64d87e5dca09e79caafa9b597553adcaefc9050c | /test5.R | 20ad15a76f7b9eb010c2691827cef1a67608f585 | [] | no_license | lionem2018/R_Practice | 127f85b16c8a6404893d31fc96f858b3f5452421 | 28660a71e0e0dd9219f2279edf5273c758f7d3a2 | refs/heads/master | 2020-03-22T08:57:59.919723 | 2018-07-05T06:28:56 | 2018-07-05T06:28:56 | null | 0 | 0 | null | null | null | null | ISO-8859-7 | R | false | false | 500 | r | test5.R | install.packages("readxl") # exel??Ό??½κΈ°μ??¨?€ΧΩ?€μΉ?
library(readxl)
# 첫ν?λ³?λͺ
μ΄μ‘΄μ¬? κ²½μ°
df_exam1 <-read_excel("excel_exam.xlsx")
df_exam1
# 첫νλΆ?°λ°λ‘?°?΄?°?Όκ²½μ°
df_exam2 <- read_excel("excel_exam.xlsx", col_names=F)
df_exam2
mean(df_exam1$english)
mean(df_exam1$math)
write.csv(df_exam1, file="csv_test.csv")
df_csv_exam <- read.csv("csv_test.csv") |
48baa4ccc46dd4f0d8ee5b95c79203682487d087 | 0211662ef5092f5350ef811056d9ad39bd7e40b3 | /man/hello.Rd | 3155555a0267c8ff4cc355f545afc97d879c379d | [] | no_license | paulafortuna/StopPropagHateR | eafdaf2aa4738ba51cc8479c69a5a6cf4425c0ca | 56ca97d37c3a87e0dc89e4c1d2fcecf99b6df400 | refs/heads/master | 2020-03-22T17:49:12.981636 | 2018-07-18T07:36:01 | 2018-07-18T07:36:01 | 140,418,313 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 286 | rd | hello.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/hello.R
\name{hello}
\alias{hello}
\title{Hello World}
\usage{
hello(myname = "")
}
\arguments{
\item{myname}{your name. Required.}
}
\description{
Basic hello world function to be called from the demo app
}
|
bb48561977ee1fd499a63f5871720a6b69853c13 | e5b1416f3d7434fc19fee3a51474069cb2478e29 | /man/evaluateFasta.Rd | 936174b2accb9fa41afe2e725df443fa9de3a6cb | [] | no_license | anilgunduz/deepG | 16c13a8e0d2d372913506ab626ad31d4af76c428 | e47c415f04da15e363b46c39027c30255e0b698e | refs/heads/master | 2023-06-26T23:38:27.845094 | 2021-07-30T09:51:12 | 2021-07-30T09:51:12 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 2,861 | rd | evaluateFasta.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/predict.R
\name{evaluateFasta}
\alias{evaluateFasta}
\title{Evaluates a trained model on .fasta/fastq files}
\usage{
evaluateFasta(
fasta.path,
model = NULL,
batch.size = 100,
step = 1,
vocabulary = c("a", "c", "g", "t"),
label_vocabulary = c("a", "c", "g", "t"),
numberOfBatches = 10,
filePath = NULL,
format = "fasta",
filename = "",
target_middle = FALSE,
plot = FALSE,
mode = "lm",
acc_per_batch = FALSE,
output_format = "target_right",
ambiguous_nuc = "zero",
evaluate_all_files = FALSE,
verbose = TRUE,
max_iter = 20000,
target_from_csv = NULL
)
}
\arguments{
\item{fasta.path}{Input directory where fasta/fastq files are located.}
\item{model}{A keras model.}
\item{batch.size}{Number of samples per batch.}
\item{step}{How often to take a sample.}
\item{vocabulary}{Vector of allowed characters, character outside vocabulary get encoded as 0-vector.}
\item{label_vocabulary}{Labels for targets. Equal to vocabulary if not given.}
\item{numberOfBatches}{How many batches to evaluate.}
\item{filePath}{Where to store output, if missing output won't be written.}
\item{format}{File format, "fasta" or "fastq".}
\item{filename}{Name of output file.}
\item{plot}{Returns density plot of accuracies if TRUE.}
\item{mode}{Either "lm" for language model and "label_header", "label_csv" or "label_folder" for label classification.}
\item{acc_per_batch}{Whether to return vector with accuracies for every batch.}
\item{output_format}{Determines shape of output tensor for language model.
Either "target_right", "target_middle_lstm", "target_middle_cnn" or "wavenet".
Assume a sequence "AACCGTA". Output correspond as follows
"target_right": X = "AACCGT", Y = "A"
"target_middle_lstm": X = (X_1 = "AAC", X_2 = "ATG"), Y = "C" (note reversed order of X_2)
"target_middle_cnn": X = "AACGTA", Y = "C"
"wavenet": X = "AACCGT", Y = "ACCGTA"}
\item{ambiguous_nuc}{How to handle nucleotides outside vocabulary, either "zero", "discard" or "equal". If "zero", input gets encoded as zero vector;
if "equal" input is 1/length(vocabulary) x length(vocabulary). If "discard" samples containing nucleotides outside vocabulary get discarded.}
\item{evaluate_all_files}{Boolean, if TRUE will iterate over all files in \code{fasta.path} once. \code{numberOfBatches} will be overwritten.}
\item{verbose}{Whether to show message.}
\item{max_iter}{Stop after max_iter number of iterations failed to produce a new batch.}
\item{target_from_csv}{Path to csv file with target mapping. One column should be called "file" and other entries in row are the targets.}
\item{model.path}{Path to pretrained model.}
}
\description{
Returns accuracies per batch and overall confusion matrix. Evaluates \code{batch.size} * \code{numberOfBatches} samples.
}
|
3328254b26b254e0c4cecb4daf032a007db9f8a8 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/HK80/examples/HK1980GRID_TO_WGS84UTM.Rd.R | 669abe3d4f2ec90f7774d30c4a730f7bc43c5ccc | [] | 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 | 542 | r | HK1980GRID_TO_WGS84UTM.Rd.R | library(HK80)
### Name: HK1980GRID_TO_WGS84UTM
### Title: Convert HK1980GRID coordinates to WGS84UTM coordinates
### Aliases: HK1980GRID_TO_WGS84UTM
### Keywords: HK1980GRID WGS84UTM
### ** Examples
options(digits = 15)
HK1980GRID_TO_WGS84UTM(820351.389, 832591.320)
#### $N
#### [1] 2471278.72371238
####
#### $E
#### [1] 205493.220852789
####
#### $zone
#### [1] 50
######################################
#### Answer from the online Conversion tool
#### http://www.geodetic.gov.hk/smo/tform/tform.aspx
#### 50Q 2471279 205494
|
bddc749c3c1e47b89267c79d6604db2eb7df4566 | 78ee080962e68cbca60c7a27e5abe91ca728ebfe | /server.R | e412b8b37d9c9bc6a88b38ebdccb751862d5b2ff | [] | no_license | saos-apps/wspolzasiadanie | 44abe18adbd221d1a653ba89741fc457043ab167 | 8a3ee349168429de9a11d00a266bb66bf3cd02dd | refs/heads/master | 2021-01-15T11:49:06.683865 | 2019-05-24T17:47:54 | 2019-05-24T17:47:54 | 31,543,312 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 28,320 | r | server.R | require(tidyr)
require(scales)
require(zoo)
require(shiny)
require(ggplot2)
require(igraph)
require(plyr)
require(dplyr)
require(data.table)
require(RColorBrewer)
require(sqldf)
source("funkcje.R")
source("helpers.R")
judgments<-readRDS("data/judgments.rds")
judges<-readRDS("data/judges.rds")
divisions<-readRDS("data/divisions.rds")
judges.net<-readRDS("data/judges.net.rds")
Sys.setlocale("LC_ALL","pl_PL.UTF-8")
mon<-data.frame(abr=paste(months(as.Date(paste("01-",1:12,"-1995",sep="")),T)," ",sep=""),pe=paste(months(as.Date(paste("01-",1:12,"-1995",sep="")),F)," ",sep=""))
theme_set(theme_bw())
shinyServer(function(input, output, session) {
values <- reactiveValues(starting = TRUE)
session$onFlushed(function() {
values$starting <- FALSE
})
output$select.court<-renderUI({
courts.un<-divisions[!duplicated(divisions$CourtCode),] %>% dplyr::arrange(CourtName)
list1<-as.list(courts.un$CourtCode)
names(list1)<-courts.un$CourtName
selectInput("select.court",label=h3("Wybierz sąd:"),choices=list1)
})
court.divisions<-reactive({
subset(divisions,CourtCode==input$select.court)
})
subset.judgments.court<-reactive({
subset(judges.net,CourtCode==input$select.court)
})
subset.judges.court<-reactive({
judges.sub<-subset(judges,CourtCode==input$select.court)
judges.sub<-subset(judges.sub,!is.na(judges.sub$JudgeName))
})
judges.top.court<-reactive({
judges.top.c(subset.judges.court())
})
subgraph.court<-reactive({
g.court(subset.judges.court(),subset.judgments.court())
})
subgraph.simplified.court<-reactive({
g.simplify.c(subgraph.court())
})
subgraph.mark.matrix<-reactive({
g.mark.matrix(subgraph.simplified.court())
})
subgraph.mark.list<-reactive({
g.mark.list(subgraph.simplified.court(),subgraph.mark.matrix())
})
subgraph.color.pie<-reactive({
g.color.pie(subgraph.simplified.court())
})
subgraph.layout<-reactive({
g<-subgraph.simplified.court()
layout.fruchterman.reingold(g,weights=E(g)$weight,area=10000*vcount(g)^2,repulserad=50000*vcount(g)^3)
})
# judges.coop.year<-reactive({
# j.coop.year(subset.judges.court(),subset.judgments.court(),subgraph.simplified.court())
# })
subgraph.summary<-reactive({
g<-subgraph.court()
g.sim<-subgraph.simplified.court()
paste("vcount:",vcount(g),"ecount",ecount(g),
"ecount simplified:",ecount(g.sim),sep=" ")
})
s.dist<-reactive({
s<-plyr::count(subset.judges.court(),"judgmentID")$freq
as.data.frame(s)
})
k.dist<-reactive({
if(vcount(subgraph.simplified.court())<2){ return(NULL)}
k<-as.vector(degree(subgraph.simplified.court()))
as.data.frame(k)
})
w.dist<-reactive({
if(ecount(subgraph.simplified.court())==0){return(NULL)}
w=as.vector(E(subgraph.simplified.court())$weight)
data.frame(w=w)
})
judgments.year<-reactive({
validate(
need(nrow(subset.judges.court())!=0,"Trwa ładowanie danych...")
)
judgm.year(subset.judges.court())
})
judgments.year2<-reactive({
validate(
need(nrow(subset.judges.court())!=0,"Trwa ładowanie danych...")
)
judgm.year2(subset.judges.court())
})
judges.year<-reactive({
validate(
need(nrow(subset.judges.court())!=0,"Trwa ładowanie danych...")
)
j.year(subset.judges.court())
})
team.size<-reactive({
#judgm.count<- subset(judges,CourtCode==input$select.court) %>% plyr::count(.,"judgmentID") %>% mutate(liczba.s=as.factor(freq))
judgm.count<- subset(judges,CourtCode==input$select.court) %>% plyr::count(.,"judgmentID") %>% mutate(liczba.s=as.factor(freq)) %>% select(-freq) %>% group_by(liczba.s) %>% dplyr::summarise(count=n())
})
team.types<-reactive({
validate(
need(nrow(subset.judges.court())!=0,"Trwa ładowanie danych...")
)
judg.cnt<-plyr::count(subset.judges.court(),c("judgmentID","JudgeSex"))
temp<-spread(judg.cnt,JudgeSex,freq,fill = 0) %>% filter(F+M>0) %>% mutate(typestring=paste(F,ifelse(F==1,"kobieta","kobiet"),"i\n",M,ifelse(M==1,"mężczyzna","mężczyzn"))) %>% mutate(frac=F/(F+M)) %>% group_by(F,M,typestring,frac) %>% dplyr::summarise(count=n())
if(nrow(temp)>25){temp<-temp %>% ungroup() %>% mutate(typestring=paste(F,"k.\n",M,"m."))}
temp
})
team.types2<-reactive({
validate(
need(nrow(subset.judges.court())!=0,"Trwa ładowanie danych...")
)
judg.cnt<-plyr::count(subset.judges.court(),c("judgmentID","JudgeSex"))
ttypes2<-spread(judg.cnt,JudgeSex,freq,fill = 0) %>% mutate(major=ifelse(F>M,"kobiety",ifelse(F==M,"brak przewagi","mężczyźni"))) %>% mutate(typer=paste(ifelse(F>M,F,M),ifelse(F>M,M,F),sep="/"))
ggplot(ttypes2, aes(x=typer, fill=major))+geom_bar(position="fill")
ctypes2<-plyr::count(ttypes2,c("major","typer")) %>% filter(typer!="0/0") #%>% mutate(freqnorm=ifelse(freq<sum(freq)/17,sum(freq)/17,freq))
temp<-aggregate(freq ~ typer,ctypes2,sum) %>% mutate(freqnorm=ifelse(freq<sum(freq)/17,sum(freq)/17,freq)) %>% arrange(desc(freqnorm)) %>% mutate(xmax=cumsum(freqnorm),xmin=(xmax-freqnorm))
ctypes2<-merge(ctypes2,temp,by="typer") %>% mutate(freq.x=freq.x/freq.y)
names(ctypes2)[c(3,4)]<-c("freqmajor","typesum")
ctypes2<-ddply(ctypes2, .(typer), transform, ymax = cumsum(freqmajor)) %>% mutate(ymin=ymax-freqmajor)
ctypes2$xtext <- with(ctypes2, xmin + (xmax - xmin)/2)
ctypes2$ytext <- with(ctypes2, ymin + (ymax - ymin)/2)
ctypes2
})
team.types2b<-reactive({
validate(
need(nrow(subset.judges.court())!=0,"Trwa ładowanie danych...")
)
judg.cnt<-plyr::count(subset.judges.court(),c("judgmentID","JudgeSex"))
ttypes2<-spread(judg.cnt,JudgeSex,freq,fill = 0) %>% mutate(major=ifelse(F>M,"kobiety",ifelse(F==M,"brak przewagi","mężczyźni"))) %>% mutate(typer=paste(ifelse(F>M,F,M),ifelse(F>M,M,F),sep="/"))
ctypes2<-plyr::count(ttypes2,c("major","typer")) %>% mutate(typer=ifelse(freq<10,"inne",typer)) %>% group_by(major,typer) %>% dplyr::summarise(freq=sum(freq)) %>% filter(freq>=10)
temp<-aggregate(freq ~ typer,ctypes2,sum) %>% mutate(freqnorm=ifelse(freq<sum(freq)/17,sum(freq)/17,freq)) %>% arrange(desc(freqnorm)) %>% mutate(xmax=cumsum(freqnorm),xmin=(xmax-freqnorm))
ctypes2<-merge(ctypes2,temp,by="typer") %>% mutate(freq.x=freq.x/freq.y)
names(ctypes2)[c(3,4)]<-c("freqmajor","typesum")
ctypes2<-ddply(ctypes2, .(typer), transform, ymax = cumsum(freqmajor)) %>% mutate(ymin=ymax-freqmajor)
ctypes2$xtext <- with(ctypes2, xmin + (xmax - xmin)/2)
ctypes2$ytext <- with(ctypes2, ymin + (ymax - ymin)/2)
ctypes2
})
team.types3<-reactive({
validate(
need(nrow(subset.judges.court())!=0,"Trwa ładowanie danych...")
)
judg.cnt<-plyr::count(subset.judges.court(),c("judgmentID","JudgeSex"))
ttypes3<-spread(judg.cnt,JudgeSex,freq,fill = 0) %>% plyr::count(.,c("F","M")) %>% filter(F+M>0)
})
#
# max.component<-reactive({
# max.comp(subgraph.court())
# })
subset.judges.clean<-reactive({
subset(subset.judges.court(),!is.na(JudgeSex))
})
output$plot.k <- renderPlot({
#if(is.null(k.dist())){return(NULL)}
validate(
need(!is.null(k.dist()),"Brak danych...")
)
#br<-if(length(unique(k.dist()$k))>1) seq(min(k.dist()$k,na.rm =T),max(k.dist()$k,na.rm =T),length.out=20) else seq(0,20,length.out=20)
# ggplot(k.dist(),aes(x=k))+geom_histogram(breaks=br)+
# #scale_x_discrete
# labs(x="k - liczba bezpośrednich połączeń z innymi sędziami",y="Liczba wystąpień",title="Histogram zmiennej k")+
# theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0, vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"))+scale_x_continuous(breaks=pretty_breaks(20))
#
bby<-ceiling(max(k.dist()$k)/20)
br<-seq(1,max(k.dist()$k),by=bby)
ggplot(k.dist(),aes(x=k))+geom_histogram(aes(fill=..count..),breaks=br)+
#scale_x_discrete
labs(x="Liczba współorzekających sędziów.",y="Liczba sędziów",title="Współzasiadanie (sędziowie)")+
theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0, vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"))+
scale_x_continuous(breaks=br[-1]-bby/2,labels=br[-1])
}) #,width=1000,height=600)
output$plot.w <- renderPlot({
#if(is.null(w.dist())){return(NULL)}
validate(
need(!is.null(w.dist()),"Brak danych...")
)
# br<-if(length(unique(w.dist()$w))>1) seq(min(w.dist()$w,na.rm =T),max(w.dist()$w,na.rm =T),length.out=20) else seq(0,20,length.out=20)
# ggplot(w.dist(),aes(x=w))+geom_histogram(breaks=br)+labs(x="w - ile razy dwóch sędziów zasiadało w tym samym składzie sędziowskim",y="Liczba wystąpień",title="Histogram zmiennej w")+
# theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0, vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"))+scale_x_continuous(breaks=pretty_breaks(20))
bby<-ceiling(max(w.dist()$w)/20)
br<-seq(1,max(w.dist()$w),by=bby)
ggplot(w.dist(),aes(x=w))+geom_histogram(aes(fill=..count..),breaks=br)+labs(x="Ile razy dwóch sędziów zasiadało w tym samym składzie sędziowskim",y="Liczba wystąpień",title="Współzasiadanie (orzeczenia)")+
theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0, vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"))+
scale_x_continuous(breaks=br[-1]-bby/2,labels=br[-1])
}) #,width=1000,height=600)
#
# plot.comp <- reactive({
# if(is.null(max.component())){return(NULL)}
# ggplot(max.component(),aes(x=year,y=size.max.component)) + geom_line()+labs(y="Rozmiar największego komponentu [%]",title="Graph of the maximum component relative size in terms of number of nodes")+ylim(0,1)
# })
output$plot.judges <- renderPlot({
#if(nrow(judges.year())==0){return(NULL)}
validate(
need(sum(!is.na(judges.year()$number.judges))>1,"Brak danych...")
)
siz<-c(1,2,3,4,6,12,24)
bylab<-siz[which(length(judges.year()$Data)/44 < siz)[1]]
br1<-judges.year()$Data[seq(1,length(judges.year()$Data),by=bylab)]
yearlabel<-seq(as.numeric(strsplit(as.character(judges.year()$Data[1])," ")[[1]][2]),as.numeric(strsplit(as.character(judges.year()$Data[length(judges.year()$Data)])," ")[[1]][2]))
xlab<-seq(1,length(judges.year()$Data),12)
br2<-rep(mon$abr[seq(1,12,by=bylab)],length(yearlabel))
#br2<-as.vector(br)
# for(i in 1:12){br2<-gsub(pattern = mon$abr[i],paste0(mon$pe[i],"\n"),br2)}
plabels<-data.frame(x=xlab,year=yearlabel,y=1.05*(max(judges.year()$number.judges,na.rm=T)))
ggplot(judges.year(), aes(x=Data, y=number.judges, group=1)) +
geom_point(stat='summary', fun.y=sum) +
stat_summary(fun.y=sum, geom="line")+
scale_x_discrete(labels=br2,breaks=br1)+
labs(x="miesiąc",y="Liczba orzekających sędziów",title="Liczba orzekających sędziów w czasie")+
ylim(0,max(judges.year()$number.judges)*1.1)+
theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0, vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"))+
geom_vline(xintercept =xlab[-1],colour="grey45",alpha=0.7,linetype="longdash")+
geom_text(data=plabels,aes(x=x, label=year,y=y), colour="blue", angle=0, text=element_text(size=10),hjust =-0.1)
}) #,width=1000,height=600)
output$plot.judgments<- renderPlot({
#if(nrow(judgments.year())==0){return(NULL)}
validate(
need(sum(!is.na(judgments.year()$number.judgments))>1,"Brak danych...")
)
siz<-c(1,2,3,4,6,12,24)
bylab<-siz[which(length(judgments.year()$Data)/44 < siz)[1]]
br1<-judgments.year()$Data[seq(1,length(judgments.year()$Data),by=bylab)]
yearlabel<-seq(as.numeric(strsplit(as.character(judgments.year()$Data[1])," ")[[1]][2]),as.numeric(strsplit(as.character(judgments.year()$Data[length(judgments.year()$Data)])," ")[[1]][2]))
xlab<-seq(1,length(judgments.year()$Data),12)
br2<-rep(mon$abr[seq(1,12,by=bylab)],length(yearlabel))
plabels<-data.frame(x=xlab,year=yearlabel,y=1.05*(max(judgments.year()$number.judgments,na.rm=T)))
ggplot(judgments.year(), aes(x=Data, y=number.judgments, group=1)) +
geom_point(stat='summary', fun.y=sum) +
stat_summary(fun.y=sum, geom="line")+
scale_x_discrete(labels=br2,breaks=br1)+
labs(x="miesiąc",y="Liczba orzeczeń",title="Wykres pokazujący liczbę orzeczeń w wybranym sądzie w danym miesiącu")+
ylim(0,max(judgments.year()$number.judgments)*1.1)+
theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0, vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"))+
geom_vline(xintercept =xlab[-1],colour="grey45",alpha=0.7,linetype="longdash")+
geom_text(data=plabels,aes(x=x, label=year,y=y), colour="blue", angle=0, text=element_text(size=10),hjust =-0.1)
}) #,width=1000,height=600)
output$plot.team.size<-renderPlot({
validate(
need(nrow(team.size())>1,"Brak danych...")
)
# ggplot(team.size(),aes(x=liczba.s))+geom_histogram()+
# labs(x="Liczba sędziów w składzie",y="Liczba wystąpień",title="Wykres pokazujący wielkość składów sędziowskich")+
# #ylim(0,max())
# theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0, vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"))
ggplot(team.size(), aes(x=liczba.s, y=count, width=0.5)) +
geom_bar(aes(fill=count), stat="identity", position="identity")+
labs(x="Liczba sędziów orzekających",y="Liczba orzeczeń")+
geom_text(aes(x=liczba.s,y=count+max(count)/30,label=count),size=5)+
scale_y_continuous(breaks=pretty_breaks(10))+
theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0, vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"),legend.position="none")
}) #,width=1000,height=600)
output$plot.team.types<-renderPlot({
validate(
need(nrow(team.types())!=0,"Trwa ładowanie danych...")
)
# qplot(typestring,data=team.types(),geom="bar",fill=frac)+
# labs(x="Typ składu orzekającego",y="Liczba wystąpień",title="Wykres pokazujący wszystkie typy składów orzekających z podziałem na płeć")+
# theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0, vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"))+
# scale_fill_continuous()+
#
ggplot(team.types(), aes(x=typestring, y=count, width=0.5)) +
geom_bar(aes(fill=frac), stat="identity", position="identity")+
labs(x="Typ składu orzekającego",y="Liczba wystąpień",title="Wykres pokazujący wszystkie typy składów orzekających z podziałem na płeć")+
geom_text(aes(x=typestring,y=count+max(count)/30,label=count),size=5)+
scale_y_continuous(breaks=pretty_breaks(10))+
scale_fill_continuous(low="royalblue3",high="indianred3")+
theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0, vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"),legend.position="none")
}) #,width=1000,height=600)
output$plot.team.types2<-renderPlot({
validate(
need(nrow(team.types2())>1,"Brak danych...")
)
labels<-data.frame(xmean=team.types2()$xmin+(team.types2()$xmax-team.types2()$xmin)/2,text=team.types2()$typesum)
ggplot(team.types2(), aes(ymin = ymin, ymax = ymax, xmin = xmin, xmax = xmax, fill = major))+geom_rect(colour = I("grey"))+
geom_text(aes(x = xtext, y = ytext, label = ifelse(xmin==0,paste(major," - ",round(100*freqmajor,1), "%", sep = ""),paste(round(100*freqmajor,1), "%", sep = ""))), size = 4.5)+
geom_text(aes(x = xtext, y = 1.03, label = typer), size = 5)+
annotate("text",label="Typ składu: ",x=(min(labels$xmean*0.1)),y=1.03,size=5)+
annotate("text",x=labels$xmean,y=-0.03,label=labels$text,size=5)+
annotate("text",label="L. orzeczeń: ",x=(0),y=-0.03,size=5)+ #min(labels$xmean*0.1)
ggtitle("Wykres pokazujący wszystkie typy składów orzekających z podziałem na płeć")+
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(),legend.position="bottom",
panel.background=element_blank(),panel.border=element_blank(),panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),plot.background=element_blank())
}) #,width=1000,height=600
output$plot.team.types2b<-renderPlot({
validate(
need(nrow(team.types2b())>1,"Brak danych...")
)
labels<-data.frame(xmean=team.types2b()$xmin+(team.types2b()$xmax-team.types2b()$xmin)/2,text=team.types2b()$typesum)
ggplot(team.types2b(), aes(ymin = ymin, ymax = ymax, xmin = xmin, xmax = xmax, fill = major))+geom_rect(colour = I("grey"),aes(fill=major))+
geom_text(aes(x = xtext, y = ytext, label = ifelse(xmin==0,paste(major," - ",round(100*freqmajor,1), "%", sep = ""),paste(round(100*freqmajor,1), "%", sep = ""))), size = 4)+
geom_text(aes(x = xtext, y = 1.03, label = typer), size = 4)+
annotate("text",label="Typ składu: ",x=(min(labels$xmean*0.1)),y=1.03,size=4)+
annotate("text",x=labels$xmean,y=-0.03,label=labels$text,size=4)+
annotate("text",label=" L. orzeczeń: ",x=(0),y=-0.03,size=4)+ #min(labels$xmean*0.15)
ggtitle("Wykres pokazujący wszystkie typy składów orzekających z podziałem na płeć")+
scale_fill_manual(name="",values=c("kobiety"="indianred3","mężczyźni"="royalblue3","brak przewagi"="grey45"))+
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(),legend.position="bottom",
panel.background=element_blank(),panel.border=element_blank(),panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),plot.background=element_blank())
}) #,width=1000,height=600)
output$plot.team.types3<-renderPlot({
validate(
need(nrow(team.types3())!=0,"Trwa ładowanie danych...")
)
ggplot(team.types3(),aes(x=M,y=F))+geom_point(aes(size=freq,colour=F/(F+M)))+
scale_size_continuous(range = c(9,20))+scale_shape()+
scale_color_continuous(low="orange",high="firebrick3")+
scale_x_continuous(limits=c(-1,1+max(team.types3()$M)),breaks=seq(0,max(team.types3()$M)))+
scale_y_continuous(limits=c(-1,1+max(team.types3()$F)),breaks=seq(0,max(team.types3()$F)))+
theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0,face="bold", hjust=0.5,vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"),legend.position="none")+
geom_text(aes(x=M,y=F,label=freq),size=3.5,color="white",fontface=2)+
labs(x="Liczba mężczyzn",y="Liczba kobiet")+
coord_fixed(ratio = 1)
}) #,width=1000,height=600)
output$typesImage<-renderImage({
validate(
need(nrow(team.types3())!=0,"Trwa ładowanie danych...")
)
width <- session$clientData$output_typesImage_width
height <- session$clientData$output_typesImage_height
# For high-res displays, this will be greater than 1
pixelratio <- session$clientData$pixelratio
outfile <- tempfile(fileext='.svg')
xylim<-max(c(team.types3()$M,team.types3()$F))
g1<-ggplot(team.types3(),aes(x=M,y=F))+geom_point(aes(size=freq,colour=F/(F+M)))+
scale_size_continuous(range = c(11,25))+scale_shape()+
#scale_color_continuous(low="orange",high="firebrick3")+
scale_color_continuous(low="royalblue3",high="indianred3")+
scale_x_continuous(limits=c(-1,1+xylim),breaks=seq(0,xylim))+
scale_y_continuous(limits=c(-1,1+xylim),breaks=seq(0,xylim))+
theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(angle=0,face="bold", hjust=0.5,vjust=0.5, size=12),axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=12),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"),legend.position="none")+
geom_text(aes(x=M,y=F,label=freq),size=4.2,color="white",fontface=2)+
labs(x="Liczba mężczyzn",y="Liczba kobiet")
ggsave(filename=(outfile),g1,width = height*0.8,height=height*0.8,units ="mm") #height/width
filename <- normalizePath(file.path(outfile))
list(src=filename,
alt="alt text",
width=width*0.7, #*pixelratio
height=width*0.7
# width=1000,
#height=750
)
})
plot.sex<-reactive({
if(nrow(subset.judges.clean())==0){return(NULL)}
plot.sex.distribution(subset.judges.clean())
})
output$topbreaks <- renderUI({
if(round((session$clientData$output_topImage_width-550)/30)>0){
HTML(rep("<br/>",round((session$clientData$output_topImage_width-550)/30)))
}
})
output$netbreaks <- renderUI({
if(round((session$clientData$output_pieImage_width-500)/30)>0){
HTML(rep("<br/>",round((session$clientData$output_pieImage_width-500)/30)))
}
})
output$typbreaks <- renderUI({
if(round((session$clientData$output_typesImage_width*0.7 - 410)/20)>0){
HTML(rep("<br/>",1+round((session$clientData$output_typesImage_width*0.7 - 410)/20)))
}
})
# output$text1<-renderText({c(session$clientData$output_typesImage_width," ",session$clientData$output_typesImage_height)})
# output$table1<-renderDataTable({judges.year()})
# output$table2<-renderDataTable({judgments.year()})
# output$table3<-renderDataTable({team.types()})
# output$table4<-renderDataTable({team.size()})
# stare rysowanie sieci bez svg
output$plot.pie<-renderPlot({
g<-subgraph.color.pie()
lay<-subgraph.layout()
layout(matrix(c(rep(1,12),2,2,2,3), 4, 4, byrow = FALSE))
par(mar=c(0,0,0,0))
plog.pie(g,lay)
par(mar=c(0,0,0,0))
plog.legend2(g.color.div(subgraph.simplified.court(),subgraph.mark.matrix(),court.divisions()))
par(mar=c(0,0,3,0))
plog.sex()
},width=1000,height=800)
output$plot.multi<-renderPlot({
#multiplot(plot.judgments(),plot.judges(),plot.sex(),plot.k(),plot.w(),plot.comp(),plot.coop(),cols=1)
#multiplot(plot.judgments(),plot.judges(),plot.k(),plot.w(),plot.team.size(),plot.team.types(),cols=1)
#multiplot(plot.judgments(),cols=1)
},width=1000,height=2850)
output$topImage<-renderImage({
validate(
need(nrow(subset.judges.court())>0,"Trwa ładowanie danych...")
)
validate(
need(nrow(subset.judges.court())>1,"Brak danych...")
)
width <- session$clientData$output_topImage_width
height <- session$clientData$output_topImage_height*1.5
# For high-res displays, this will be greater than 1
pixelratio <- session$clientData$pixelratio
top<-judges.top.court()
outfile <- tempfile(fileext='.svg')
g1<-ggplot(top,aes(x=N.of.judgments,y=JudgeName,size=N.of.judgments))+geom_point()+labs(x="Łączna liczba orzeczeń",y="Sędzia",title="10 sędziów orzekających w największej liczbie spraw")+geom_segment(x =0, y =nrow(top):1 , aes(xend =(N.of.judgments-0.50*sqrt(N.of.judgments/pi))), yend = nrow(top):1,size=0.7)+theme(axis.title.x = element_text(face="bold", colour="#990000", size=14),axis.title.y = element_text(face="bold", colour="#990000", size=14),axis.text.y = element_text(face="bold",angle=0, vjust=0.5, size=10),legend.position="none",plot.title=element_text(face="bold",angle=0, vjust=0.5, size=14,colour="#990000"))+scale_shape()+scale_size_continuous(range = c(3,12))
ggsave(filename=(outfile),g1,width = 2*120,height=2*120*0.7,units ="mm") #height/width
filename <- normalizePath(file.path(outfile))
list(src=filename,
alt="alt text",
width=width, #*pixelratio
height=width*0.7
# width=1000,
#height=750
)
}, deleteFile = TRUE)
#not used
# output$times<-renderText({
# g<-subgraph.color.pie()
# lay<-subgraph.layout()
# t.pie<-system.time(plog.pie(g,lay))[1]
# t.multi<-system.time(multiplot(plot.judgments(),plot.judges(),plot.sex(),plot.k(),plot.w(),plot.comp(),plot.coop(),cols=2))[1]
# t.lay<-system.time(subgraph.layout())[1]
# t.g<-system.time(subgraph.court())[1]
# t.sim<-system.time(subgraph.simplified.court())[1]
# paste("Times",t.lay,t.g,t.sim,t.pie,t.multi,sep=";")
# })
output$pieImage <- renderImage({
validate(
need(vcount(subgraph.simplified.court())>0, "Trwa ładowanie danych...")
)
validate(
need(vcount(subgraph.simplified.court())>1, "Brak danych...")
)
width <- session$clientData$output_pieImage_width
height <- session$clientData$output_pieImage_height
# For high-res displays, this will be greater than 1
pixelratio <- session$clientData$pixelratio
g<-subgraph.color.pie()
lay<-subgraph.layout()
outfile <- tempfile(fileext='.svg')
svg(outfile)
layout(matrix(c(rep(c(rep(1,3),2),2),rep(1,3),3,rep(4,4)), 4, 4, byrow = TRUE))
par(mar=c(0,0,0,0))
plog.pie.svg(g,lay)
par(mar=c(0,0,0,0))
plog.legend.svg(g.color.div(subgraph.simplified.court(),subgraph.mark.matrix(),court.divisions()))
par(mar=c(0,0,0,0))
plog.sex.svg()
dev.off()
filename <- normalizePath(file.path(outfile))
list(src=filename,
alt="alt text",
width=width,
height=width
#width=1000,
#height=1000
)
}, deleteFile = TRUE)
}) |
db924e83f69a3f07e4c493692fa83d88af9d958c | 7906d9809924c2d9d6f7652aca712144e095cf35 | /man/readFromPopulationFile.Rd | ef43cb8fac8bb53e8cd6ef47cf6a45369d9c9158 | [
"MIT"
] | permissive | rdinnager/slimrlang | 999d8f5af0162dbcc8c42ff93b4dc5ae2f0cb7fc | 375a2667b0b3ab4fa03786fb69c5572f6367d36b | refs/heads/master | 2022-10-19T04:02:43.013658 | 2020-06-14T10:31:45 | 2020-06-14T10:31:45 | 262,492,066 | 1 | 0 | null | null | null | null | UTF-8 | R | false | true | 7,317 | rd | readFromPopulationFile.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/slim_lang.R
\name{readFromPopulationFile}
\alias{readFromPopulationFile}
\alias{SLiMSim$readFromPopulationFile}
\alias{.SS$readFromPopulationFile}
\title{SLiM method readFromPopulationFile}
\usage{
readFromPopulationFile(filePath)
}
\arguments{
\item{filePath}{An object of type string. Must be of length 1 (a singleton). See
details for description.}
}
\value{
An object of type integer. Return will be of length 1 (a singleton)
}
\description{
Documentation for SLiM function \code{readFromPopulationFile}, which is a method
of the SLiM class \code{SLiMSim}.
Note that the R function is a stub, it does not do anything in R (except bring
up this documentation). It will only do
anything useful when used inside a \code{\link{slim_block}} function further
nested in a \code{\link{slim_script}}
function call, where it will be translated into valid SLiM code as part of a
full SLiM script.
}
\details{
Read from a population initialization file, whether in text or binary
format as previously specified to outputFull(), and return the generation
counter value represented by the file’s contents (i.e., the generation at which
the file was generated). Although this is most commonly used to set up initial
populations (often in an Eidos event set to run in generation 1, immediately
after simulation initialization), it may be called in any Eidos event; the
current state of all populations will be wiped and replaced by the state in
the file at filePath. All Eidos variables that are of type object and have
element type Subpopulation, Genome, Mutation, Individual, or Substitution will
be removed as a side effect of this method, since all such variables would
refer to objects that no longer exist in the SLiM simulation; if you want to
preserve any of that state, you should output it or save it to a file prior
to this call. New symbols will be defined to refer to the new Subpopulation
objects loaded from the file. If the file being read was written by a version
of SLiM prior to 2.3, then for backward compatibility fitness values will be
calculated immediately for any new subpopulations created by this call, which
will trigger the calling of any activated and applicable fitness() callbacks.
When reading files written by SLiM 2.3 or later, fitness values are not
calculated as a side effect of this call (because the simulation will often
need to evaluate interactions or modify other state prior to doing so). In SLiM
2.3 and later when using the WF model, calling readFromPopulationFile() from
any context other than a late() event causes a warning; calling from a late()
event is almost always correct in WF models, so that fitness values can be
automatically recalculated by SLiM at the usual time in the generation cycle
without the need to force their recalculation (see chapter 21, and comments on
recalculateFitness() below). In SLiM 3.0 when using the nonWF model, calling
readFromPopulationFile() from any context other than an early() event causes a
warning; calling from an early() event is almost always correct in nonWF models,
so that fitness values can be automatically recalculated by SLiM at the usual
time in the generation cycle without the need to force their recalculation (see
chapter 22, and comments on recalculateFitness() below). As of SLiM 2.1, this
method changes the generation counter to the generation read from the file.
If you do not want the generation counter to be changed, you can change it
back after reading, by setting sim.generation to whatever value you wish. Note
that restoring a saved past state and running forward again will not yield the
same simulation results, because the random number generator’s state will not
be the same; to ensure reproducibility from a given time point, setSeed() can
be used to establish a new seed value. Any changes made to the simulation’s
structure (mutation types, genomic element types, etc.) will not be wiped
and re-established by readFromPopulationFile(); this method loads only the
population’s state, not the simulation configuration, so care should be taken
to ensure that the simulation structure meshes coherently with the loaded data.
Indeed, state such as the selfing and cloning rates of subpopulations, values
set into tag properties, and values set onto objects with setValue() will also
be lost, since it is not saved out by outputFull(). Only information saved by
outputFull() will be restored; all other state associated with the simulation’s
subpopulations, individuals, genomes, mutations, and substitutions will be lost,
and should be re-established by the model if it is still needed. As of SLiM
2.3, this method will read and restore the spatial positions of individuals if
that information is present in the output file and the simulation has enabled
continuous space (see outputFull() for details). If spatial positions are
present in the output file but the simulation has not enabled continuous space
(or the number of spatial dimensions does not match), an error will result.
If the simulation has enabled continuous space but spatial positions are not
present in the output file, the spatial positions of the individuals read will
be undefined, but an error is not raised. As of SLiM 3.0, this method will read
and restore the ages of individuals if that information is present in the output
file and the simulation is based upon the nonWF model. If ages are present but
the simulation uses a WF model, an error will result; the WF model does not use
age information. If ages are not present but the simulation uses a nonWF model,
an error will also result; the nonWF model requires age information. As of SLiM
3.3, this method will restore the nucleotides of nucleotide-based mutations, and
will restore the ancestral nucleotide sequence, if that information is present
in the output file. Loading an output file that contains nucleotide information
in a non-nucleotide-based model, and vice versa, will produce an error.
This method can also be used to read tree-sequence (.trees) files saved by
treeSeqOutput() or generated by the Python pyslim package. When loading a tree
sequence, a crosscheck of the loaded data will be performed to ensure that the
tree sequence was well-formed and was loaded correctly. When running a Release
build of SLiM, however, this crosscheck will only occur the first time that
readFromPopulationFile() is called to load a tree sequence; subsequent calls
will not perform this crosscheck, for greater speed when running models that
load saved population state many times (such as models that are conditional on
fixation). If you suspect that a tree sequence file might be corrupted or read
incorrectly, running a Debug build of SLiM enables crosschecks after every load.
}
\section{Copyright}{
This is documentation for a function in the SLiM software, and has been
reproduced from the official manual,
which can be found here: \url{http://benhaller.com/slim/SLiM_Manual.pdf}. This
documentation is
Copyright © 2016–2020 Philipp Messer. All rights reserved. More information
about SLiM can be found
on the official website: \url{https://messerlab.org/slim/}
}
\author{
Benjamin C Haller (\email{bhaller@benhaller.com}) and Philipp W Messer
(\email{messer@cornell.edu})
}
|
60280b155ff9af171e71399d1f1d552fa03ca0cc | f3bbc879600ff372f713d7570ed25c307f09a75b | /imageprocessing/readimages.R | 604ed58f76abc6fa3792c1b05fee8fcaf7087169 | [] | no_license | lauracova/senior_project | 3f73fd3368087c848f0b4ec2d3939a8d51fb0bc5 | 9d15734b6c36c9c72ff65440df4462f95e09f106 | refs/heads/master | 2020-05-03T10:56:51.433338 | 2019-12-03T23:05:57 | 2019-12-03T23:05:57 | 178,590,651 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,232 | r | readimages.R |
'''
The 10 classes to predict are:
c0: safe driving
c1: texting - right
c2: talking on the phone - right
c3: texting - left
c4: talking on the phone - left
c5: operating the radio
c6: drinking
c7: reaching behind
c8: hair and makeup
c9: talking to passenger
'''
############################################
# read in images
############################################
#This video shows what I did in python in 5 minutes
#https://campus.datacamp.com/courses/convolutional-neural-networks-for-image-processing/image-processing-with-neural-networks?ex=1
library(magick)
#https://cran.r-project.org/web/packages/magick/vignettes/intro.html
#read in one pic
image <- image_read("data/train/c0/img_100026.jpg")
#read in many
images <- list.files("data/train/c0")
'''
file_list <- list.files("names/")
my_list <-do.call("rbind",map(file_list,function(x)
read_table(here::here(paste0("Case_Study_12/analysis/names/",x)), col_names = FALSE) %>%
separate("X1", into=c("State", "Gender", "Year", "Name", "Count"), remove=TRUE)
))
'''
####################################################
# Work with Saunders on 4/24
####################################################
class(image)
?image_read
image
image[[1]]
class(image[[1]])
image[[1]][1,,] #reds
image[[1]][,,1] #blues
tmp <- image[[1]]
tmp
tmp <- image
tmp
class(tmp[[1]][1,,]) #these are hex values
class(tmp[[1]][1,1,1])
?raw
View(tmp[[1]][1,,])
View(tmp[[1]][2,,])
#saunders said to just clasify whether the driver is safe or texting in right hand
#attempts to change one rgb color to zero:
> tmp[[1]][1,,] <- 0
Error in tmp[[1]][1, , ] <- 0 :
incompatible types (from double to raw) in subassignment type fix
> tmp[[1]][1,,] <- "0"
Error in tmp[[1]][1, , ] <- "0" :
incompatible types (from character to raw) in subassignment type fix
> tmp[[1]][1,,] <- "00"
Error in tmp[[1]][1, , ] <- "00" :
incompatible types (from character to raw) in subassignment type fix
> tmp[[1]][1,,] <- ff
Error: object 'ff' not found
> tmp[[1]][1,,] <- "ff"
Error in tmp[[1]][1, , ] <- "ff" :
incompatible types (from character to raw) in subassignment type fix
###################################################
# Turn images into data. bitmap, rbg, and raw data
###################################################
library(imager)
#imager package lets you plot image with x and y coordinates and show image without r, g, or b
image2 <- load.image("data/train/c0/img_10003.jpg")
plot(image2) #drivers arms are in different positions???
image2
class(image2)
str(image2) #shows the structure
image2[,,,]
image2[1,,,] #first r, g, b for 480 pixels
image2[2,,,] #second r, g, b for 480 pixels
image2[,1,,] #first r, g, b for 640 pixels
image2[4,4,,]*255 #r, g, b for specific pixel location
#multiply by 255 to get r,g,b from decimal to rgb value
dat1 <- image2[,,,]*255
dat1.red <- dat1[,,1]
dat1.green <- dat1[,,2]
dat1.blue <- dat1[,,3]
View(dat1.red)
#in tidy format with all rgb
data <- as.data.frame(image2)
data %>% mutate(value= value*255)
table(data$cc)
#data$x = 640, data$y = 480, data$cc = r, g, or b, data$value = value of rgb
plot(grayscale(image2))
#turn off r, g, or b
cscale <- function(r,g,b) rgb(0,g,b)
plot(image2, colourscale=cscale,rescale=FALSE)
cscale <- function(r,g,b) rgb(r,0,b)
plot(image2, colourscale=cscale,rescale=FALSE)
cscale <- function(r,g,b) rgb(r,g,0)
plot(image2, colourscale=cscale,rescale=FALSE)
#detect edges
image2.g <- grayscale(image2)
grayscale.values <- image2.g[,,,]
nrow(grayscale.values)
ncol(grayscale.values)
gr <- imgradient(image2.g,"xy")
gr
plot(gr)
grmag <- imgradient(image2,"xy") %>% enorm %>% plot(main="Gradient magnitude")
grmag <- imgradient(image2.g,"xy") %>% enorm %>% plot(main="Gradient magnitude")
class(grmag)
dat2 <- image2.g[,,,] #still 4 dimensions but one color channel
View(dat2)
#raster image
library(raster)
rst.blue <- raster(image2[,,1])
rst.green <- raster(image2[,,2])
rst.red <- raster(image2[,,3])
rst.blue
head(rst.blue)
#another package got the rgb values
library(jpeg)
img <- readJPEG("data/train/c0/img_10003.jpg")
class(img)
img
dim(img)
(img[,,])
dat2 <- (img[,,])*255
dat2.red <- dat2[,,1]
dat2.green <- dat2[,,2]
dat2.blue <- dat2[,,3]
View(dat2.red)
|
b24cf30140b231ce49293c29b9e3565ee966f88d | 457ac364ea29973a1a0378d5665931872100a121 | /CCES R.R | 0f858328fa5acf3e2658f50ab178f33e7a79dee9 | [] | no_license | jberry2/trumps-border-wall | 939f3c93088029b538b532fb64a6d8f1ed2fa219 | 3ddf3f15a3fd1d5f38f560b47d013f0b09b26658 | refs/heads/master | 2020-04-16T21:42:30.689827 | 2019-01-15T23:53:21 | 2019-01-15T23:53:21 | 165,936,317 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 544 | r | CCES R.R | library(haven)
library(tidyverse)
library(ggplot2)
library(survey)
library(ggthemes)
CCES <- read_dta("Documents - Harvard University/2018-2019/September-December/American Public Opinion/Final Memo/CCES16_Common_OUTPUT_Feb2018_VV.dta")
CCES <- as_factor(CCES)
CCES$state <- CCES$inputstate
CCES$white <- CCES$race
white <- CCES %>% rename(race = race) %>% mutate(w = race == "White")
des <- svydesign(id=~1, weights = ~commonweight, data=CCES)
svymean(~white, design = des)
CCES_white <- svyby(~ white, ~ state, design=des, svymean)
|
9b63eac6e49a49b76c542a8b57f2230ba0c7f4f7 | 2219f7988e07df1d78f09e2bd3ce2feb6c87fc51 | /tests/testthat/test-lba-math.R | 7d988ae5efbf318eed9a52cb3d223d1d14c015c7 | [] | no_license | rtdists/rtdists | d1374c0e57fdbe05c0bdd3ce7d2b71d53a4f84e8 | 99a226f750c22de61e8e4899d2776104c316f03d | refs/heads/master | 2022-01-19T10:51:30.547103 | 2022-01-04T09:00:15 | 2022-01-04T09:00:15 | 23,277,437 | 41 | 14 | null | 2023-08-12T02:39:35 | 2014-08-24T09:20:45 | R | UTF-8 | R | false | false | 4,366 | r | test-lba-math.R | context("LBA-math agrees with current implementation")
runif(1)
x <- .Random.seed
set.seed(2)
test_that("PDF and CDF", {
n <- 10
samples_per_run <- 100
source(system.file("extdata", "lba-math.R", package = "rtdists"))
#source("inst/extdata//lba-math.r")
for (i in seq_len(n)) {
A <- runif(1, 0.3, 0.9)
b <- A+runif(1, 0, 0.5)
t0 <- runif(1, 0.1, 0.7)
v1 <- runif(2, 0.5, 1.5)
v2 <- runif(2, 0.1, 0.5)
r_lba1 <- rLBA(samples_per_run, A=A, b=b, t0 = t0,
mean_v=v1[1:2], sd_v=v2[1:2])
expect_equal(
dlba_norm(r_lba1$rt[r_lba1$response==1], A=A, b=b, t0 = t0,
mean_v=v1[1], sd_v=v2[1]),
fptpdf(pmax(r_lba1$rt[r_lba1$response==1]-t0[1], 0), x0max=A, chi=b,
driftrate=v1[1], sddrift=v2[1])
)
expect_equal(
plba_norm(r_lba1$rt[r_lba1$response==1], A=A, b=b, t0 = t0,
mean_v=v1[1], sd_v=v2[1]),
fptcdf(pmax(r_lba1$rt[r_lba1$response==1]-t0[1], 0), x0max=A, chi=b,
driftrate=v1[1], sddrift=v2[1])
)
}
})
test_that("small A values for 'norm'", {
n <- 10
samples_per_run <- 100
source(system.file("extdata", "lba-math.R", package = "rtdists"))
#source("inst/extdata//lba-math.r")
for (i in seq_len(n)) {
A <- runif(1, 0, 1e-10)
b <- A+runif(1, 0, 0.5)
t0 <- runif(1, 0.1, 0.7)
v1 <- runif(2, 0.5, 1.5)
v2 <- runif(2, 0.1, 0.5)
r_lba1 <- rlba_norm(samples_per_run, A=A, b=b, t0 = t0,
mean_v=v1[1:2], sd_v=v2[1:2])
expect_equal(
dlba_norm(r_lba1[,"rt"][r_lba1[,"response"]==1], A=A, b=b, t0 = t0,
mean_v=v1[1], sd_v=v2[1]),
fptpdf(pmax(r_lba1[,"rt"][r_lba1[,"response"]==1]-t0[1], 0),
x0max=A, chi=b, driftrate=v1[1], sddrift=v2[1])
)
expect_equal(
plba_norm(r_lba1[,"rt"][r_lba1[,"response"]==1], A=A, b=b, t0 = t0,
mean_v=v1[1], sd_v=v2[1]),
fptcdf(pmax(r_lba1[,"rt"][r_lba1[,"response"]==1]-t0[1], 0),
x0max=A, chi=b, driftrate=v1[1], sddrift=v2[1])
)
}
})
test_that("Random generation", {
n <- 10
samples_per_run <- 100
source(system.file("extdata", "lba-math.R", package = "rtdists"))
#source("inst/extdata//lba-math.r")
for (i in seq_len(n)) {
A <- runif(1, 0.3, 0.9)
b <- A+runif(1, 0, 0.5)
t0 <- runif(1, 0.1, 0.7)
v1 <- runif(2, 0.5, 1.5)
v2 <- runif(2, 0.1, 0.5)
x <- .Random.seed
r_lba1 <- rlba_norm(samples_per_run, A=A, b=b, t0 = t0,
mean_v=v1[1:2], sd_v=v2[1:2])
.Random.seed <<- x
#r_lba2 <- rlba_norm(samples_per_run, A=A, b=b, t0 = t0, mean_v=v1[1:2], sd_v=v2[1:2])
r_lba2 <- rlba(samples_per_run, A=A, b=b, t0 = t0, vs=v1[1:2], s=v2[1:2])
expect_equal(r_lba1[,"rt"], r_lba2$rt)
expect_equal(r_lba1[,"response"], r_lba2$resp)
}
})
test_that("n1CDF", {
n <- 10
samples_per_run <- 100
source(system.file("extdata", "lba-math.R", package = "rtdists"))
#source("inst/extdata//lba-math.r")
for (i in seq_len(n)) {
A <- runif(1, 0.3, 0.9)
b <- A+runif(1, 0, 0.5)
t0 <- runif(1, 0.1, 0.7)
v1 <- runif(2, 0.5, 1.5)
v2 <- runif(2, 0.1, 0.5)
r_lba1 <- rlba_norm(samples_per_run, A=A, b=b, t0 = t0,
mean_v=v1[1:2], sd_v=v2[1:2], posdrift = TRUE)
#head(r_lba1)
#if(!isTRUE(all.equal(n1CDF(r_lba1$rt[r_lba1$response==1], A=A, b=b, t0 = t0, mean_v=v1[1:2], sd_v=v2[1]),.n1CDF(pmax(r_lba1$rt[r_lba1$response==1]-t0[1], 0), x0max=A, chi=b, drift=v1[1:2], sdI=v2[1]) ))) browser()
#n1CDF(r_lba1$rt[r_lba1$response==1], A=A, b=b, t0 = t0, mean_v=v1[1:2], sd_v=v2[1], browser = TRUE)
#n1CDF(pmax(r_lba1$rt[r_lba1$response==1]-t0[1], 0), A=A, b=b, t0 = 0, mean_v=v1[1:2], sd_v=v2[1])
#.n1CDF(pmax(r_lba1$rt[r_lba1$response==1]-t0[1], 0), x0max=A, chi=b, drift=v1[1:2], sdI=v2[1], browser=TRUE)
#save(r_lba1, A, b, t0, v1, v2, file = "n1CDF_no_diff_example_5.RData")
expect_equal(
n1CDF(sort(r_lba1[,"rt"][r_lba1[,"response"]==1]), A=A, b=b, t0 = t0,
mean_v=v1[1:2], sd_v=v2[1]),
.n1CDF(sort(pmax(r_lba1[,"rt"][r_lba1[,"response"]==1]-t0[1], 0)),
x0max=A, chi=b, drift=v1[1:2], sdI=v2[1]), tolerance = 0.0001
)
}
})
.Random.seed <<- x
|
bf47b41936c8e5ed251127657817e82718632762 | f6dcb066042632979fc5ccdd6aa7d796d3191003 | /Tutorial Code/ggplot_tutorial.R | 4526955965c2eccc79d21f24eab7de39f93ac132 | [] | no_license | NikoStein/ADS19 | 45301bcd68d851053399621dd8a0be784e1cc899 | 90f2439c6de8569f8a69983e0a605fd94e2e9f0a | refs/heads/master | 2020-05-19T19:10:12.411585 | 2020-03-12T00:02:14 | 2020-03-12T00:02:14 | 185,165,255 | 0 | 4 | null | 2019-08-06T06:16:30 | 2019-05-06T09:26:01 | HTML | UTF-8 | R | false | false | 1,487 | r | ggplot_tutorial.R | library(tidyverse)
dfSoccer = read.csv("https://github.com/vincentarelbundock/Rdatasets/raw/master/csv/vcd/Bundesliga.csv")
soccerTable = function(year){
dfSoccer %>%
filter(Year == year) %>%
mutate(pointsHome = if_else(HomeGoals > AwayGoals, 3, if_else(HomeGoals == AwayGoals, 1, 0)),
pointsAway = if_else(HomeGoals > AwayGoals, 0, if_else(HomeGoals == AwayGoals, 1, 3))) %>%
select(-X, -Date, -Round) %>%
gather(key, team, -HomeGoals, -AwayGoals, -Year, -pointsHome, -pointsAway) %>%
group_by(team, Year) %>%
summarise(Points = sum(pointsHome[key=="HomeTeam"]) + sum(pointsAway[key=="AwayTeam"]),
Goals = sum(HomeGoals[key=="HomeTeam"]) - sum(AwayGoals[key=="HomeTeam"]) +
sum(AwayGoals[key=="AwayTeam"]) - sum(HomeGoals[key=="AwayTeam"])) %>%
ungroup() -> df
return(df)
}
years = unique(dfSoccer$Year)
bundesliga = map_df(years, soccerTable)
# Wie bestimmt man den Gewinner pro Saison? Welche Mannschaft hat die meisten Tore geschossen?
bundesliga %>%
group_by(Year) %>%
filter(Points == max(Points))
# Prozente in Labels?
bundesliga %>%
group_by(Year) %>%
arrange(desc(Points)) %>%
mutate(rank = row_number()) %>%
group_by(team) %>%
summarise(shareWon = length(Year[rank==1]) / length(years)) %>%
arrange(desc(shareWon)) %>%
head(5) %>%
ggplot(aes(x=team, y=shareWon)) +
geom_col() + scale_y_continuous(labels = scales::percent) +
theme_bw() + ylab("Anteil Meister") + xlab("") |
f80150efa73044c43b35744943ea8689f6d5c100 | a064b6a958ad39eb5c06001228f8a14d55a14c53 | /ui.R | 0d8b714ae7f5b99cb8005bda38c55c3a31a1d4ed | [
"Apache-2.0"
] | permissive | NickTalavera/Xbox-One-Backwards-Compatibility-Predictions | 51196a064e05ea487664983cc6e2edd277dcee4d | 1263036d2edb66d5edc62907db47c35aed6bb8df | refs/heads/master | 2021-01-17T07:56:03.777255 | 2017-03-04T18:26:34 | 2017-03-04T18:26:34 | 83,819,189 | 2 | 1 | null | null | null | null | UTF-8 | R | false | false | 16,286 | r | ui.R | # Xbox 360 Backwards Compatability Predictor
# Nick Talavera
# Date: November 1, 2016
# ui.R
#===============================================================================
# LIBRARIES #
#===============================================================================
library(shiny)
#===============================================================================
# GENERAL FUNCTIONS #
#===============================================================================
dashboardPage(
#=============================================================================
# DASHBOARD HEADER #
#=============================================================================
dashboardHeader(
title = programName,
titleWidth = sideBarWidth
),
#=============================================================================
# DASHBOARD SIDEBAR #
#=============================================================================
dashboardSidebar(
width = sideBarWidth,
sidebarMenu(id = "sideBarMenu",
menuItem("Lists", tabName = "Lists", icon = icon("gamepad")),
menuItem("Game Search", tabName = "Search", icon = icon("search"))
# menuItem("Processing", tabName = "Processing", icon = icon("list-ol")),
# menuItem("About", tabName = "AboutMe", icon = icon("user"))
)# end of sidebarMenu
),#end of dashboardSidebar
#=============================================================================
# DASHBOARD BODY #
#=============================================================================
dashboardBody(
theme = shinythemes::shinytheme("superhero"),
includeCSS("www/custom.css"),
tabItems(
tabItem(tabName = "Search",
fluidPage(
title = "Search",
fluidRow(
box(
title = "Search",
status = "primary",
width = 12,
solidHeader = FALSE,
collapsible = TRUE,
helpText("Note: You may leave fields empty or unchecked to select all."),
checkboxGroupInput("SEARCH_Is_Backwards_Compatible", label = h3("Is backwards compatible:"),
choices = list("Yes" = TRUE, "No" = FALSE),
selected = ""),
checkboxGroupInput("SEARCH_Predicted_to_become_Backwards_Compatible", label = h3("Predicted to become backwards compatible:"),
choices = list("Yes" = TRUE, "No" = FALSE),
selected = ""),
# sliderInput("SEARCH_Backwards_Compatibility_Probability_Percent",
# label = h3("Backwards compatibility probability percent:"),
# min = 0, max = 100, value = c(0,100), step = 1,
# post = "%", sep = ",", animate=FALSE),
dateRangeInput('SEARCH_Release_date',
label = h3("Release Date:"),
start = range(xboxData$releaseDate)[1], end = range(xboxData$releaseDate)[2],
min = range(xboxData$releaseDate)[1], max = range(xboxData$releaseDate)[2],
separator = " - ", format = "mm/dd/yy",
startview = 'month', weekstart = 1
),
# checkboxGroupInput("SEARCH_Is_Listed_on_XboxCom", label = h3("Is listed on Xbox.com:"),
# choices = list("Yes" = TRUE, "No" = FALSE),
# selected = 1),
# checkboxGroupInput("SEARCH_Is_Exclusive", label = h3("Is Exclusive:"),
# choices = list("Only on Xbox 360" = "Only on Xbox 360", "Also Available on PC" = "PC", "No" = "No"),
# selected = 1),
# checkboxGroupInput("SEARCH_Xbox_One_Version_Available", label = h3("Xbox One version available:"),
# choices = list("Yes" = TRUE, "No" = FALSE),
# selected = 1),
# checkboxGroupInput("SEARCH_Is_On_Uservoice", label = h3("Is on Uservoice"),
# choices = list("Yes" = TRUE, "No" = FALSE),
# selected = 1),
# sliderInput("SEARCH_Uservoice_Votes",
# label = h3("Uservoice votes:"),
# min = 0, max = roundUp(max(xboxData$votes, na.rm = TRUE)), value = c(0,roundUp(max(xboxData$votes, na.rm = TRUE))), step = 1,
# post = " votes", sep = ",", animate=FALSE),
# sliderInput("SEARCH_Uservoice_Comments",
# label = h3("Uservoice comments:"),
# min = 0, max = roundUp(max(xboxData$comments, na.rm = TRUE)), value = c(0,roundUp(max(xboxData$comments, na.rm = TRUE))), step = 1,
# post = " comments", sep = ",", animate=FALSE),
# checkboxGroupInput("SEARCH_Is_Kinect_Supported", label = h3("Is Kinect supported:"),
# choices = list("Yes" = TRUE, "No" = FALSE),
# selected = ""),
# checkboxGroupInput("SEARCH_Is_Kinect_Required", label = h3("Is Kinect required:"),
# choices = list("Yes" = TRUE, "No" = FALSE),
# selected = ""),
# checkboxGroupInput("SEARCH_Does_The_Game_Need_Special_Peripherals", label = h3("Does the game need special peripherals:"),
# choices = list("Yes" = TRUE, "No" = FALSE),
# selected = ""),
# checkboxGroupInput("SEARCH_Is_The_Game_Retail_Only", label = h3("Is the game retail only:"),
# choices = list("Yes" = TRUE, "No" = FALSE),
# selected = ""),
# checkboxGroupInput("SEARCH_Available_to_Purchase_a_Digital_Copy_on_Xbox.com", label = h3("Available to purchase a digital copy on Xbox.com:"),
# choices = list("Yes" = TRUE, "No" = FALSE),
# selected = ""),
# checkboxGroupInput("SEARCH_Has_a_Demo_Available", label = h3("Has a demo available:"),
# choices = list("Yes" = TRUE, "No" = FALSE),
# selected = ""),
sliderInput("SEARCH_Xbox_User_Review_Score",
label = h3("Xbox user review score:"),
min = 0, max = 5, value = c(0,5), step = 0.5,
post = "", sep = ",", animate=FALSE),
sliderInput("SEARCH_Xbox_User_Review_Counts",
label = h3("Xbox user review counts:"),
min = 0, max = roundUp(max(xboxData$numberOfReviews, na.rm = TRUE)), value = c(0,roundUp(max(xboxData$numberOfReviews, na.rm = TRUE))), step = 1,
post = " reviews", sep = ",", animate=FALSE),
sliderInput("SEARCH_Metacritic_Review_Score",
label = h3("Metacritic review score:"),
min = 0, max = 100, value = c(0,100), step = 1,
post = "", sep = ",", animate=FALSE),
sliderInput("SEARCH_Metacritic_User_Review_Score",
label = h3("Metacritic user review score:"),
min = 0, max = 10, value = c(0,10), step = 0.1,
post = "", sep = ",", animate=FALSE),
sliderInput("SEARCH_Price_on_Xbox.com",
label = h3("Price on Xbox.com:"),
min = 0, max = roundUp(max(xboxData$price, na.rm = TRUE)), value = c(0,roundUp(max(xboxData$price, na.rm = TRUE))), step = 1, pre = "$",
post = "", sep = ",", animate=FALSE),
selectInput("SEARCH_Publisher",
label = h3("Publisher:"),
choices = str_title_case(sort(c(as.character(unique(xboxData$publisher))))),
multiple = TRUE),
selectInput("SEARCH_Developer",
label = h3("Developer:"),
choices = str_title_case(sort(c(as.character(unique(xboxData$developer))))),
multiple = TRUE),
selectInput("SEARCH_Genre",
label = h3("Genre:"),
choices = str_title_case(sort(c(as.character(unique(xboxData$genre))))),
multiple = TRUE),
selectInput("SEARCH_ESRB_Rating",
label = h3("ESRB Rating:"),
choices = str_title_case(sort(c(as.character(unique(xboxData$ESRBRating))))),
multiple = TRUE),
selectInput("SEARCH_Features",
label = h3("Features:"),
choices = str_title_case(sort(c(as.character(unique(xboxData$features))))),
multiple = TRUE),
checkboxGroupInput("SEARCH_Smartglass_Compatible",
label = h3("Smartglass Compatible:"),
choices = list("Yes" = TRUE, "No" = FALSE),
selected = ""),
sliderInput("SEARCH_Number_of_Game_Add_Ons",
label = h3("Number of Game Add-Ons:"),
min = 0, max = roundUp(max(xboxData$DLgameAddons, na.rm = TRUE)), value = c(0,roundUp(max(xboxData$DLgameAddons, na.rm = TRUE))), step = 1,
post = " Add-Ons", sep = ",", animate=FALSE),
sliderInput("SEARCH_Number_of_Avatar_Items",
label = h3("Number of Avatar Items:"),
min = 0, max = roundUp(max(xboxData$DLavatarItems, na.rm = TRUE)), value = c(0,roundUp(max(xboxData$DLavatarItems, na.rm = TRUE))), step = 1,
post = " Avatar Items", sep = ",", animate=FALSE),
sliderInput("SEARCH_Number_of_GamerPics",
label = h3("Number of GamerPics:"),
min = 0, max = roundUp(max(xboxData$DLgamerPictures, na.rm = TRUE)), value = c(0,roundUp(max(xboxData$DLgamerPictures, na.rm = TRUE))), step = 1,
post = " GamerPics", sep = ",", animate=FALSE),
sliderInput("SEARCH_Number_of_Themes",
label = h3("Number of Themes:"),
min = 0, max = roundUp(max(xboxData$DLthemes, na.rm = TRUE)), value = c(0,roundUp(max(xboxData$DLthemes, na.rm = TRUE))), step = 1,
post = " Themes", sep = ",", animate=FALSE),
sliderInput("SEARCH_Number_of_Game_Videos",
label = h3("Number of Game Videos:"),
min = 0, max = roundUp(max(xboxData$DLgameVideos, na.rm = TRUE)), value = c(0,roundUp(max(xboxData$DLgameVideos, na.rm = TRUE))), step = 1,
post = " Game Videos", sep = ",", animate=FALSE),
actionButton("query", label = "Search")
),
# conditionalPanel(
# condition = "input.query",
box(
title = "Results",
# status = "primary",
width = 12,
# solidHeader = TRUE,
collapsible = FALSE,
DT::dataTableOutput('List_SearchResults')
)
# )
)# end of fluidrow
) # End of fluidPage
), # End of tabItem
tabItem(tabName = "Lists",
tags$head(tags$style(HTML('
.content {
min-height: 250px;
padding-top:0px;
padding-right: 0px;
padding-bottom: 0px;
padding-left: 0px;
margin-right: 0px;
margin-left: 0px;
}
'))),
navbarPage(
title = 'Interesting Lists',
# position = "static-top",
tabPanel('All Games', DT::dataTableOutput('List_AllGames')),
tabPanel('Backwards Compatible Now', DT::dataTableOutput('List_BackwardsCompatibleGames')),
tabPanel('Predicted Backwards Compatible', DT::dataTableOutput('List_PredictedBackwardsCompatible')),
navbarMenu("Publishers",
tabPanel('Most Likely 25',
helpText('Not including Games that Require Kinect or Peripherals'),
shiny::tableOutput('PublisherTop')),
tabPanel('Least Likely',
helpText('Not including Games that Require Kinect or Peripherals'),
shiny::tableOutput('PublisherBottom'))
),
tabPanel('Exclusives', DT::dataTableOutput('List_Exclusives')),
tabPanel('Has Xbox One Version', DT::dataTableOutput('List_HasXboxOneVersion')),
tabPanel('Kinect Games', DT::dataTableOutput('List_KinectGames'))
)
), # End of tabItem
tabItem(tabName = "Processing",
fluidPage(
tags$head(tags$style(HTML('
.content {
min-height: 250px;
padding: 0px;
padding-top:0px;
padding-right: 0px;
padding-bottom: 0px;
padding-left: 0px;
margin-right: 0px;
margin-left: 0px;
}
'))),
title = 'Xbox One Backwards Compatibility With The Xbox 360',
shiny::htmlOutput("Explanation", inline = TRUE)
# uiOutput(knitr::render_html())
) # End of fluidPage
# ), # End of tabItem
# tabItem(tabName = "AboutMe",
# fluidPage(
# # titlePanel("About Me"),
# mainPanel(
# shiny::htmlOutput("AboutMe", inline = TRUE)
# )
# )
) # End of tabItem
) # end of tabITems
)# end of dashboard body
)# end of dashboard page |
a22c6c3dd00ff21fa6c7b7aec3f7e184b135b850 | b951201cd94fc90a7e3fdb62ddc5215533e31abe | /drawing_raw_data.R | e648f6029eea3f23bf8d6d6ccbed56506ede407c | [] | no_license | omidi/Stochasticity_Sister_Cells | d6d203dc2d0b6ee0bdd146fa810d300969c0e386 | e5084b32064f97632bce31e5ce45d8fe376c4ec4 | refs/heads/master | 2021-01-09T20:53:37.458544 | 2016-06-20T16:07:07 | 2016-06-20T16:07:07 | 58,932,474 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,275 | r | drawing_raw_data.R | setwd('~/PycharmProjects/Stochasticity_Sister_Cells/')
# df = read.csv('~/Dropbox/Communication/Gene.Expression.Inheritance/Data 29.04.16/4.11 with mitosis.csv',
# header=FALSE)
require(RColorBrewer)
cols = brewer.pal(7, "Set1")
dest = "4.11_raw_data_plots"
# for (i in seq(1, dim(df)[2], by=2)) {
#
# if(dest!="") {
# fname = sprintf('%s/%d_cell_pairs.pdf', dest, i)
# } else {
# fname = sprintf('%d_cell_pairs.pdf', i)
# }
#
# pdf(fname, height = 6, width = 8)
# df2 = df[, c(i, i+1)]
# colnames(df2) = c("V1", "V2")
# y.range = range(df2, na.rm = TRUE)
# df2 = subset(df2, !(is.na(V1) & is.na(V2)) )
# times = seq(0, dim(df2)[1]*5 - 5, by=5 )
# par(mar=c(5,5,5,2))
# plot(times, df2$V1, col=cols[1],
# xlab = "time (hr)", ylab="Luminescence signal",
# cex.lab=1.5, cex.axis=1.4, xaxt='n', cex.main=2,
# main = i, ylim = y.range)
# axis(1, at=seq(0, max(times), by=120), labels=seq(0, max(times), by=120)/60 , cex.axis=1.5)
# lines(smooth.spline(times[!is.na(df2$V1)], df2$V1[!is.na(df2$V1)], spar = .3), col=cols[1], lwd=3)
# points(times, df2$V2, pch=2, col=cols[2])
# lines(smooth.spline(times[!is.na(df2$V2)], df2$V2[!is.na(df2$V2)], spar = .3), col=cols[2], lwd=3)
# dev.off()
# } |
e3af05f08072eecd21afb0dd569a806cb2582fa5 | 81d27c380d53de5258e56be5a240de9e954a229a | /src/deaths_averted_hospital/script.R | 4238835032b0e1cc79d9e8bcb149f6f3af92cd95 | [
"MIT"
] | permissive | mrc-ide/covid-vaccine-impact-orderly | 3145d6d9a817661d7094282dac94752eeeae9ed3 | eb325f1fea1c9ee5f2750d6567e5f6a0ba5fbfb4 | refs/heads/main | 2023-04-17T22:27:41.041072 | 2022-05-11T15:27:25 | 2022-05-11T15:27:25 | 410,044,956 | 4 | 3 | MIT | 2022-04-20T14:27:17 | 2021-09-24T17:16:03 | R | UTF-8 | R | false | false | 4,711 | r | script.R | if(!is.na(seed)){
set.seed(seed)
}
###Load data:
df_overall <- loadCounterfactualData(c("No Vaccines", "Baseline-Direct",
"Baseline-Direct & No Healthcare Surging",
"No Vaccines-No Healthcare Surging",
"Baseline-No Healthcare Surging"),
group_by = "date"
)
###Figure 1 daily deaths over time:
#sort data
df_sorted <- df_overall %>%
select(date, counterfactual, deaths_avg) %>%
rbind(df_overall %>%
select(date, baseline_deaths_avg) %>%
rename(deaths_avg = baseline_deaths_avg) %>%
unique() %>%
mutate(counterfactual = "Baseline")) %>%
pivot_wider(id_cols =date, names_from = counterfactual, values_from = deaths_avg)
#calculate levels, need to isolate vaccine impacts:
df_averted <- df_sorted %>%
transmute(
date = date,
averted_reduced_burden_hospital_max = `No Vaccines` - `Baseline`,
averted_reduced_burden_hospital_min = `No Vaccines-No Healthcare Surging` - `Baseline-No Healthcare Surging`,
averted_indirect_max = averted_reduced_burden_hospital_min,
averted_indirect_min = `No Vaccines-No Healthcare Surging` - `Baseline-Direct & No Healthcare Surging`,
averted_direct_max = averted_indirect_min,
averted_direct_min = rep(0, length(averted_direct_max))
) %>%
pivot_longer(cols = contains("averted"), names_to = c("mechanism", "bound"),
names_sep = "_(?![\\s\\S]*_)") %>%
pivot_wider(id_cols = c(date, mechanism), names_from = bound, values_from = value)
df_averted <- df_sorted %>%
transmute(
date = date,
averted_reduced_burden_hospital_indirect_max = `No Vaccines` - `Baseline`, #total deaths averted
averted_reduced_burden_hospital_direct_min = `No Vaccines-No Healthcare Surging` - `Baseline-No Healthcare Surging`, #these two bound deaths averted through hosptial admission reductions
#calculate deaths averted by direct and indirect effects in the absence of hospital burden
averted_indirect_max = averted_reduced_burden_hospital_direct_min,
averted_indirect_min = `No Vaccines-No Healthcare Surging` - `Baseline-Direct & No Healthcare Surging`,
averted_direct_max = averted_indirect_min,
averted_direct_min = rep(0, length(averted_direct_max)),
#split deaths averted by reduced burden into direct/indirect
averted_reduced_burden_hospital_indirect_min = (`No Vaccines` - `Baseline-Direct`) - #deaths averted by direct with both hospital reduction and direct
averted_direct_max + #subtract the deaths averted with no reduction in burden
averted_reduced_burden_hospital_direct_min, #scale up so area is correct
averted_reduced_burden_hospital_direct_max = averted_reduced_burden_hospital_indirect_min,
) %>%
pivot_longer(cols = contains("averted"), names_to = c("mechanism", "bound"),
names_sep = "_(?![\\s\\S]*_)") %>%
pivot_wider(id_cols = c(date, mechanism), names_from = bound, values_from = value) %>%
#rename and fitler for the plot
mutate(
mechanism = case_when(
# mechanism == "averted_direct" ~ "Protection against Disease",
# mechanism == "averted_indirect" ~ "Protection against Transmission and Infection",
# mechanism == "averted_reduced_burden_hospital_direct" ~
# "Reduction in healthcare burden\n(from Protection against Disease)",
# mechanism == "averted_reduced_burden_hospital_indirect" ~
# "Reduction in healthcare burden\n(from Protection against Transmission and Infection)"
mechanism == "averted_direct" ~ "Direct Protection",
mechanism == "averted_indirect" ~ "Indirect Protection",
mechanism == "averted_reduced_burden_hospital_direct" ~
"Reduced Healthcare Burden\n(Direct)",
mechanism == "averted_reduced_burden_hospital_indirect" ~
"Reduced Healthcare Burden\n(Indirect)"
)
) %>%
filter(date > "2021-01-01")
fig <-
ggplot(df_averted,
aes(x = date, ymin = min, ymax = max, fill = mechanism)) +
geom_ribbon(colour = "black") +
labs(
x = "Date",
y = "Median Deaths Averted by Vaccinations per day",
fill = "Deaths Averted By:"
) +
theme_pubr() +
scale_fill_manual(values =
c(
"Direct Protection" = "#FF9966BF", #17becf
"Indirect Protection" = "#3399CCBF", #98df8a
"Reduced Healthcare Burden\n(Direct)" = "#FF996640",
"Reduced Healthcare Burden\n(Indirect)" = "#3399CC40"
))
saveRDS(fig, "hospital_effects.Rds")
|
fb19846d73bd3d0bd20b721f1325b40a0b7f353b | efc4e708132e1543827ee12f0076540681f2c354 | /Plot1.R | d9cfbbab590ba3cac5ea672679ccf1860a483d1e | [] | no_license | cmauricio/DataPlotCoursera | d99c934d40c5389a0486e8ff6eb2368323a89899 | 87358bfc84871e4ae96e560d6bd20af02133bbe6 | refs/heads/master | 2021-03-12T20:21:49.229998 | 2015-07-12T18:57:11 | 2015-07-12T18:57:11 | 38,973,195 | 0 | 0 | null | null | null | null | ISO-8859-1 | R | false | false | 1,265 | r | Plot1.R | ## Data asignment for the Data Scientist Course in Coursera
## Developed by Carlos Mauricio Castaño Díaz
## R version: 3.2.1
## Platform: Windows 7. 64 bit
## RStudio version: 0.99.451
setwd("C:/Users/Mauro/Desktop/RAssignment") ## Setup work directory
household_power_consumption <- read.csv("C:/Users/Mauro/Desktop/RAssignment/household_power_consumption.txt", sep=";", na.strings="?") ## Import data sheet
attach(household_power_consumption) ##to ease the use of names
Data1207<-subset(household_power_consumption, household_power_consumption$Date=="1/2/2007") ## measurements from the first of february 2007
Data2207<-subset(household_power_consumption, household_power_consumption$Date=="2/2/2007") ## measurements from the second of february 2007
ExperimentalData<-rbind(Data1207,Data2207) ## matix containing the information of the two dates to be analysed
detach (household_power_consumption) ## Ends attach
attach(ExperimentalData)
hist(ExperimentalData$Global_active_power, col="red", main="Global Active Power", xlab="Global Active Power (kilowatts)", ylab="Frequency") ## Creates the histogram of the power use by days
dev.copy(png, file = "plot1.png") ## Creates the PNG file
dev.off() ## Closes the device
detach(ExperimentalData)
|
b4b82dfaf0bed7ea9b58a8d9a5fdbb4d33f55687 | 6f5408c66e329107478513deabdc27b19e676be4 | /hw05/hw05.R | bad37364011460f9121c99c26fed67e9f50d2a8a | [] | no_license | quyiwode/Data-Mining-in-R | 12095e6b00bf3e554893c85ae771a61f51f7cf97 | 4a2bf7503e17e676f863cde018af1f127a022001 | refs/heads/master | 2020-05-19T07:43:26.386518 | 2015-10-06T14:39:30 | 2015-10-06T14:39:30 | 42,493,297 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 6,802 | r | hw05.R | #############################
# < Yi Qu >
# STAT W4240
# Homework 05
# < Homework Due Date: Novemeber 25 >
#
# The following code use classfication trees and logistic regression
# to classify the federalist papers
#############################
#################
# Problem 4
#################
#----- START YOUR CODE BLOCK HERE -----#
gini = function(pm1){
return(pm1*(1-pm1)+(1-pm1)*pm1)
}
error = function(pm1){
n = length(pm1)
pm2 = 1 - pm1
pm = NULL
for(i in 1:n) {
if(pm1[i] - pm2[i] > 0)
pm[i] = pm2[i]
else
pm[i] = pm1[i]
}
return(pm)
}
entropy = function(pm1){
return(-pm1*log(pm1)-(1-pm1)*log(1-pm1))
}
pmk = seq(0,1,by = 0.01)
gini.pmk = gini(pmk)
error.pmk = error(pmk)
entropy.pmk = entropy(pmk)
plot(pmk,entropy.pmk,type="l",col='red',ylab="function(pmk)")
lines(pmk,error.pmk,type="l",col='blue')
lines(pmk,gini.pmk,type="l",col='green')
legend("bottom",c("cross-entropy","classification error","Gini index"),
col=c("red","blue","green"),lty=1)
#----- END YOUR CODE BLOCK HERE -----#
#################
# Problem 6a
#################
#----- START YOUR CODE BLOCK HERE -----#
# load("C:\\Users\\yi\\Desktop\\W4240\\hw05\\.RData")
ls()
#dim(dtm.hamilton.train)
#nrow(dtm.hamilton.train)
dtm.train <- rbind(dtm.hamilton.train, dtm.madison.train)
dtm.train.label <- matrix(nrow = nrow(dtm.train),ncol = 1)
dtm.train.label[1:nrow(dtm.train),1] <- 0
dtm.train.label[1:nrow(dtm.hamilton.train),1] <- 1
dtm.train.df<- cbind(dtm.train.label,dtm.train)
words <- as.vector(mydictionary[,1])
colnames(dtm.train.df) <- c("y", words)
dtm.train.df = data.frame(dtm.train.df)
#fix(dtm.train.df)
#class(dtm.train.df[,1])
dtm.test <- rbind(dtm.hamilton.test, dtm.madison.test)
test.num <- nrow(dtm.test)
hamilton.num <- nrow(dtm.hamilton.test)
madison.num <- nrow(dtm.madison.test)
dtm.test.label <- matrix(nrow = test.num,ncol = 1)
dtm.test.label[1:test.num,1] <- 0
dtm.test.label[1:hamilton.num,1] <- 1
dtm.test.df<- cbind(dtm.test.label,dtm.test)
colnames(dtm.test.df) <- c("y", words)
dtm.test.df = data.frame(dtm.test.df)
#fix(dtm.test.df)
#class(dtm.test.df[,2])
#library(rpart)
fit.6a = rpart(y ~ ., data=dtm.train.df, parms = list(split='gini'))
out.6a = predict(fit.6a, dtm.test.df, type="class")
plot(fit.6a)
text(fit.6a, use.n = F)
correct = (sum(out.6a==0 & dtm.test.df$y==0)+ sum(out.6a==1 & dtm.test.df$y==1))/test.num
#0.962963 26/27
false.positive <- sum(out.6a==1 & dtm.test.df$y ==0)/madison.num #0.09 #1/11
false.negative <- sum(out.6a==0 & dtm.test.df$y ==1)/hamilton.num #0
#----- END YOUR CODE BLOCK HERE -----#
#################
# Problem 6b
#################
#----- START YOUR CODE BLOCK HERE -----#
fit.6b = rpart(y ~ ., data=dtm.train.df, parms = list(split='information'))
out.6b = predict(fit.6a, dtm.test.df, type="class")
plot(fit.6b)
text(fit.6b, use.n = F)
correct = (sum(out.6b==0 & dtm.test.df$y==0)+ sum(out.6b==1 & dtm.test.df$y==1))/test.num
#0.962963 26/27
false.positive <- sum(out.6b==1 & dtm.test.df$y ==0)/madison.num #
false.negative <- sum(out.6b==0 & dtm.test.df$y ==1)/hamilton.num #
# do different between two models.
#----- END YOUR CODE BLOCK HERE -----#
#################
# Problem 7a
#################
#----- START YOUR CODE BLOCK HERE -----#
#dim(dtm.test.df)
n <- ncol(dtm.test.df)
dtm.train.scaled.df <- dtm.train.df
train.mean <- colMeans(dtm.train.df[,2:n])
train.sd <- apply(dtm.train.df[,2:n],2,sd)
dtm.train.scaled.df[,2:n] <- scale(dtm.train.df[,2:n])
dtm.train.scaled.df[is.na(dtm.train.scaled.df)] <- 0
fix(dtm.train.scaled.df)
save(dtm.train.scaled.df,file="train_scale.Rda")
#sum(is.na(dtm.train.scaled.df)==TRUE) # make sure NAN all gone
fix(dtm.test.df)
dtm.test.scaled.df <- dtm.test.df
dtm.test.scaled.df[,2:n] <- scale(dtm.test.df[,2:n],
center = train.mean, scale = train.sd)
dtm.test.scaled.df[is.na(dtm.test.scaled.df)] <- 0
fix(dtm.test.scaled.df)
save(dtm.test.scaled.df,file="test_scale.Rda")
# no only after centering and scaling, we can treat every X samely.
#----- END YOUR CODE BLOCK HERE -----#
#################
# Problem 7b
#################
#----- START YOUR CODE BLOCK HERE -----#
install.packages("glmnet", repos = "http://cran.us.r-project.org")
library(glmnet)
# class(dtm.train.scaled.df)
dtm.train.scaled.mat <- data.matrix(dtm.train.scaled.df)
cv.fit.ridge <- cv.glmnet(dtm.train.scaled.mat[,2:n],dtm.train.scaled.mat[,1],
alpha=0, family="binomial")
best.lambda <- cv.fit.ridge$lambda.min # 3.14008
correct.ridge = (sum(pred.ridge==0 & dtm.test.df$y==0)+ sum(pred.ridge==1 & dtm.test.df$y==1))/test.num
false.positive.ridge <- sum(pred.ridge==1 & dtm.test.df$y ==0)/madison.num #
false.negative.ridge <- sum(pred.ridge==0 & dtm.test.df$y ==1)/hamilton.num #
correct.ridge
#[1] 0.5925926
false.positive.ridge
#[1] 1
false.negative.ridge
#[1] 0
fit.ridge <- glmnet(dtm.train.scaled.mat[,2:n],dtm.train.scaled.mat[,1],
alpha=0,family="binomial")
index.best <- which(cv.fit.ridge$lambda == cv.fit.ridge$lambda.min)
sort.ridge.beta <-sort(abs(fit.ridge$beta[,index.best]),decreasing = TRUE)
sort.ridge.beta[1:10]
februari upon whilst within sever X1783 form
0.01667850 0.01572522 0.01428038 0.01367439 0.01344405 0.01302053 0.01193143
member X5 although
0.01168189 0.01153821 0.01127392
plot(fit.ridge,main="Ridge")
#----- END YOUR CODE BLOCK HERE -----#
#################
# Problem 7c
#################
#----- START YOUR CODE BLOCK HERE -----#
cv.fit.lasso <- cv.glmnet(dtm.train.scaled.mat[,2:n],dtm.train.scaled.mat[,1],
alpha=1,family="binomial")
best.lambda <- cv.fit.lasso$lambda.min # 0.01155041
best.lambda
pred.lasso <- predict(cv.fit.lasso,newx=dtm.test.scaled.mat[,2:n],
s=best.lambda,type="class")
correct.lasso = (sum(pred.lasso==0 & dtm.test.df$y==0)+ sum(pred.lasso==1 & dtm.test.df$y==1))/test.num
false.positive.lasso <- sum(pred.lasso==1 & dtm.test.df$y ==0)/madison.num #
false.negative.lasso <- sum(pred.lasso==0 & dtm.test.df$y ==1)/hamilton.num #
correct.lasso
#[1] 0.8888889
false.positive.lasso
#[1] 0.1818182
false.negative.lasso
#[1] 0.0625
fit.lasso <- glmnet(dtm.train.scaled.mat[,2:n],dtm.train.scaled.mat[,1],
alpha=1,family="binomial")
ind.best <- which(cv.fit.lasso$lambda == cv.fit.lasso$lambda.min)
sort.lasso.beta <-sort(abs(fit.lasso$beta[,ind.best]),decreasing = TRUE)
sort.lasso.beta[1:10]
whilst februari upon form although within sever lesser
1.7549559 1.6178042 1.3466915 0.7008493 0.6751041 0.5129032 0.4357153 0.4222712
ad anim
0.3212790 0.2833942
plot(fit.lasso, main = "Lasso")
# The words are different, The coefficients of ridge is smaller than coefficient
# of lasso, because lasso will turn most of beta to 0.
#----- END YOUR CODE BLOCK HERE -----#
##########################################
#################
# End of Script
#################
|
3e6411aa53b1deff63b516014102d2fecfaa2b48 | 8e6464eea79b07d65a72b38744dd317950991e70 | /Figure3c-d.R | b4a6882abddb2e7aeb41d6cd7882c4778c273e5f | [] | no_license | zm-git-dev/LDM_RNAseq_ChIPseq_NSCLC | 4c9d0253b17e26e9bf66f28ca2299a3a5d2772ce | 5d33fded3e9b24bb7c3cff2c31441d7266174be8 | refs/heads/main | 2023-03-28T09:50:22.883957 | 2021-04-04T02:31:06 | 2021-04-04T02:31:06 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,822 | r | Figure3c-d.R | ###Running RNA-seq analysis###
library("DESeq2")
library("ggplot2")
library("EnsDb.Hsapiens.v75")
library("AnnotationDbi")
library("ComplexHeatmap")
library("circlize")
library("ChIPseeker")
library("TxDb.Hsapiens.UCSC.hg19.knownGene")
library("enrichplot")
library("clusterProfiler")
library("org.Hs.eg.db")
source("RNA-seq_DEGsAnalysis.R")
source("Figure2b-c.R")
###Getting ChIP-seq analysis results###
altered_TSS <- "data/Tumor-altered-overlapTSS.bed"
txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene
peakAnno <- annotatePeak(altered_TSS, tssRegion=c(-1000, 1000),TxDb=txdb, annoDb="EnsDb.Hsapiens.v75")
altered.TSS.genes <- na.exclude(as.data.frame(peakAnno)$geneId)
dup.genes <- altered.TSS.genes[duplicated(altered.TSS.genes) == TRUE]
altered_TSS.df <- as.data.frame(peakAnno)
altered.TSS.genes <- unique(na.exclude(as.data.frame(peakAnno)$geneId))
###Making heatmap###
Sig.LUAD.genes <- na.omit(SigDEG.LUAD$entrezid)
Sig.LUSC.genes <- na.omit(SigDEG.LUSC$entrezid)
altered.TSS.genes.DEGs <- union(intersect(Sig.LUAD.genes,altered.TSS.genes), intersect(Sig.LUSC.genes,altered.TSS.genes))
altered.TSS.genes.DEGs.data <- subset(res.rna.all, res.rna.all$entrezid %in% altered.TSS.genes.DEGs)
altered.TSS.genes.DEGs.count <- subset(norm.count.RNA, rownames(norm.count.RNA) %in% rownames(altered.TSS.genes.DEGs.data))
altered.TSS.genes.DEGs.count <- altered.TSS.genes.DEGs.count[,c(11:30)]
colnames(altered.TSS.genes.DEGs.count) <- colnames(norm.count.RNA[,c(11:30)])
altered.TSS.genes.DEGs.ezid <- as.data.frame(na.omit(mapIds(EnsDb.Hsapiens.v75,keys = altered.TSS.genes.DEGs,column = "GENEID", keytype = "ENTREZID", multiVals = "first")))
altered.TSS.df <- as.data.frame(peakAnno)
altered.TSS.df$status <- ""
altered.TSS.df$status[1:188] <- "gained.TSS"
altered.TSS.df$status[189:444] <- "loss.TSS"
#Checking gene names
a1 <- unique(subset(altered.TSS.df, altered.TSS.df$geneId %in% altered.TSS.genes.DEGs))[,c(15,20)]
a1$entrez <- mapIds(EnsDb.Hsapiens.v75,keys = a1$geneId,column = "GENEID", keytype = "ENTREZID", multiVals = "first")
a2 <- unique(subset(a1, a1$entrez %in% rownames(altered.TSS.genes.DEGs.count)))
subset(altered.TSS.genes.DEGs.count, !(rownames(altered.TSS.genes.DEGs.count) %in% a2$entrez))
b <- data.frame("729238","loss.TSS","ENSG00000185303")
colnames(b) <- colnames(a2)
a3 <- rbind(a2,b)
a3 <- a3[,c(3,2)]
#There are 311 (NSCLC subtype specific) DEGs with their TSSs overlaped with tumor-altered H3K4me3 regions as shown in 'altered.TSS.genes.DEGs.data'
altered.TSS.genes.DEGs.type <- data.frame(type = a3[,2])
rownames(altered.TSS.genes.DEGs.type) <- a3$entrez
altered.TSS.genes.DEGs.type <- altered.TSS.genes.DEGs.type[match(rownames(altered.TSS.genes.DEGs.count), rownames(altered.TSS.genes.DEGs.type)), ]
#Making Figure 3c
peak_type_col <- c("#91cf60","#f7fcb9")
names(peak_type_col) <- c("gained.TSS","loss.TSS")
typeRNA = c(rep("Normal", 10), rep("Tumor",10))
CelltypeRNA = c(rep(c(rep("squamous", 4),rep("adeno", 6)),2))
haRNA = HeatmapAnnotation(df = data.frame(Sample = typeRNA, Case = CelltypeRNA),
col = list(Sample = c("Normal" = "#3288bd", "Tumor" = "#d53e4f"),
Case = c("squamous" = "#fc8d59", "adeno" = "#b35806")),
annotation_name_side = "left",
annotation_legend_param = list(
Sample = list(nrow = 2),
Case = list(nrow = 2)))
scale.chip <- as.data.frame(t(apply(as.matrix(altered.TSS.genes.DEGs.count),1, scale)),stringsAsFactors = FALSE)
colnames(scale.chip) <- colnames(altered.TSS.genes.DEGs.count)
hm1 <- Heatmap(scale.chip, name = "z-score",col = colorRamp2(c(-0.7,1.2,2.7,4.2,5.7), c("black", "red", "orange","yellow","green")),
top_annotation = haRNA, cluster_columns = T, column_names_gp = gpar(fontsize = 8), clustering_distance_rows = "euclidean",
show_row_names = FALSE, show_column_names = TRUE, row_km = 2, heatmap_legend_param = list(direction = "horizontal"))
hm2 <- Heatmap(altered.TSS.genes.DEGs.type, name = "Type", show_row_names = FALSE,
show_column_names = FALSE, col = peak_type_col,heatmap_legend_param = list(nrow = 2),
width = unit(5, "mm"))
#svg("Figure3c.svg", width = 7, height = 7.5)
draw(hm1 + hm2, merge_legend = T, heatmap_legend_side = "bottom", annotation_legend_side = "bottom")
#dev.off()
#Making Figure 3d
geneList <- altered.TSS.genes.DEGs.data$log2FoldChange
names(geneList) <- altered.TSS.genes.DEGs.data$entrezid
kk <- enrichKEGG(gene = altered.TSS.genes.DEGs,
organism = 'hsa',
pvalueCutoff = 0.05)
edox <- setReadable(kk, 'org.Hs.eg.db', 'ENTREZID')
#svg("Figure3d.svg", width = 9, height = 7.5)
cnetplot(edox, foldChange=geneList)
#dev.off() |
9de2eb76bde7e2ea839b5f511037d2328bdb6042 | 7f9a64c8bffb593b2fc77b990345512b7021235b | /Arp53D_populationCage_plotModellingResults.R | 2f1b90f2f7e41b6e030431eea63fbd49966eb359 | [] | no_license | jayoung/Arp53D_popCage | e69a99bdc7a23081026868c176442178ecd18499 | 8f6d9e77a2a693bc895ec21467e703328e574d3c | refs/heads/main | 2023-08-18T12:01:42.655882 | 2022-12-07T02:22:28 | 2022-12-07T02:22:28 | 373,989,515 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,260 | r | Arp53D_populationCage_plotModellingResults.R | library(dplyr)
library(tidyr)
library(ggplot2)
library(ggpubr)
library(scales)
library(grid)
library(gridExtra)
rm(list=ls())
setwd("/Volumes/malik_h/user/jayoung/forOtherPeople/forCourtney/Arp53D_population_cage_experiments/Arp53D_popCage")
load("Rdata_files/Arp53D_populationCage_modellingOutput.Rdata")
source("Arp53D_populationCage_functions.R")
####### make a plot for the paper:
#### get text labels that show the parameters of the best models
getModelCoefficientsAsLabel_v2 <- function(modelResults) {
paste("best model:",
"\n Fwt = ",modelResults[1,"selectionWThom"],
"\n Fhet = ",modelResults[1,"selectionHet"],
"\n Fko = ",modelResults[1,"selectionKOhom"],
"\n MAE = ",round(modelResults[1,"fitScore"],digits=3), sep="")
}
bestModelLabels_allRegimesFitTypes_v2 <- lapply(bestModelsAllRegimesSeveralFitTypes, function(x) {
lapply(x, getModelCoefficientsAsLabel_v2)
})
bestModelLabels_allRegimesFitTypes_v2_df <- lapply(names(bestModelLabels_allRegimesFitTypes_v2), function(thisSelectionRegime) {
theseLabels <- bestModelLabels_allRegimesFitTypes_v2[[thisSelectionRegime]]
theseLabels_df <- data.frame(fitType=names(theseLabels), label=unlist(theseLabels,use.names = FALSE))
theseLabels_df[,"selectionRegime"] <- thisSelectionRegime
return(theseLabels_df)
})
bestModelLabels_allRegimesFitTypes_v2_df <- do.call("rbind",bestModelLabels_allRegimesFitTypes_v2_df) %>%
select(selectionRegime,fitType,label) %>% # reorder columns
mutate(generation=0,WThom=0.85) %>% # add columns that will specify label position on plots
mutate(selectionRegime=factor(selectionRegime, levels=allSelectionRegimes))
facetNameReplacements <- c(
"het_equalsWThom" = "Fhet = Fwt",
"het_intermediate" = "Fhet = intermediate",
"het_equalsKOhom" = "Fhet = Fko"
)
plotFitnessModelling_allRegimes_justMAE <- infinitePopulation_multipleSelectiveRegimesFineGrain %>%
filter( ( (selectionKOhom*1000) %% 25)==0 ) %>% ## this is so I don't plot every single increment of 0.001 for selectionKOhom (instead, I plot increments of 0.025).## I thought I could use modulo to filter for increments, but there is something weird about floating point arithmetic that means it doesn't work. See https://stackoverflow.com/questions/13614749/modulus-bug-in-r
# e.g. 1 %% 0.2 should be 0, but on my Mac R thinks it is 0.2
# so instead I will multiply by 1000 first, and then take the modulo
ggplot(aes(x=generation, y=WThom)) +
geom_line(aes(group=selectionKOhom, colour=selectionKOhom)) +
facet_grid(cols=vars(selectionRegime), labeller=labeller(selectionRegime=facetNameReplacements)) +
theme_classic() +
coord_cartesian(xlim=c(0,30)) +
scale_colour_distiller(palette = "Spectral", direction=1,
guide = guide_colourbar(title="Fko")) +
labs(x="Generation", y="Freq WT homozygotes") +
## the gray line showing best model
geom_line(data=(bestModelsAllRegimesSeveralFitTypesCombined %>% filter(fitType=="meanAbsErr")),
aes(x=generation,y=WThom), color="gray",lwd=2) +
## the REAL data:
geom_point(data=arp53d, aes(x=generation,y=freqWThom)) +
## old - I was including means at each generation
#stat_summary(data=arp53d, aes(x=generation,y=freqWThom), fun="mean",
# geom="point", shape=5, size=3,
# colour = "black", fill="white") +
## dashed lines for the REAL data
geom_line(data=arp53d, aes(x=generation,y=freqWThom, group=bottle), lty=2) +
## gray boxes showing coefficients for best models
geom_label(data=(bestModelLabels_allRegimesFitTypes_v2_df %>% filter(fitType=="meanAbsErr")),
aes(label=gsub("fitScore","MAE",label)),
colour="gray60", hjust = 0, #vjust = 1, label.padding=unit(0.25, "lines"),
size=1.75, family = "mono") +
theme(panel.spacing = unit(2, "lines"),
strip.background = element_blank(),
strip.text.x = element_text(size = 12)
)
plotFitnessModelling_allRegimes_justMAE
ggsave(file="plots/fitnessModelling_allRegimes_justMAE.pdf",
plotFitnessModelling_allRegimes_justMAE,
width=8, height=2.75, device="pdf")
|
e782acc2724c158fb38d8e739c5120e74fd0de97 | 82f9c1b5dc7ff6b2f48bf83a19ca79b9cd9391f6 | /man/getWaterML2Data.Rd | 35655e749eb88d202b5a251526b76ee9daac0c97 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain-disclaimer"
] | permissive | bjsomalley/dataRetrieval | 1810a981f34c8a37acd59c704c8765cc0281831a | f775a8f9abbc07ff2924d2e48c35b52c125c7bc5 | refs/heads/master | 2021-01-18T07:52:02.826815 | 2014-08-05T22:00:56 | 2014-08-05T22:00:56 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 702 | rd | getWaterML2Data.Rd | % Generated by roxygen2 (4.0.1): do not edit by hand
\name{getWaterML2Data}
\alias{getWaterML2Data}
\title{Function to return data from the WaterML2 data}
\usage{
getWaterML2Data(obs_url)
}
\arguments{
\item{obs_url}{string containing the url for the retrieval}
}
\value{
mergedDF a data frame containing columns agency, site, dateTime, values, and remark codes for all requested combinations
}
\description{
This function accepts a url parameter for a WaterML2 getObservation
}
\examples{
URL <- "http://webvastage6.er.usgs.gov/ogc-swie/wml2/dv/sos?request=GetObservation&featureID=435601087432701&observedProperty=00045&beginPosition=2012-01-01&offering=Sum"
dataReturned3 <- getWaterML2Data(URL)
}
|
4d8d6e48d44acfc5a71d7a2c428b80d64ba2ce5c | 4687684b530d87f13130e0bb3d1446dacfd08af9 | /R/plotFunction.R | 30004d9b3d573f041f523232a33d570181be49bb | [] | no_license | MarieEtienne/MixtLiP | ce576354901513d2d49dde88ddb2203309e28be8 | 5a41a0183223a8d17f0a2cea583fa533e5a09c66 | refs/heads/master | 2021-01-12T10:25:21.951744 | 2016-12-14T10:52:35 | 2016-12-14T10:52:35 | 76,445,613 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,294 | r | plotFunction.R | plot4dimData <- function(Y, Z = NULL, names=NULL, cex=1) {
if (is.null(Z)) {
Z = rep(1, nrow(Y))
}
if(is.null(names)){
names<- paste('Var', 1:ncol(Y))
}
par(mfcol = c(3,3))
plot(Y[,1], Y[,2], col = Z, xlab='',ylab=names[2], cex=cex)
plot(Y[,1], Y[,3], col = Z, xlab='',ylab=names[3], cex=cex)
plot(Y[,1], Y[,4], col = Z, xlab=names[1],ylab=names[4], cex=cex)
plot(
x = 1, axes = F, col = 0, xlab = '', ylab = '', cex=cex
)
plot(Y[,2], Y[,3], col = Z, xlab='', ylab='', cex=cex)
plot(Y[,2], Y[,4], col = Z, xlab=names[2], ylab='', cex=cex)
plot(
x = 1, axes = F, col = 0, xlab = '', ylab = '', cex=cex
)
plot(
x = 1, axes = F, col = 0, xlab = '', ylab = '', cex=cex
)
plot(Y[,3], Y[,4], col = Z, xlab=names[3], ylab='', cex=cex)
}
plot3dimData <- function(Y, Z = NULL, names=NULL, cex=1, pch=1) {
if (is.null(Z)) {
Z = rep(1, nrow(Y))
}
if(is.null(names)){
names<- paste('Var', 1:ncol(Y))
}
par(mfcol = c(2,2))
plot(Y[,1], Y[,2], col = Z, xlab='',ylab=names[2], cex=cex, pch=pch)
plot(Y[,1], Y[,3], col = Z,ylab=names[3], xlab=names[1], cex=cex, pch=pch)
plot(
x = 1, axes = F, col = 0, xlab = '', ylab = '', cex=cex, pch=pch
)
plot(Y[,2], Y[,3], col = Z, ylab='', xlab=names[2], cex=cex, pch=pch)
}
|
65955ad9514258ac24e227b7b3f947d367d5a504 | 794863d2e9e26424a04079a91c3a23063bdb4f8e | /R/GARCHselection.R | e1c775d5ec686cb34d7094e52b460382f478ba80 | [] | no_license | GabauerDavid/ConnectednessApproach | ef768e64e0bc458ad180bac6b667b3fe5662f01d | 0ca4799a2f5aa68fdd2c4a3e8a2e0e687d0a9b17 | refs/heads/main | 2023-08-09T07:23:45.002713 | 2023-07-27T22:57:04 | 2023-07-27T22:57:04 | 474,462,772 | 47 | 20 | null | 2023-03-12T04:22:26 | 2022-03-26T20:47:15 | R | UTF-8 | R | false | false | 3,769 | r | GARCHselection.R |
#' @title Univariate GARCH selection criterion
#' @description This function estimates and evaluates a combination of GARCH models with different distributions and suggests the best GARCH models among all alternatives given some test statistics
#' @param x zoo data matrix
#' @param distributions Vector of distributions
#' @param models Vector of GARCH models
#' @param ar AR(p)
#' @param ma MA(q)
#' @param prob The quantile (coverage) used for the VaR.
#' @param conf.level Confidence level of VaR test statistics
#' @param lag Lag length of weighted Portmanteau statistics
#' @return Get optimal univariate GARCH model specification
#' @importFrom stats bartlett.test coef fitted fligner.test integrate qnorm quantile residuals sd sigma var.test
#' @references
#' Ghalanos, A. (2014). rugarch: Univariate GARCH models, R package version 1.3-3.
#'
#' Antonakakis, N., Chatziantoniou, I., & Gabauer, D. (2021). The impact of Euro through time: Exchange rate dynamics under different regimes. International Journal of Finance & Economics, 26(1), 1375-1408.
#' @author David Gabauer
#' @export
GARCHselection = function(x, distributions=c("norm","snorm","std","sstd","ged","sged"), models=c("sGARCH","eGARCH","gjrGARCH","iGARCH","TGARCH","AVGARCH","NGARCH","NAGARCH","APARCH","ALLGARCH"), prob=0.05, conf.level=0.90, lag=20, ar=0, ma=0) {
message("A dynamic version of the optimal univariate GARCH selection procedure is implemented according to:\n Antonakakis, N., Chatziantoniou, I., & Gabauer, D. (2021). The impact of Euro through time: Exchange rate dynamics under different regimes. International Journal of Finance & Economics, 26(1), 1375-1408.")
if (!is(x, "zoo")) {
stop("Data needs to be of type 'zoo'")
}
GARCH_IC = matrix(Inf, nrow=length(distributions), ncol=length(models))
colnames(GARCH_IC) = models
rownames(GARCH_IC) = distributions
spec_list = list()
table_list = list()
for (i in 1:length(models)) {
spec_list[[i]] = list()
table_list[[i]] = list()
for (j in 1:length(distributions)) {
spec_list[[i]][[j]] = list()
}
names(spec_list[[i]]) = distributions
}
names(spec_list) = names(table_list) = models
for (j in 1:length(models)) {
message(paste0("-",models[j]))
for (i in 1:length(distributions)) {
message(paste0("--",distributions[i]))
if (models[j] %in% c("AVGARCH","TGARCH","APARCH","NAGARCH","NGARCH","ALLGARCH")) {
ugarch.spec = rugarch::ugarchspec(mean.model=list(armaOrder=c(ar,ma)),
variance.model=list(model="fGARCH", submodel=models[j], garchOrder=c(1,1)),
distribution.model=distributions[i])
} else {
ugarch.spec = rugarch::ugarchspec(mean.model=list(armaOrder=c(ar,ma)),
variance.model=list(model=models[j], garchOrder=c(1,1)),
distribution.model=distributions[i])
}
ugarch.fit = rugarch::ugarchfit(ugarch.spec, data=x, solver="hybrid", solver.list=list(outer.iter=10, inner.iter=1000, eval.se=FALSE, tol=1e-12))
if (ugarch.fit@fit$convergence==0) {
fit = GARCHtests(ugarch.fit, prob=prob, conf.level=conf.level, lag=lag)
GARCH_IC[i,j] = fit$InformationCriterion
spec_list[[models[j]]][[distributions[i]]] = ugarch.spec
table_list[[j]][[distributions[i]]] = fit
}
}
}
GARCH_selection = which(GARCH_IC==min(GARCH_IC),arr.ind=TRUE)
best_ugarch = spec_list[[GARCH_selection[2]]][[GARCH_selection[1]]]
best_table = table_list[[GARCH_selection[2]]][[GARCH_selection[1]]]
return = list(best_ugarch=best_ugarch, best_table=best_table, GARCH_IC=GARCH_IC, spec_list=spec_list, table_list=table_list)
}
|
a3c3dab5092e7b5cf9343d8406b8866741737de9 | 57ece4e522fd10bf49f001c6b2caedbb07965068 | /run_analysis.R | 8086a8ed38855fc0fc4cbd46bd892d93218e2af1 | [] | no_license | SKelliher/DataCleaningAssignment | 74846b11a4af27c5961a2b037e46db3d14d5069f | e8c8c820913d50ed266735422e802ae3327afffc | refs/heads/master | 2021-01-20T17:15:38.585875 | 2016-07-10T21:31:45 | 2016-07-10T21:31:45 | 63,018,069 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 2,192 | r | run_analysis.R | # Clear workspace variables
rm(list=ls())
# Check if subdirectory "dataset" exists
if (!file.exists("dataset")) {dir.create("dataset")}
# Source data URL
URL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
# Assign local name for zip archive
ziparchive = "UCI HAR Dataset.zip"
# Download stage
message("Download zip archive")
# Using Windows
download.file(URL, destfile=ziparchive)
# Other OS
# download.file(URL, destfile=ziparchive, method = "curl")
# Record download date
dateDownloaded <- date()
message("Unzip the archive to subdirectory dataset")
unzip(ziparchive, exdir="dataset")
message("Load column and activity labels")
features <- read.table('dataset/UCI HAR Dataset/features.txt',header=FALSE)[[2]]
activity_labels <- read.table('dataset/UCI HAR Dataset/activity_labels.txt',header=FALSE, col.names=c("actNumber", "activity"))
message("Extract training datasets as tables")
x_train <- read.table("dataset/UCI HAR Dataset/train/X_train.txt") #columns correspond to features labels
y_train <- read.table("dataset/UCI HAR Dataset/train/y_train.txt", col.names=c("actNumber"))
subject_train <- read.table("dataset/UCI HAR Dataset/train/subject_train.txt",col.names=c("subject"))
message("Extract test datasets as tables")
x_test <- read.table("dataset/UCI HAR Dataset/test/X_test.txt")
y_test <- read.table("dataset/UCI HAR Dataset/test/y_test.txt", col.names=c("actNumber"))
subject_test <- read.table("dataset/UCI HAR Dataset/test/subject_test.txt",col.names=c("subject"))
message("Merge training and test tables")
x_merge <- rbind(x_train, x_test)
y_merge <- rbind(y_train, y_test)
subject_merge <- rbind(subject_train, subject_test)
# Assign column names
colnames(x_merge) <- features
# Merge datasets
UCIdataset <- cbind(subject_merge, y_merge, x_merge)
# Ordered summary set with the average of each variable for each activity and each subject.
UCIsummary<-aggregate(. ~ subject + actNumber, UCIdataset, mean)
UCIsummary<-UCIsummary[order(UCIsummary$subject,UCIsummary$actNumber),]
write.table(UCIsummary, file = "SummarizedDataset.csv",row.name=FALSE,sep=",")
|
a4fc175e9d0e2ec27b9b8041e3e07471722321c7 | dfe533f87566e7d3da51d58ff74e0a1200572300 | /Shiny_Richard/gina-trouble-shoot.R | 4cf5da2635c802296fa92ab884e3f73246503ee5 | [] | no_license | Agron508/Repository_2020 | 859c9072f8609ebab52019ad1d21386ece9d0e26 | 1273277ce10fad7831a5476a0759b53162e6e69c | refs/heads/master | 2020-12-29T07:34:58.107010 | 2020-05-06T21:13:05 | 2020-05-06T21:13:05 | 238,516,619 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,041 | r | gina-trouble-shoot.R | #This is my app to edit
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(tidyverse)
library(janitor)
library(scales)
library(lubridate)
library(shinythemes)
dat2 <- read_csv("data/tidy/condensed.csv") %>%
filter(mol_pho < 0.002) %>%
filter(hour >= 6, hour <= 20) %>%
mutate(
wl_bins = (wavelength %/% 10) * 10,
hour2 = trunc(hour / 2) * 2,
energy = mol_pho * 6.022E23 * (6.63E-19 * 3E8) / wavelength / 1E-9,
month_lab = month(month, label = T)
) %>%
select(month_lab, wl_bins, hour2, mol_pho, energy) %>%
pivot_longer(mol_pho:energy) %>%
group_by(month_lab, hour2, wl_bins, name) %>%
summarise(val_sum = sum(value, na.rm = TRUE)) %>%
ungroup() %>%
mutate(hour2 = paste0(hour2, "-", hour2+2)) %>%
mutate(mycolor = ifelse(
wl_bins < 380, "thistle",
ifelse(wl_bins < 440, "purple4",
ifelse(wl_bins < 490, "blue",
ifelse(wl_bins < 500, "lightblue",
ifelse(wl_bins < 570, "green4",
ifelse(wl_bins < 590, "yellow",
ifelse(wl_bins < 630, "orange",
ifelse(wl_bins < 740, "red", "darkred")
)
)
)
)
)
)
)
)
mycolor_vct <-
dat2 %>%
select(mycolor) %>%
unique() %>%
pull()
dat2 %>%
mutate(mycolor = factor(mycolor, levels = mycolor_vct)) %>%
filter(month_lab == "Jul") %>%
filter(name == "mol_pho") %>%
ggplot(aes(x = wl_bins,y = val_sum)) +
geom_col(aes(fill = mycolor)) +
facet_wrap(~hour2) +
labs(x = "wavelength (nm)",
y = bquote('photon flux '(number/sm^2)),
title = "Photon Flux Over Next Two Hours") +
scale_fill_manual(values = mycolor_vct)
|
25c19caf0862a9a4cf7bafdd3cd0a443aa71c7e0 | 4a636d9dbd819640c13ed6ad600fa41fe736356d | /man/Modelcharts.Rd | dd262f73798426090b7e27e8d176c9b7a84dda49 | [] | no_license | cran/Modelcharts | 87c6f7f6f2c6e904c2f9ae48dc98bd36df437ef0 | e3231f7011d32308e92f0688c05c6ab437af57cb | refs/heads/master | 2021-04-03T09:03:48.415112 | 2018-03-13T10:07:18 | 2018-03-13T10:07:18 | 125,039,178 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 653 | rd | Modelcharts.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Modelcharts.R
\docType{package}
\name{Modelcharts}
\alias{Modelcharts}
\alias{Modelcharts-package}
\title{Gain Chart and Lift Chart \cr}
\description{
This Package provides two important functions for producing Gain chart and Lift chart for any classification model.
}
\section{GAIN_CHART()}{
Creates a gain chart based on calculated probability values and actual outcome.
}
\section{LIFT_CHART()}{
creates a lift chart based on calculated probability values and actual outcome.
}
\seealso{
\code{\link{GAIN_CHART}}, \code{\link{LIFT_CHART}}
}
|
984da32ff6717714cf645d2fd5a22c61634f7f8d | ed43c0b1500ce9849c27c3e241b6df4c1a52b8ca | /man/load_data.Rd | b3e3ea40e94dfb2d0f285111d2ba5cf54d2fdc87 | [] | no_license | akastrin/sarcoid-microbiome-paper | 6b97ba60a96dad83885793cba8cc943fe5121426 | 6d19e284fc89a9b952fd21ca7e1f7042d737578c | refs/heads/master | 2020-03-28T12:24:34.027376 | 2017-07-20T12:06:36 | 2017-07-20T12:06:36 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 457 | rd | load_data.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/load_data.R
\name{load_data}
\alias{load_data}
\title{Load datasets.}
\usage{
load_data(set = c("A", "B", "C", "DE"), data = c("16S", "ITS", "virome",
"WGS"), data_fp = opts$data_fp)
}
\arguments{
\item{set}{the sample set in question (of A-C, DE)}
\item{data}{the data type (of 16S, ITS, virome, or WGS)}
\item{data_fp}{path to data files}
}
\description{
Load datasets.
}
|
dbc02a2ecb56154d82c9578a749d9768fb9c4955 | a3769c8719aa41fce75f203ffcf02f485626cceb | /data-raw/df-abs-ROX-data.R | e37ffb70453b1bd6c75de00e9be506876d1d8dd9 | [
"MIT"
] | permissive | JPSieg/MeltR | e2af7222f6755be076005e9100a8ded3726580be | d1ce870082194de47ca54a3a0d470548f723a2e8 | refs/heads/master | 2023-04-13T00:54:44.703450 | 2023-03-28T17:29:13 | 2023-03-28T17:29:13 | 262,172,873 | 7 | 1 | null | 2022-07-12T13:20:22 | 2020-05-07T22:37:27 | R | UTF-8 | R | false | false | 165 | r | df-abs-ROX-data.R | ## code to prepare `df.abs.ROX.data` dataset goes here
df.abs.ROX.data = read.csv("data/js3047_ROX_data.csv")
usethis::use_data(df.abs.ROX.data, overwrite = TRUE)
|
50e676289bffa5fe196e9c3f8ae42ea2cba5baaa | b718ca150ca94783df2bbfacd42e93548ada0ba5 | /xbrl.R | 0bf5a3550198e9d502b7c025c83c21f007d0a253 | [] | no_license | PaulMaley/Toba | 11f6901a15d89321fe7a31325e860494171a344e | cbe7355ed7e16a436ba6142d9b5f04419832ad00 | refs/heads/master | 2021-01-19T03:29:07.866534 | 2017-04-17T09:26:57 | 2017-04-17T09:26:57 | 87,316,067 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 561 | r | xbrl.R | library('XBRL')
library('finstr') ## needs package DBI, assertthat, tibble
options(stringsAsFactors = FALSE)
## Link to Edgar - Serious downloading problems to understand .....
## ref <- 'https://www.sec.gov/Archives/edgar/data/1318605/000156459017003118/tsla-20161231.xml'
ref <- 'https://www.sec.gov/Archives/edgar/data/320193/000162828016020309/aapl-20160924.xml'
## Get the data
xbrl.vars <- xbrlDoAll(ref, verbose=TRUE, delete.cached.inst = FALSE)
sts <- xbrl_get_statements(xbrl.vars)
## Look inside the XBRL
apple16 <- xbrl_get_statements(xbrl.vars)
|
aac0a7c424d1920d5cf6d4901e317accc4437366 | 0153b7d266bc6b6ba4bd42533853999aaa89f707 | /man/computePhysChem.Rd | 216070a7bc20c4c9dd4355ff7a4c17be3e7de010 | [] | no_license | Yan-Liao/ncProR | c45b6976d7bdbc32676bd5b12e4ab651858940b7 | fd6e5648a5e697c320a5356f6aedb7967bd6098d | refs/heads/master | 2022-04-07T21:04:00.304571 | 2020-03-04T05:34:15 | 2020-03-04T05:34:15 | 258,749,779 | 0 | 1 | null | 2020-04-25T10:37:48 | 2020-04-25T10:37:47 | null | UTF-8 | R | false | true | 6,107 | rd | computePhysChem.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/PhysicochemicalProperty.R
\name{computePhysChem}
\alias{computePhysChem}
\title{Computation of the Physicochemical Features of RNA or Protein Sequences}
\usage{
computePhysChem(seqs, seqType = c("RNA", "Pro"), Fourier.len = 10,
physchemRNA = c("hydrogenBonding", "vanderWaal"),
physchemPro = c("polarity.Grantham", "polarity.Zimmerman",
"bulkiness.Zimmerman", "isoelectricPoint.Zimmerman", "hphob.BullBreese",
"hphob.KyteDoolittle", "hphob.Eisenberg", "hphob.HoppWoods"),
parallel.cores = 2, as.list = TRUE)
}
\arguments{
\item{seqs}{sequences loaded by function \code{\link[seqinr]{read.fasta}} of package
"seqinr" (\code{\link[seqinr]{seqinr-package}}). Or a list of RNA/protein sequences.
RNA sequences will be converted into lower case letters, but
protein sequences will be converted into upper case letters.
Each sequence should be a vector of single characters.}
\item{seqType}{a string that specifies the nature of the sequence: \code{"RNA"} or \code{"Pro"} (protein).
If the input is DNA sequence and \code{seqType = "RNA"}, the DNA sequence will be converted to RNA sequence automatically.
Default: \code{"RNA"}.}
\item{Fourier.len}{postive integer specifying the Fourier series length that will be used as features.
The \code{Fourier.len} should be >= the length of the input sequence. Default: \code{10}.}
\item{physchemRNA}{strings specifying the physicochemical properties that are computed in RNA sequences. Ignored if \code{seqType = "Pro"}.
Options: \code{"hydrogenBonding"} for Hydrogen-bonding and \code{"vanderWaal"} for Van der Waal's interaction
Multiple elements can be selected at the same time. (Ref: [2])}
\item{physchemPro}{strings specifying the physicochemical properties that are computed in protein sequences. Ignored if \code{seqType = "RNA"}.
Options: \code{"polarity.Grantham"}, \code{"polarity.Zimmerman"}, \code{"bulkiness.Zimmerman"}, \code{"isoelectricPoint.Zimmerman"},
\code{"hphob.BullBreese"}, \code{"hphob.KyteDoolittle"}, \code{"hphob.Eisenberg"}, and
\code{"hphob.HoppWoods"}.
Multiple elements can be selected at the same time. See details below. (Ref: [3-9])}
\item{parallel.cores}{an integer that indicates the number of cores for parallel computation. Default: \code{2}.
Set \code{parallel.cores = -1} to run with all the cores.}
\item{as.list}{logical. The result will be returned as a list or data frame.}
}
\value{
This function returns a data frame if \code{as.list = FALSE} or returns a list if \code{as.list = TRUE}.
}
\description{
The function \code{computePhysChem} computes the physicochemical features of RNA
or protein sequences.
}
\details{
The default physicochemical properties are selected or derived from tool "catRAPID" (Ref: [10])
and "lncPro" (Ref: [11]).
In "catRAPID", \code{Fourier.len = 50}; in "lncPro", \code{Fourier.len} is set as \code{10}.
\itemize{
\item The physicochemical properties of RNA
\enumerate{
\item Hydrogen-bonding (\code{"hydrogenBonding"}) (Ref: [2])
\item Van der Waal's interaction (\code{"vanderWaal"}) (Ref: [2])
}
\item The physicochemical properties of protein sequence
\enumerate{
\item polarity \code{"polarity.Grantham"} (Ref: [3])
\item polarity \code{"polarity.Zimmerman"} (Ref: [4])
\item bulkiness \code{"bulkiness.Zimmerman"} Ref: [4]
\item isoelectric point \code{"isoelectricPoint.Zimmerman"} (Ref: [4])
\item hydropathicity \code{"hphob.BullBreese"} (Ref: [5])
\item hydropathicity \code{"hphob.KyteDoolittle"} (Ref: [6])
\item hydropathicity \code{"hphob.Eisenberg"} (Ref: [7])
\item hydropathicity \code{"hphob.HoppWoods"} (Ref: [8])
}}
}
\section{References}{
[1] Han S, Liang Y, Li Y, \emph{et al}.
ncProR: an integrated R package for effective ncRNA-protein interaction prediction.
(\emph{Submitted})
[2] Morozova N, Allers J, Myers J, \emph{et al}.
Protein-RNA interactions: exploring binding patterns with a three-dimensional superposition analysis of high resolution structures.
Bioinformatics 2006; 22:2746-52
[3] Grantham R.
Amino acid difference formula to help explain protein evolution.
Science 1974; 185:862-4
[4] Zimmerman JM, Eliezer N, Simha R.
The characterization of amino acid sequences in proteins by statistical methods.
J. Theor. Biol. 1968; 21:170-201
[5] Bull HB, Breese K.
Surface tension of amino acid solutions: a hydrophobicity scale of the amino acid residues.
Arch. Biochem. Biophys. 1974; 161:665-670
[6] Kyte J, Doolittle RF.
A simple method for displaying the hydropathic character of a protein.
J. Mol. Biol. 1982; 157:105-132
[7] Eisenberg D, Schwarz E, Komaromy M, \emph{et al}.
Analysis of membrane and surface protein sequences with the hydrophobic moment plot.
J. Mol. Biol. 1984; 179:125-42
[8] Hopp TP, Woods KR.
Prediction of protein antigenic determinants from amino acid sequences.
Proc. Natl. Acad. Sci. U. S. A. 1981; 78:3824-8
[9] Kawashima S, Kanehisa M. AAindex: amino acid index database. Nucleic Acids Res. 2000; 28:374
[10] Bellucci M, Agostini F, Masin M, \emph{et al}.
Predicting protein associations with long noncoding RNAs.
Nat. Methods 2011; 8:444-445
[11] Lu Q, Ren S, Lu M, \emph{et al}.
Computational prediction of associations between long non-coding RNAs and proteins.
BMC Genomics 2013; 14:651
}
\examples{
data(demoPositiveSeq)
seqsRNA <- demoPositiveSeq$RNA.positive
seqsPro <- demoPositiveSeq$Pro.positive
physChemRNA <- computePhysChem(seqs = seqsRNA, seqType = "RNA",
Fourier.len = 10, as.list = FALSE)
physChemPro <- computePhysChem(seqs = seqsPro, seqType = "Pro", Fourier.len = 8,
physchemPro = c("polarity.Grantham",
"polarity.Zimmerman",
"hphob.BullBreese",
"hphob.KyteDoolittle",
"hphob.Eisenberg",
"hphob.HoppWoods"),
as.list = TRUE)
}
\seealso{
\code{\link{featurePhysChem}}
}
|
3f05c1bfbd022cac31c5c029ab45578136a47d06 | 1ea1fac76546164a7de31459b844214280a50c38 | /man/player_stats.Rd | f1b96db365727a8838b4c02aba9c0734dd38152a | [] | no_license | SaniyaMAli/columbia | a19391b57555c9109f00386b8c643f74e5a6037d | 256cc060ba0edfeb832edd9a739d374d17eddbd5 | refs/heads/master | 2021-02-14T01:59:37.289637 | 2020-03-04T20:21:27 | 2020-03-04T20:21:27 | 244,756,069 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 392 | rd | player_stats.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/playerstats.R
\name{player_stats}
\alias{player_stats}
\title{A Player Assists Function}
\usage{
player_stats(year)
}
\arguments{
\item{year}{Year of interest.}
}
\description{
This function allows you to see which player had the most assists in a specific year
}
\examples{
player_stats(2005)
}
\keyword{assists}
|
93ae345df1fc6d09d2a6c43568552c10e6801ff2 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/entropart/examples/Tsallis.Rd.R | f17e427020a2b14ce37517f494c74781f7dfd897 | [] | 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 | 626 | r | Tsallis.Rd.R | library(entropart)
### Name: Tsallis
### Title: Tsallis (HCDT) Entropy of a community
### Aliases: Tsallis bcTsallis Tsallis.ProbaVector Tsallis.AbdVector
### Tsallis.integer Tsallis.numeric
### ** Examples
# Load Paracou data (number of trees per species in two 1-ha plot of a tropical forest)
data(Paracou618)
# Ns is the total number of trees per species
Ns <- as.AbdVector(Paracou618.MC$Ns)
# Species probabilities
Ps <- as.ProbaVector(Paracou618.MC$Ns)
# Whittaker plot
plot(Ns)
# Calculate entropy of order 1, i.e. Shannon's entropy
Tsallis(Ps, 1)
# Calculate it with estimation bias correction
Tsallis(Ns, 1)
|
c81942d28a2a08385e959e08b8829369988316da | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/knitr/examples/opts_chunk.Rd.R | a6018f9b89222d0d5369e4300cd0b66dc9505fef | [] | 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 | 216 | r | opts_chunk.Rd.R | library(knitr)
### Name: opts_chunk
### Title: Default and current chunk options
### Aliases: opts_chunk opts_current
### Keywords: datasets
### ** Examples
opts_chunk$get("prompt")
opts_chunk$get("fig.keep")
|
6c2ff0589638fcef289e3ba0ded987b500b82056 | 926517ec2bca37361dd5c785f5350d7179bcff61 | /data-raw/Tree.dataset.BCI.R | 7e6be04d05e822aabca79fa66e49946f36cd0002 | [] | no_license | femeunier/LianaRTM | 0f144b5db9b8d980bd72f5dc6e2e9ab5355fba32 | 697a5945b49816351d409ae58c5a41ec8b8f7ecd | refs/heads/main | 2023-05-02T02:56:22.638079 | 2021-05-06T15:06:47 | 2021-05-06T15:06:47 | 348,286,242 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 1,234 | r | Tree.dataset.BCI.R | library(dplyr)
library(LidarED)
folder <- "./data/"
times <- seq(1980,2010,5)
census <- list()
df.BCI <- data.frame()
for (i in seq(1,7)){
censusname <- paste0("bci.full",i)
datafile2read <- file.path(folder,paste0(censusname,".rdata"))
load(datafile2read)
census[[as.character(times[i])]] <- get(censusname)
df.BCI <- bind_rows(list(df.BCI,
census[[as.character(times[i])]] %>% mutate(census.time = times[i])))
}
Delta_XY <- 25
patch.num <- df.BCI%>% filter(gx <= 1000,
gx >= 0,
gy >= 0,
gy <= 500,census.time == 2000) %>% mutate(patch = (patchnumber_from_position(gx,gy,Delta_XY,Delta_XY))) %>% pull(patch)
df.BCI.f <- df.BCI%>% filter(gx <= 1000,
gx >= 0,
gy >= 0,
gy <= 500) %>% mutate(patch = rep(patch.num,length(times)))
tree.BCI <- df.BCI.f %>% dplyr::select(treeID,sp,patch,DFstatus,census.time,gx,gy,dbh,agb) %>% mutate(is_liana = FALSE,
dbh = dbh/10)
usethis::use_data(tree.BCI, overwrite = TRUE)
|
22a6ee15018c929c63ff8877cd2f1bdd8f13d880 | 93e8e426da28151c87829df7dcdbb61b3f157f74 | /plot3.R | cd4adaedf8957a799a76960e59f43c422dffbeb6 | [] | no_license | GGanguly/ExData_Plotting1 | 65684a56c522a98e5966b01a51aee15d6dd49991 | 84fe9a951aa8f9bc2eaa5cb4fbf97ea602b75518 | refs/heads/master | 2021-01-13T10:06:52.760080 | 2016-03-27T00:03:53 | 2016-03-27T00:03:53 | 54,757,175 | 0 | 0 | null | 2016-03-26T01:41:32 | 2016-03-26T01:41:32 | null | UTF-8 | R | false | false | 451 | r | plot3.R | plot3 <- function(finalDf){
with(finalDf,plot(date_ts,Sub_metering_1, type="l", xlab="", ylab="Energy sub metering"))
lines(finalDf$date_ts,finalDf$Sub_metering_2,col="red")
lines(finalDf$date_ts,finalDf$Sub_metering_3,col="blue")
legend("topright", col=c("black","red","blue"), c("Sub_metering_1 ","Sub_metering_2 ", "Sub_metering_3 "),lty=c(1,1), lwd=c(1,1), cex=.5)
dev.copy(png, file="plot3.png", width=480, height=480)
dev.off()
} |
a1d8b22501064fac3acc99fa49a6526441b7b732 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/kequate/examples/cdist.Rd.R | 807f18404c809546588935ba2e849e2c507911f1 | [] | 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 | 522 | r | cdist.Rd.R | library(kequate)
### Name: cdist
### Title: Conditional Mean, Variance, Skewness and Kurtosis
### Aliases: cdist
### ** Examples
freqdata<-data.frame(X=c(1,2,2,1,2,2,2,2,3,1,2,1,4,2,1,1,3,3,3,3),
A=(c(0,2,1,1,0,3,1,2,2,0,2,0,3,1,1,2,2,2,1,2)))
Pdata<-kefreq(freqdata$X, 0:5, freqdata$A, 0:3)
Pglm<-glm(frequency~X+I(X^2)+A+I(A^2)+X:A, data=Pdata, family="poisson", x=TRUE)
Pobs<-matrix(Pdata$freq, nrow=6)/sum(Pglm$y)
Pest<-matrix(Pglm$fitted.values, nrow=6)/sum(Pglm$y)
cdP<-cdist(Pest, Pobs, 0:5, 0:3)
plot(cdP)
|
11062edb05e6a166cd9f4d92eceb3c1657e5b620 | 057cb37817ffeec47fffecdabb59fc1f060884e8 | /experiment_real_data/single_cell/breast_TNBC/generate.onconem.R | be3c03660801a56569119c2e41f0358d258a54b3 | [] | no_license | BIMIB-DISCo/MST | 7e1a89e430ed0c16f42a9caecafb0e1f426189fc | d1db82d70c6df9c19ab86153e3b7e696d1f7588b | refs/heads/master | 2021-01-13T06:56:36.494870 | 2018-12-09T22:22:08 | 2018-12-09T22:22:08 | 54,653,989 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,981 | r | generate.onconem.R | ##############################################################################
###
### MST
###
### Generate OncoNEM
###
##############################################################################
### Copyright (c) 2015-2018, The TRONCO Team (www.troncopackage.org)
### email: tronco@disco.unimib.it
### All rights reserved. This program and the accompanying materials
### are made available under the terms of the GNU GPL v3.0
### which accompanies this distribution
##############################################################################
library(oncoNEM)
library(TRONCO)
options(scipen = 999)
if (! dir.exists('onconem')) {
dir.create('onconem')
}
epos_level = 0.05
eneg_level = 0.05
load('dataset_navin_TNBC.RData')
data = dataset_navin_TNBC
onconem.genotypes = t(data)
oNEM = oncoNEM$new(Data = onconem.genotypes,
FPR = epos_level,
FNR = eneg_level)
oNEM$search(delta = 200)
plotTree(tree = oNEM$best$tree, clones = NULL, vertex.size = 25)
dev.copy2pdf(file = 'onconem/onconem.best.pdf')
oNEM.expanded = expandOncoNEM(oNEM,
epsilon = 10,
delta = 200,
checkMax = 10000,
app = TRUE)
plotTree(tree = oNEM.expanded$best$tree,
clones = NULL,
vertex.size = 25)
dev.copy2pdf(file = 'onconem/onconem.best.expand.pdf')
oncoTree = clusterOncoNEM(oNEM = oNEM.expanded, epsilon = 10)
post = oncoNEMposteriors(tree = oncoTree$g,
clones = oncoTree$clones,
Data = oNEM$Data,
FPR = oNEM$FPR,
FNR = oNEM$FNR)
edgeLengths = colSums(post$p_theta)[-1]
plotTree(tree = oncoTree$g,
clones = oncoTree$clones,
e.length = edgeLengths,
label.length = 4,
axis = TRUE)
dev.copy2pdf(file = 'onconem/onconem.best.clustered.pdf')
### end of file -- generate.onconem.R
|
ea0bc130412abcf95452a852e9d68d5ffe8015e9 | afe00b66262d444a8380bd346372d98ef7bf6299 | /fasagfa.R | 13e3f888e5be64912a98e83990aa0dddd83f45d6 | [] | no_license | YingxiaLiu/try | f8c7b2c4d8ee4e033017594ff0363f35d184e080 | 41ae0d650eac28962299a994a9459d99fc06cf5f | refs/heads/master | 2020-12-12T05:31:15.022256 | 2020-01-15T10:39:24 | 2020-01-15T10:39:24 | 234,052,816 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 33 | r | fasagfa.R | tiffile <- dircontents[1]
j=69
lm |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.