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
23538fa8875b4d496738109cfa4de48a8e6ee7aa
7bef5b5f81c1d089fbd9ddd82882269b456a1acc
/src/localauthority_Dec.R
d883da010cb4d5cc40c02574bea4c7d0c3f5e92e
[ "MIT" ]
permissive
Gabriel-Danelian/covid19uklocal
e835b880dd67c8181aa40dba21d3b6af2f49736f
af74fa23e8506419b839bcfe7017920222ff406f
refs/heads/main
2023-05-27T16:47:32.865537
2021-06-11T04:57:31
2021-06-11T04:57:31
null
0
0
null
null
null
null
UTF-8
R
false
false
9,476
r
localauthority_Dec.R
## for epidemia with the new observation format ## script runs for a single ltla library(optparse) library(here) library(epidemia) library(dplyr) library(zoo) options(mc.cores=parallel::detectCores()) source(here("UK_Linelist/public/utility.R")) option_list <- list( make_option(c("--ltla"),action="store", type="integer", default=-1,help="Which LTLA to run this for [default \"%default\"]"), make_option(c("--ltlaname"),action="store", default="Leicester",help="Which LTLA to run this for [default \"%default\"]"), make_option(c("--input"),action="store", default=paste(here(),"/data/uk-public-ltla-combined.rds",sep=""),help="Input file [default \"%default\"]"), make_option(c("--nchains"),action="store", type="integer", default=4,help="Number of Chains [default \"%default\"]"), make_option(c("--iter"),action="store", type="integer", default=1000,help="Number of iterations [default \"%default\"]"), make_option(c("--thin"),action="store", type="integer", default=1,help="Amount of thinning of results [default \"%default\"]"), make_option(c("--UKfits"),action="store", default=here("fits"), help="fits for UK model [default \"%default\"]"), make_option(c("--fit_params"),action="store", default=here("fits/fit_params.csv"), help="population file [default \"%default\"]"), make_option(c("--output"),action="store", default=here("fits"), help="Output directory [default \"%default\"]") ) option_list <- add_i2o_rates_option(option_list) opt <- parse_args(OptionParser(option_list=option_list)) dataorig <- readRDS(opt$input) pops <- read.csv2(here("data/modified_population.csv"),sep=",") pops <- data.frame(ltla=as.character(pops$AREA),pop=pops$Y2018,stringsAsFactors=FALSE) pop <- pops$pop names(pop) <- pops$ltla dataorig$pop <- pop[dataorig$Area_name] data <- ungroup(dataorig) data <- select(data, Area_name, Cdate, Cases, Deaths, pop) data <- rename(data, ltla=Area_name, date=Cdate, Cases=Cases, Deaths_week=Deaths) Caseend <- getcaseend(data) cat("Case End=",as.character(Caseend),"\n") data <- group_by(data, ltla) data <- arrange(data, date, .by_group=T) if (opt$ltla==-1){ a <- opt$ltlaname a <- gsub("_"," ",a) }else{ i <- opt$ltla a <- unique(data$ltla)[i] } data <- data[is.element(data$ltla,a),] Caseend <- min(max(data$date)-2,Caseend) data <- data[data$date<=Caseend,] ## weeks ends with the last case data$week <- ceiling((data$date - (Caseend-3))/7) ## to allign with Caseend data$week[data$week>0] <- 0 ##to stabilise the end data$Cases_week <- NA for (ltla in a){ w <- data$ltla==ltla o <- order(data$date[w]) ##ensure dates are ordered data[w,] <- data[w,][o,] ##compute cumulative obs per week data$Cases_week[w] <- sapply(1:sum(w), function(i) if (as.integer((data$date[w][i]-Caseend))%% 7==0){ sum(data$Cases[w][i:(max(1,i-6))]) }else { NA } ) start <- which(cumsum(ifelse(is.na(data$Deaths_week[w]),0,data$Deaths_week[w]))>=10) if (length(start)>=1){ ostart <- min(min(data$date[w][start]),as.Date("2020-06-01")) }else{ ostart <- as.Date("2020-06-01") } ostart <- as.Date("2020-12-15") cat("Observation start=",as.character(ostart),"\n") epistart <- ostart -30 cat("Start of Epidemic=",as.character(epistart),"\n") Casestart <- as.Date("2020-12-05") ### cases start in June in the model data$Cases[w][data$date[w]<Casestart] <- NA data$Cases[w][data$date[w]>Caseend] <- NA data$Cases_week[w][data$date[w]<Casestart] <- NA data$Cases_week[w][data$date[w]>Caseend] <- NA data$Deaths_week[w][data$date[w]>Caseend] <- NA data$Deaths_week[w][data$date[w]<ostart] <- NA data$ltla[w][data$date[w]<epistart] <- NA data <- data[!is.na(data$ltla),] } ## Load Regional fit region <- dataorig$Region_name[min(which(dataorig$Area_name==a))] load(paste(opt$UKfits,"/fm-",gsub(" ","_",region),".rds",sep="")) data <- left_join(data, res$meanRt) firstentryaRt <- min(which(!is.na(data$averageRt))) data$averageRt[1:firstentryaRt] <- data$averageRt[firstentryaRt] ##fill NAs at beginning with first value wNA <- which(is.na(data$averageRt)) wNA <- wNA[wNA<10] data$averageRt[wNA] <- data$averageRt[max(wNA)+1] wNA <- which(is.na(data$averageRt)) wNA <- wNA[wNA>10] if (length(wNA)>0){ data$averageRt[wNA] <- data$averageRt[min(wNA)-1] } data$logitRt <- log(data$averageRt/3.28/2/(1-data$averageRt/3.28/2)) data$averageRt <- data$averageRt-3.28 ##stop regional trend a month before the end of observation to get regional trend. data$logitRt[data$date>(Caseend-45)] <- data$logitRt[data$date==Caseend-45] #### Parsing i2o_rates into data i2o_rates <- readRDS(opt$i2o_rates) data <- data %>% add_i2o_rates(i2o_rates) IFR_sd <- get_IFR_sd(i2o_rates) IAR_sd <- get_IAR_sd(i2o_rates) obs <- list() obs$Cases <- epiobs(formula=Cases(ltla,date) ~ 1, i2o=c(0,0,0,rep(1/10,10))) i2o2week <- function(i2o) rowSums(sapply(0:6, function (k) c(rep(0,k),i2o,rep(0,6-k)))) obs$Deaths_week <- epiobs(formula=Deaths_week(ltla,date) ~ 0+ifr, link="identity", family="quasi_poisson", prior_aux = rstanarm::normal(location=3,2), prior=rstanarm::normal(1,IFR_sd,autoscale=FALSE), i2o=i2o2week(EuropeCovid$obs$deaths$i2o)) obs$Cases_week <- epiobs(formula=Cases_week(ltla,date) ~ 0 + iar, link="identity", family="quasi_poisson", prior_aux = rstanarm::normal(location=3,2), prior=rstanarm::normal(1,IAR_sd,autoscale=FALSE), i2o=i2o2week(obs$Cases$i2o)) obs$logit_Deaths_week <- epiobs(formula=Deaths_week(ltla,date) ~ 0 + I(log(ifr/(1-ifr))), link="logit", family="quasi_poisson", prior_aux = rstanarm::normal(location=3,2), prior=rstanarm::normal(1,IAR_sd,autoscale=FALSE), i2o=2*i2o2week(EuropeCovid$obs$deaths$i2o)) obs$logit_Cases_week <- epiobs(formula=Cases_week(ltla,date) ~ 0 + I(log(iar/(1-iar))), link="logit", family="quasi_poisson", prior_aux = rstanarm::normal(location=3,2), prior=rstanarm::normal(1,IFR_sd,autoscale=FALSE), i2o=2*i2o2week(obs$Cases$i2o)) args <- list() args$data <- data args$obs <- list(Cases_week=obs$Cases_week,Deaths_week=obs$Deaths_week) args$prior_covariance <- rstanarm::decov(shape=2,scale=0.15) args$rt <- epirt(formula=R(ltla,date) ~ rw(time=week,prior_scale=.15)+logitRt,prior=rstanarm::normal(1,.05),prior_intercep=rstanarm::normal(0,.1)) args$pops <- pops args$si <- c(EuropeCovid$si[1:33],sum(EuropeCovid$si[34:length(EuropeCovid$si)])) args$group_subset <- a args$algorithm <- "sampling" adapt_delta <- 0.92 args$alpha <- 1 args$beta <- 10 args$data$ltla <- factor(args$data$ltla) ##temporary fix - country needs to be categorical args$init_run <- list(iter=1000, chains=1) fitparams <- read.csv(opt$fit_params,sep="&") fitparams$Area_name <- gsub("_"," ",fitparams$Area_name) fitparams <- fitparams %>% filter(Area_name==gsub("_"," ",a)) if (dim(fitparams)[1]>0){ opt$iter <- max(fitparams$iter) opt$thin <- max(fitparams$thin) adapt_delta <- max(fitparams$adapt_delta) } args$sampling_args <- list(iter=opt$iter, chains=opt$nchains,thin=opt$thin,control=list(adapt_delta=adapt_delta,max_treedepth=11)) cat("iter=",opt$iter, "thin= ", opt$thin, " adapt_delta=",adapt_delta,"\n") time <- system.time({fit <- do.call("epim", args)}) sampler_params <- rstan::get_sampler_params(fit$stanfit, inc_warmup = FALSE) Rhat <- max(rstan::summary(fit$stanfit)$summary[,"Rhat"]) divergent <- sum(sapply(sampler_params, function(x) x[,"divergent__"])) cat("Rhat=",Rhat," divergent steps=", divergent,"\n") res <- list(fit=fit, model=fit$formula, last_obs_date=fit$data$date[max(which(!is.na(fit$data$Cases)))], today=max(fit$data$date), ltla=a, time=time) if (Rhat>=1.2||divergent>=opt$nchains*opt$iter/2.*.005){ if (divergent>=opt$nchains*opt$iter/2.*.005) { adapt_delta <- (adapt_delta+1.)/2. } else if (Rhat>=1.2 && opt$iter<6000){ opt$iter <- opt$iter*2 opt$thin <- opt$thin*2 } write.table(data.frame(Area_name=a, iter=opt$iter, thin=opt$thin, adapt_delta=adapt_delta), sep="&",append=TRUE,col.names=FALSE,row.names=FALSE, file=opt$fit_params) dir.create(file.path(opt$output,"failedruns"), showWarnings = FALSE) # save result to file save(res, file=paste(opt$output,"/failedruns/fm-", gsub(" ","_",a), Sys.time(), ".rds",sep="")) stop("Sampling not successful; parameters adjusted") } warnings() # save result to file save(res, file=paste(opt$output,"/fm-", gsub(" ","_",a), ".rdata",sep=""))
3bfbe3accc639748bacbf4ae19637e29bdb79d28
213281f024e937cc91028e27a6b70f2f5c78275a
/R/TSP_elasticnet.R
7af3f49e036b011e54dead82dda4fd770e19389b
[]
no_license
thomasgurry/data_analysis
865c65727f2869aa794d8ee9ce8e3a99f15993e1
ec5a863c3ca82924ade60dfdc97a413d054678c0
refs/heads/master
2021-01-23T03:27:21.417090
2019-04-30T16:23:34
2019-04-30T16:23:34
86,078,683
1
0
null
null
null
null
UTF-8
R
false
false
4,112
r
TSP_elasticnet.R
#Generate N cities randomly in a unit square. random.cities <- function(N){ points = matrix(runif(2*N,min=0,max=1),nrow=N,ncol=2) } #Function to calculate Euclidean distance between two points. #’y’ may be a matrix of points. distance <- function(x,y){ if(length(y)>2){ dimension = dim(y)[1] }else{ dimension = 1 } dist = rep(0,dimension) if(dimension>1){ for(i in 1:dimension){ dist[i] = sqrt(sum((x-y[i,])^2)) } }else{ for(i in 1:dimension){ dist[i] = sqrt(sum((x-y[i])^2)) } } return(dist) } #Function phi(d,K). phi.function <- function(d,K){ res = exp(-(d^2)/(2*(K^2))) return(res) } #Implementation of elastic net for a set of N points. TSP <- function(points,N){ #par(ask=TRUE) centroid = c(sum(points[,1])/N,sum(points[,2])/N) M = 2.5*N path.points = matrix(0,nrow=M,ncol=2) alpha = 0.2 beta = 2.0 K = 0.2 weights = matrix(0,nrow=N,ncol=M) delta.y = matrix(1,nrow=M,ncol=2) x.max = max(max(points[,1]),max(path.points[,1])) x.min = min(min(points[,1]),min(path.points[,1])) y.max = max(max(points[,2]),max(path.points[,2])) y.min = min(min(points[,2]),min(path.points[,2])) range = mean((x.max-x.min),(y.max-y.min)) print(range) #Set M path points randomly on a circle of radius range/6. initial.radius = range/10 which.angles = seq((2*pi)/M,2*pi,by=(2*pi)/M) path.points[,1] = cos(which.angles)*initial.radius + centroid[1] path.points[,2] = sin(which.angles)*initial.radius + centroid[2] iteration = 0 change = 1 plot.path(points,path.points,centroid,K) while(iteration<5000){ if(K<(0.05+0.0001) & K>(0.05-0.0001)){ plot.path(points,path.points,centroid,K) } if(K<(0.01+0.0001) & K>(0.01-0.0001)){ plot.path(points,path.points,centroid,K) } if(iteration==4999) plot.path(points,path.points,centroid,K) #Reduce value of K by 1% every 5 iterations. iteration = iteration + 1 #print(iteration) if(iteration%%5 == 0) K = 0.99*K #Compute w_ij according to (2) in Durbin & Willshaw. for(j in 1:M){ for(i in 1:N){ denominator = 0 dist1 = sqrt((points[i,1]-path.points[,1])^2 + (points[i,2]-path.points[,2])^2) denominator = denominator + sum(exp(-(dist1^2)/(2*K^2))) if(denominator==0) denominator= 10^(-10) dist = sqrt((points[i,1]-path.points[j,1])^2 + (points[i,2]-path.points[j,2])^2) weights[i,j] = exp(-(dist^2)/(2*K^2)) weights[i,j] = weights[i,j]/denominator } } #Compute delta y_j. for(j in 1:M){ #Include periodic boundary conditions, for a = j+1, j, k = j-1 if(j==1){ k = M }else{ k = j-1 } if(j==M){ a = 1 }else{ a = j+1 } term = 0 for(n in 1:N){ term = term + weights[n,j]*(points[n,]-path.points[j,]) } delta.y[j,1] = alpha*term[1] + beta*K*(path.points[a,1]-2*path.points[j,1]+path.points[k,1]) delta.y[j,2] = alpha*term[2] + beta*K*(path.points[a,2]-2*path.points[j,2]+path.points[k,2]) } path.points = path.points + delta.y plot.path(points,path.points,centroid,K) } path.length = 0 for(x in 1:M){ if(x==M){ y = 1 }else{ y = x+1 } path.length = path.length + sqrt(sum(path.points[x,]-path.points[y,])^2) } print(paste("Path length: ",path.length)) return(path.points) } #Plot points. plot.path <- function(points,path.points,centroid,K){ plot(points[,1],points[,2],type="p",col="black",main=paste("K = ",K)) points(path.points,col="red") centroid = rbind(centroid,centroid) points(centroid,col="blue") lines(path.points,col="red") lines(rbind(path.points[1,],path.points[dim(path.points)[1],]),col="red") } #Generate points and run TSP. go.TSP <- function(N){ if(burma==1){ points = cities[,2:3] }else{ points = random.cities(N) } print(points) path.points = TSP(points,N) } ####################################### # CARE: RUN THIS WITH mod(N,10)==0 # ####################################### letsgo <- function(N){ points = random.cities(N) path.points = TSP(points,N) }
c373b9187e11dad2415822db2b09d43a4f571c49
a40e3ae448583f1f08712b5f25e82c9d030e22be
/Working.R
c31b7d891cb7ba95c84eff0d9c62746c6aad3cef
[]
no_license
shriharsha05/Rshiny-experiments
5ae23acbff2721fd56c7ebc614a22e2cfffdcb54
f0134524c73a35c484eb697c3241e3e468735165
refs/heads/master
2020-04-16T08:32:15.149850
2019-01-12T19:40:41
2019-01-12T19:40:41
165,428,511
0
0
null
null
null
null
UTF-8
R
false
false
4,504
r
Working.R
library(markdown) library(shiny) library(shinythemes) # Define UI ui <- fluidPage( theme = shinytheme("yeti"), navbarPage("HR ANALYTICS", tabPanel("My Team", sidebarLayout( sidebarPanel( selectInput("", h4("Branch"), choices = list("Unilog Content" = 1, "Unilog Software" = 2), selected = 1), textInput("text", h4("Employee ID"), value = "Ex : 100123"), br(), br(), br(), h4("Summary:"), h5("Attrition Prediction: No"), h5("Attrition Probability: 15%"), h5("Designation: Team Lead"), h5("Primary Department: Solution Engineering"), h5("Secondary Department: Solution Enhancement") ), mainPanel( # fluidRow( # actionButton("risk", "Risk Assessment"), # actionButton("mngmnt", "Management Recommendations"), # actionButton("perf", "Performance") # ), tabsetPanel( tabPanel("Risk Assessment", plotOutput("distPlot")), tabPanel ( "Management Recommendations", br(), h5("Professional Development Strategy : Retain and Maintain"), br(), h5("Work Environment Strategy : Improve Work-Life Balance"), br(), br(), textAreaInput("notes", h4("Notes:"), value = "", width = "300px", height = "200px"), actionButton("savenotes", "Save Notes")), tabPanel("Performance", tableOutput("table")) ), br(), br() #dummy graph plot #plotOutput(outputId = "distPlot") ) ) ), tabPanel("Department", h4(""), selectInput("Department","Select Department:",c("Research and development"="RD","Marketing"="mark")), sidebarPanel( plotOutput(outputId = "dist3Plot") ), mainPanel( hr(), br(), br(), #dummy graph plot h4("Hello") ) ), tabPanel("Recruitment Channel Analysis", mainPanel( selectInput("Department","Select Department:",c("Research and development"="RD","Marketing"="mark")), hr(), br(), br(), #dummy graph plot plotOutput(outputId = "dist2Plot") ) ) ) ) server <- function(input, output, session) { output$distPlot <- renderPlot({ x <- faithful$waiting bins <- seq(min(x), max(x), length.out = 15) hist(x, breaks = bins, col = "#75AADB", border = "white", xlab = "Waiting time to next eruption (in mins)", main = "Histogram of waiting times") }) output$dist2Plot <- renderPlot({ x <- faithful$waiting bins <- seq(min(x), max(x), length.out = 15) hist(x, breaks = bins, col = "#75AADB", border = "white", xlab = "Waiting time to next eruption (in mins)", main = "Histogram of waiting times") }) output$dist3Plot <- renderPlot({ x <- faithful$waiting bins <- seq(min(x), max(x), length.out = 15) hist(x, breaks = bins, col = "#75AADB", border = "white", xlab = "Waiting time to next eruption (in mins)", main = "Histogram of waiting times") }) output$plot <- renderPlot({ plot(cars, type=input$plotType) }) output$summary <- renderPrint({ summary(cars) }) } shinyApp(ui = ui, server = server)
1d14c93aefee6a110b7e9b86bb1ee3dfe679df3d
2f9718c70f49b585276d71c7209e75f3068f7411
/R/plotClusters.r
214f85da320f1b9f182efc7c71ce3733f2dba311
[]
no_license
PaulPyl/JagsCluster
188fdb660fe41542e2e3c16ff4cc15c23e6b5b43
7547f338aa40a104d755c70bf8b5047095e04ccb
refs/heads/master
2021-01-13T06:14:30.065541
2018-05-08T12:26:33
2018-05-08T12:26:33
94,921,226
0
0
null
null
null
null
UTF-8
R
false
false
1,414
r
plotClusters.r
plotClusters <- function(clsRes, mode = "point", minWeight = 0.01){ nSamples <- ncol(clsRes$Modelling.Data$AF) theSamples <- colnames(clsRes$Modelling.Data$AF) dat <- do.call(rbind,lapply(seq(nSamples), function(sid){ res <- melt(clsRes$jags.result[[paste0("cluster.center.", sid)]][,,,drop = FALSE]) colnames(res) <- c("ClusterIdx", "SamplingNr", "Chain", "Value") res$Sample <- colnames(clsRes$Modelling.Data$AF)[sid] res })) dat <- subset(dat, ClusterIdx %in% unique(subset(clsRes$Clusters, Weight >= minWeight)$ClusterIdx)) df <- do.call(rbind,lapply(seq(1, ncol(clsRes$Modelling.Data$AF)-1), function(i) do.call(rbind,lapply(seq(i+1, ncol(clsRes$Modelling.Data$AF)), function(j) { reta <- subset(dat, Sample == theSamples[i]) retb <- subset(dat, Sample == theSamples[j]) colnames(reta)[4] <- "AFOne" colnames(retb)[4] <- "AFTwo" colnames(reta)[5] <- "SampleOne" colnames(retb)[5] <- "SampleTwo" merge(reta, retb) })))) df$ClusterName <- clsRes$ClusterNameMap[df$ClusterIdx] p <- ggplot(df, aes(x = AFOne, y = AFTwo, fill = ClusterName)) + facet_grid(SampleOne ~ SampleTwo) + xlim(0,1) + ylim(0,1) + theme_bw() if(mode == "point"){ p <- p + geom_point(shape = 21, size = 3, alpha = 0.6) }else if(mode == "density2d"){ p <- p + stat_density2d(alpha = 0.6, contour = TRUE, colour = "grey70", size = 0.25, geom = "polygon") } }
adea9fb25f7f9bc0fc963e00b47ce77201be8d72
db3ec88138be9d83e81a8ecdf5fd02bccc0d6d28
/R/powerConj.R
007091f8033837e5f57834d9b593036abe1b708f
[]
no_license
Jingfan-Sun/powerr
df51e30a94bdeb7a82b66b494561877cab991749
873fcbfdf351ef2123a3f04dee8653493be3eded
refs/heads/master
2021-05-28T06:20:48.110757
2014-09-28T05:32:58
2014-09-28T05:32:58
null
0
0
null
null
null
null
UTF-8
R
false
false
366
r
powerConj.R
#' powerConj #' #' Calculate conj of complex or real sparse matrix #' #' @param x complex objects to calculate conjugate powerConj <- function(x) { if (class(x) == 'list') { x <- list(mRe = x[[1]], mIm = -x[[2]]); } else if (class(x) == 'dgCMatrix'){ # do nothing } else { x <- Conj(x); } return(x); }
63c2860d1e88471e7e8ae800e9ef1d8101700bd8
033bbdd258069da5eb7d5639f22d9c32b51ebb5d
/Limpeza de dados/funcaoColunaNA.R
a607a3a71eafb5ec8f9bc46087ed18d499757f2c
[]
no_license
joscelino/ETL
078abf525021d688f3184c8853d842965e495b9b
6521f430a46e671e47e0b468e20cc74c9bbc0758
refs/heads/main
2023-02-18T00:57:58.064021
2021-01-21T17:45:44
2021-01-21T17:45:44
331,707,126
1
0
null
null
null
null
UTF-8
R
false
false
454
r
funcaoColunaNA.R
# Funcao para identificar NAs em colunas de data frames funcaoNA <- function(df){ library(pacman) pacman::p_load(dplyr) index_col_na <- NULL quantidade_na <- NULL for (i in 1:ncol(df)) { if(sum(is.na(df[,i])) > 0) { index_col_na[i] <- i quantidade_na[i] <- sum(is.na(df[,i])) } } resultados <- data.frame(index_col_na,quantidade_na) resultados <- resultados %>% filter(quantidade_na>0) return(resultados) }
9645207726e5b1147ab34f7a1661b5fa1bd80a7c
1051ccaffe37c38667b79397bc78125636ca28fb
/server/napr/man/read.upload.file.Rd
5c2362b82b3c2c49a9d27090759ebaab8c9351f6
[ "Apache-2.0" ]
permissive
hpardoe/napr
ae1078cdeab1047b27f3aa0f6b2631c50b41627e
f6c123699806611e800fe9f2a3567e00945cfb1c
refs/heads/master
2023-08-23T03:40:19.376594
2023-07-05T02:18:06
2023-07-05T02:18:06
76,494,707
2
2
Apache-2.0
2023-08-15T15:09:58
2016-12-14T20:31:25
R
UTF-8
R
false
true
754
rd
read.upload.file.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/napr.file.reader.20160510.R, R/napr.file.reader.20161129.R \name{read.upload.file} \alias{read.upload.file} \title{read .brainage_upload_file} \usage{ read.upload.file(input) read.upload.file(input) } \arguments{ \item{input}{a tar archive containing lh.thickness.fwhm0.fsaverage4.mgh and rh.thickness.fwhm0.fsaverage4.mgh for a subject} \item{file.name}{The name of a file that is the aseg.stats, lh.aparc and rh.aparc files cat'ed together} } \value{ a matrix with the numbers laid out so the predictive model can read them a matrix with the numbers laid out so the predictive model can read them } \description{ read .brainage_upload_file read .brainage_upload_file }
556f15d0592a853f389b72569cf674b6d537da7c
48aa9794b5c2589da6920fd3b5791775715120df
/Farm data analysis/Plotheatmap.R
065f429a02fcd4daa71ec569396a47d9db4c176c
[]
no_license
RIF-HKU/AMR_project
02eaaceabc07f0625001118261742d7182993cc5
479d17bcdedb21b81102e0c31985973d91242aad
refs/heads/main
2023-06-27T07:07:51.964241
2021-08-04T06:48:22
2021-08-04T06:48:22
391,809,720
0
0
null
2021-08-02T03:57:26
2021-08-02T03:57:25
null
UTF-8
R
false
false
2,600
r
Plotheatmap.R
#Heatmap across farms #*heatmap.data() #Combining the count data and MIC values together, order them by their corresponding antibiogram length. #*Change the antibiotics names into regular #*s #* #* #* #****************************************************************************************************************** #chage values contains equations into numerics a_farm=ast_05%>% filter(grepl("^SA.*",i_pid)&a_bacteria=="ECOLI") a_farm=data.frame(lapply(a_farm, function(x){ gsub("< |= |<|> ","",x)})) #------------------------------------------------------------------------------------------------------------------- # Create data that used for heatmap heatmap.data<-function(farm,stage){ mapdata<-data.frame() mapdata=right_join(Mic_classification(farm,stage),stagecount.data(farm,stage),by="id") mapdata=mapdata[order(mapdata$RES),] mapdata$id<- factor(mapdata$id, levels=unique(mapdata$id)) mapdata$colname=sapply(strsplit(mapdata$colname,"_"),function(x)x[2]) return(mapdata) } t1=heatmap.data(c_farm,"piglet") t2=heatmap.data(c_farm,"weaner") t3=heatmap.data(c_farm,"grower") t4=heatmap.data(c_farm,"finisher") #--------------------------------- # Plot our heatmap plot.heatmap<-function(data){ data%>% ggplot(aes(x=colname,y=id))+ geom_tile(aes(fill=value),colour="white",colour = "white" )+scale_fill_distiller(palette = "PuBuGn",limits=c(0,16),na.value = "#de2d26", direction = 1,labels=c("Susceptible","Intermediate","Resistance","8 fold Resistance","16 fold Resistance"))+ #scale_fill_gradient2(low = "white", mid="lightyellow",high = "red", midpoint=1)+ #scale_fill_gradientn(colors = colors, breaks = b, labels = format(b))+ #sscale_fill_gradientn(name="CPU Utilization", colours=pals, #values=vals,limits=c(0,100), breaks = brk) scale_x_discrete(guide = guide_axis(angle = 90))+ xlab("Antibiotics")+ylab("Isolate Id")+ theme(title=element_text(hjust=0.5, face="bold", vjust=0.5, family="Helvetica"), text=element_text(family="Times New Roman"), axis.text.y=element_text(size=5, family="Times New Roman", hjust=1)) } #YlGrBu,PuBu,PuBuGn" p1=plot.heatmap(t1)+ggtitle("Piglet") p2=plot.heatmap(t2)+ggtitle("Weaner") p3=plot.heatmap(t2)+ggtitle("Grower") p4=plot.heatmap(t2)+ggtitle("Finisher") farm2=ggarrange(p1,p2,p3,p4,ncol=2,nrow = 2,labels = c("a","b","c","d")) ggsave("~/Desktop/farmC.png", width = 30, height = 21, units = "cm", dpi = 500, type = "cairo-png")
c373de5c6e344abeaae8a4d57ef96641fd8948a0
b757b281becded608b180cc0cdb4e196a2f56296
/R/analysis_model_E1_table.R
c1df11b93dc8ccab02e3b68bc041b2ec932d39b2
[]
no_license
gorkang/jsPsychHelpeR-Neely
0303b1800e62d8760480c026868ec70ebee600dc
8dcb345a50d8adb3fe7056dd4ca49f7599cc1fab
refs/heads/master
2023-08-10T19:05:52.523629
2021-09-21T06:05:44
2021-09-21T06:05:44
377,136,709
0
0
null
null
null
null
UTF-8
R
false
false
384
r
analysis_model_E1_table.R
##' .. content for \description{} (no empty lines) .. ##' ##' .. content for \details{} .. ##' ##' @title ##' @param model ##' @return ##' @author gorkang ##' @export analysis_model_E1_table <- function(model) { table1_model_E1 = sjPlot::tab_model(model, show.r2 = TRUE, show.icc = FALSE, show.re.var = FALSE) # show.std = TRUE, show.stat = TRUE return(table1_model_E1) }
b00deccd9f7d5bc7ffeb5594ebce66a8da61e0a1
600d14ceea86397d20d980ad7c7937d818899ae3
/plot2.R
4033510e3a2ac8812ed0f54c3de2d87ffd209c08
[]
no_license
ameyajDS/ExData_Plotting1
a4741f6cfd7eed8d102a33be222b89366fa41898
05ff8be597ff365497dd31d9c25f69c93c33f6dd
refs/heads/master
2021-07-06T05:55:20.779289
2017-10-01T18:02:08
2017-10-01T18:02:08
105,437,801
0
0
null
2017-10-01T11:35:15
2017-10-01T11:35:14
null
UTF-8
R
false
false
760
r
plot2.R
setwd("H:\\DataScience\\Coursera\\Exploratory Data Analysis\\Week 1\\Assignment") housePowerConsumption <- read.csv("household_power_consumption.txt",header = T, sep = ";", stringsAsFactors = F) housePowerConsumption$Date <- as.Date(housePowerConsumption$Date, "%d/%m/%Y") date1 <- as.Date("2007-02-01") date2 <- as.Date("2007-02-02") FebData <- housePowerConsumption[housePowerConsumption$Date >= date1 & housePowerConsumption$Date <= date2, ] dateTimeData <- strptime(paste(FebData$Date, FebData$Time, sep=" "), "%Y-%m-%d %H:%M:%S") Global_active_power <- as.numeric(FebData$Global_active_power) png("plot2.png", width = 480, height = 480) plot(dateTimeData, Global_active_power, type="l", xlab = "", ylab = "Global Active Power (kilowatts)") dev.off()
3f42e34a9937ae7739e40bc47483ab4eaa111610
de7bf478ce5b3bd796ab9bd8054b00e8b94cc9d2
/man/computeAlpha.Rd
303dda47545650c19cdb8fc5d2af47db6b321c69
[]
no_license
cran/FFD
b454ef48bf69f08d5014bb5b3a42f7df7401bb02
78eefbd15c03bf7362d9f39aca0be1c0d3d02c98
refs/heads/master
2022-11-11T01:55:17.186774
2022-11-08T09:10:06
2022-11-08T09:10:06
17,679,131
0
0
null
null
null
null
UTF-8
R
false
false
2,905
rd
computeAlpha.Rd
\name{computeAlpha} \alias{computeAlpha} %- Also NEED an '\alias' for EACH other topic documented here. \title{ FUNCTION to compute the herd-based alpha-errors (= 1 - herd sensitivity). } \description{ For a vector of herd sizes the herd-based alpha-errors (= 1-herd sensitivity) are computed for either limited or individual sampling; see Ziller et al. } \usage{ computeAlpha(nAnimalVec, method, sampleSizeLtd, herdSensitivity, intraHerdPrevalence, diagSensitivity, diagSpecificity = 1) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{nAnimalVec}{ Integer vector. Stock sizes of the herds. } \item{method}{ Character string. \code{"individual"} for individual sampling or \code{"limited"} for limited sampling. } \item{sampleSizeLtd}{ Integer. Required only if \code{method == "limited"}. Sample size for limited sampling, i.e., for each herd \code{sampleSizeLtd} animals are tested, or of the herd contains less than \code{sampleSizeLtd} animals the entire herd is tested. } \item{herdSensitivity}{ Numeric between 0 and 1. Required only if \code{method == "individual"}. Desired (minimal) hed sensitivity for individual sampling. The number of animals to test per herd is determined according to that value. } \item{intraHerdPrevalence}{ Numeric between 0 and 1. Intra-herd prevalence. The number of diseased animals per herd is computed as \code{max(1,round(intraHerdPrevalence*nAnimalVec))} (it is assumed that at least one animal is diseased). } \item{diagSensitivity}{ Numeric between 0 and 1. Sensitivity (= probability of a testpositive result, given the tested individual is diseased) of the diagnostic test. } \item{diagSpecificity}{ Numeric between 0 and 1. Specificity (= probability of a testnegative result, given the tested individual is not diseased) of the diagnostic test. The default value is 1, i.e., perfect specificity, and is recommended. } } \value{ Returns a vector containing the herd-based alpha-errors, where each entry in the vector corresponds to an entry in the input argument \code{nAnimalVec}. } \references{ M. Ziller, T. Selhorst, J. Teuffert, M. Kramer and H. Schlueter, "Analysis of sampling strategies to substantiate freedom from disease in large areas", Prev. Vet. Med. 52 (2002), pp. 333-343. } \author{ Ian Kopacka <ian.kopacka@ages.at> } \seealso{ Is used in the method \code{sample} for classes \code{\linkS4class{IndSampling}} and \code{\linkS4class{LtdSampling}}. } \examples{ data(sheepData) ## Compute the herd sensitivities usinh limited sampling: alphaVec <- computeAlpha(nAnimalVec = sheepData$nSheep, method = "limited", sampleSizeLtd = 7, intraHerdPrevalence = 0.2, diagSensitivity = 0.9) } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{methods}
f73a39c40cbe12247ca6b1aee3cabfda95dd2d87
e3c53ce91be6f5a3f54d1a978735db8091642905
/plot2.R
8ad03f76c5c39b2fbadbbe9a245e4d922c3a0b49
[]
no_license
WillHowell/ExData_Plotting1
760bb9f92c47adbf7b2fac38dcbf8581bec1c28c
eca91c63e7df6be5cde2e25dba658fe79d1ea83b
refs/heads/master
2021-01-21T07:14:56.209481
2014-05-11T21:56:30
2014-05-11T21:56:30
null
0
0
null
null
null
null
UTF-8
R
false
false
864
r
plot2.R
#load the lib library("sqldf") #if the table exists from a previous run, delete it sqldf("drop table if exists main.elec", dbname="testingdb") #read the raw text file into main.elec read.csv.sql("Data//household_power_consumption.txt", sql = "create table main.elec as select * from file", dbname = "testingdb",sep=";") #use sql to filter to the two days we're interessted in and load that into "filtered" filtered <- sqldf("select * from main.elec where Date = '1/2/2007' or Date = '2/2/2007'", dbname = "testingdb") #cast the character fields for date and time as a new datetime field filtered$datetime <- strptime(paste(filtered$Date, filtered$Time, sep=" "),"%d/%m/%Y %H:%M:%S") windows() plot(filtered$datetime,filtered$Global_active_power,type="l",ylab="Global Active Power (kilowatts)", xlab="") dev.copy(png, file="plot2.png") dev.off()
16714fad9682c3a72a1272389c494ba563ef01c2
9164e9c2f3d590795cbb763484dcbf32922b3333
/man/list_sessions.Rd
14309e070ca53c018cdcc2d150734ab2b17e6013
[ "MIT" ]
permissive
jonocarroll/tmuxr
83a33343208e3ace4a1a051b9b039a253cd3cd4e
135901ddd1417b9bdb5af7964f6aa498fbf95d06
refs/heads/master
2021-05-02T14:48:14.975903
2018-01-30T10:55:38
2018-01-30T10:55:38
null
0
0
null
null
null
null
UTF-8
R
false
true
254
rd
list_sessions.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/session.R \name{list_sessions} \alias{list_sessions} \title{List sessions.} \usage{ list_sessions() } \value{ A list of \code{tmuxr_session}s. } \description{ List sessions. }
01d4f4fb1255b5a26483ff1f318cb8c75f9ca1d6
e95cffe334a2b9202aeb729bc6b0acdcc10962d6
/data-raw/pokedex.R
22715eededb5dfca6fb8d77b1e95e915a8b7df5a
[ "CC-BY-4.0" ]
permissive
victordogo/pokechoosr
51c4ee17dc5b31f10355b4c3bd16667433dd4268
7e0b5bfe171d1bee5ef45e5ff34e5f7785ff057d
refs/heads/master
2023-07-18T08:50:58.421939
2021-09-06T19:30:09
2021-09-06T19:30:09
403,355,987
0
0
null
null
null
null
UTF-8
R
false
false
212
r
pokedex.R
## code to prepare `pokedex` dataset goes here pokedex <- readr::read_csv("data-raw/pokedex.csv") |> dplyr::select(-...1) # First column doesnt contain variables usethis::use_data(pokedex, overwrite = TRUE)
e18e0120a15f163ab01035d58bb53162c8c4adad
b4d3e44e7da647defaf290cc219a0011e9bab5f9
/man/get_power_apsim_met.Rd
0318cfaa1c4de4019b9197562ed87a4a646f2181
[]
no_license
femiguez/apsimx
81313570fbbbb915ba1519ad0cd95ac0d38dc4df
7df3b0a34d273e8035dbe22d457ed3911d07d7bc
refs/heads/master
2023-08-10T13:49:57.777487
2023-05-22T14:53:51
2023-05-22T14:53:51
194,395,452
34
21
null
2023-07-28T15:27:39
2019-06-29T10:54:27
R
UTF-8
R
false
true
1,452
rd
get_power_apsim_met.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/get_power_apsim_met.R \name{get_power_apsim_met} \alias{get_power_apsim_met} \title{Get NASA-POWER data for an APSIM met file} \usage{ get_power_apsim_met(lonlat, dates, wrt.dir = ".", filename = NULL) } \arguments{ \item{lonlat}{Longitude and latitude vector} \item{dates}{date ranges} \item{wrt.dir}{write directory} \item{filename}{file name for writing out to disk} } \value{ returns an object of class \sQuote{met} and writes a file to disk when filename is supplied. } \description{ Uses \code{\link[nasapower]{get_power}} from the \CRANpkg{nasapower} package to download data to create an APSIM met file. } \details{ This function requires the \CRANpkg{nasapower} package version 4.0.0. It looks like the earliest year you can request data for is 1984. If the filename is not provided it will not write the file to disk, but it will return an object of class \sQuote{met}. This is useful in case manipulation is required before writing to disk. } \examples{ \dontrun{ require(nasapower) ## This will not write a file to disk pwr <- get_power_apsim_met(lonlat = c(-93,42), dates = c("2012-01-01","2012-12-31")) ## Let's insert a missing value pwr[100, "radn"] <- NA summary(pwr) ## Check the met file check_apsim_met(pwr) ## Impute using linear interpolation pwr.imptd <- impute_apsim_met(pwr, verbose = TRUE) summary(pwr.imptd) check_apsim_met(pwr.imptd) } }
f1c80701418cbd9ef9dd9f806bb06dd1e647b95d
4c8abf106c9258d18818201e2ef75f35ac8b58f1
/plot1.R
b591f7e69609f823789c416b15aeab7df72d972c
[]
no_license
VaibhavBarot/ExData_Plotting1
a95f43800dcee28f0f8fdfae5fc1fbea2ebc56dd
0dd57a430005a944825ac2e184a419b80641154a
refs/heads/master
2022-10-01T11:41:57.779616
2020-06-09T12:21:50
2020-06-09T12:21:50
270,921,568
0
0
null
2020-06-09T06:29:40
2020-06-09T06:29:39
null
UTF-8
R
false
false
468
r
plot1.R
#For reading only 2 days in Feb csv<-read.table("consumption.txt",sep=";",skip=66637,nrow=2880) #Getting headers by reading only first line colnames(csv)<-unlist(strsplit(readLines("consumption.txt",n=1),";")) #Keeping main and x label empty so we can use title function hist<-hist(csv$Global_active_power,col=2,main="",xlab="") title("Global Active Power") title(xlab="Global Active Power (kilowatts)") #Saving as png dev.copy(png,"plot1.png") dev.off()
189157b7310e094a7b2f919c28a4cd8bce9e6f3a
b055d27e0b57dbc749fdeced6960621820488c71
/man/graphical.node.patterns.Rd
3c951a3051d3c068c1b326d49f930231a58f38c3
[]
no_license
vanderleidebastiani/daee
4bf43ac80e5b4ec5fcf3e883fb70ad78e5729aed
2550c1ef4119f539cbf4d7c68d0619d324e6c19e
refs/heads/master
2021-06-20T05:29:14.264681
2021-01-20T18:16:01
2021-01-20T18:16:01
23,359,900
0
3
null
2018-06-20T08:11:58
2014-08-26T17:08:48
R
UTF-8
R
false
true
2,839
rd
graphical.node.patterns.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/graphical.node.patterns.R \encoding{UTF-8} \name{graphical.node.patterns} \alias{graphical.node.patterns} \title{Define graphical parameters to plot phylogenetic tree.} \usage{ graphical.node.patterns( tree, nodes, basicpattern, nodespatterns, include.node = TRUE, force.order = TRUE ) } \arguments{ \item{tree}{phylogeny as an object of class "phylo".} \item{nodes}{a vector with node label to search the edges to change the basic graphical parameter.} \item{basicpattern}{the basic pattern for graphical parameter. This is apply for all edges.} \item{nodespatterns}{a vector with new graphical parameter for each node label. This change the basic graphical parameter in each node.} \item{include.node}{logical argument (TRUE or FALSE) to specify if edge of each node is include in change (default include.node = TRUE).} \item{force.order}{logical argument (TRUE or FALSE) to specify if force the search as according to edges (default force.order = TRUE).} } \value{ A vector with the new graphical parameters for each edge in phylogenetic tree. } \description{ Function to define graphical parameters to each edge when draw a phylogenetic tree. See details. } \details{ This function can be used to especify diferent graphical parameters (e.g. color, width and line types) for specific nodes when draw a phylogenetic tree. First, the basicpattern argument is defined for all edges of phylogenetic tree and when the basic pattern is changed in all edge within of each node, following the nodespatterns specify. The argument force.order specify if changes following order in nodes arguments step by step (this case, some changes may have no effect) or change are done from root to tips. } \examples{ set.seed(10) tree <- rtree(15) tree <- makeNodeLabel(tree) plot.phylo(tree, show.node.label = TRUE) edge.col <- graphical.node.patterns(tree, nodes = c("Node2", "Node8"), basicpattern = "black", nodespatterns = c("red","blue")) edge.col # Color vector for each edge plot.phylo(tree, show.node.label = TRUE, edge.color = edge.col) edge.width <- graphical.node.patterns(tree, nodes = c("Node11","Node3"), basicpattern = 1, nodespatterns = 5, include.node = FALSE) edge.width # width vector for each edge plot.phylo(tree, show.node.label = TRUE, edge.width = edge.width) tree <- rtree(250) tree <- makeNodeLabel(tree) plot(tree, show.tip.label = FALSE) edge.col <- graphical.node.patterns(tree, nodes = tree$node.label, basicpattern = "black", nodespatterns = rainbow(length(tree$node.label))) edge.col plot.phylo(tree, edge.color = edge.col, show.tip.label = FALSE) } \seealso{ \code{\link{plot.phylo}} \code{\link{plotcollapse.phylo}} } \author{ Vanderlei Julio Debastiani <vanderleidebastiani@yahoo.com.br> } \keyword{daee}
9baaedeeb33e961516608604fd07480b5eced7e3
a5e201d84f0a35006853237c49a380c93bf9facc
/build.R
6664d3e030083917a2004a93264f889aec541df9
[]
no_license
jbryer/likert
308d4dc7d14417536c72f7d78968600bc606b78b
6fc296a44679c103bae8a26b7aeceac2fc857a22
refs/heads/master
2023-03-15T12:32:28.404055
2022-07-27T18:16:14
2022-07-27T18:16:14
4,225,364
260
125
null
2023-06-20T07:09:21
2012-05-04T14:02:08
HTML
UTF-8
R
false
false
1,349
r
build.R
library(devtools) #Package building document() install() build() test() #Rbuild('likert',vignettes=FALSE) build_vignettes() check(cran=TRUE) # Build website pkgdown::build_site() # Ready for CRAN? release() ##### Basic testing library(likert) ls('package:likert') #Run shiny app. See also shinyLikert to run from the installed package. shiny::runApp('likert/inst/shiny') ##### testthat usethis::use_testthat() usethis::use_test('duplicate_gruops_124') ##### Data setup. We will use a few of the student items from North America PISA require(pisa) data(pisa.student) pisaitems <- pisa.student[,substr(names(pisa.student), 1,5) %in% c('CNT', #Country 'ST24Q', #Read attitude 'ST25Q', #Like reading 'ST26Q', #Online 'ST27Q', #Study 'ST34Q', #Teachers 'ST36Q', #Lessons 'ST37Q', #Stimulate 'ST38Q', #Strategies 'ST39Q', #Library 'ST41Q', #Text 'ST42Q', #Summary paste('PV', 1:5, 'MATH', sep=''), paste('PV', 1:5, 'READ', sep=''), paste('PV', 1:5, 'SCIE', sep='') )] pisaitems <- pisaitems[pisaitems$CNT %in% c('Canada','Mexico','United States'),] pisaitems$CNT <- as.factor(as.character(pisaitems$CNT)) names(pisaitems); nrow(pisaitems); ncol(pisaitems) save(pisaitems, file='likert/data/pisaitems.rda') tools::resaveRdaFiles('likert/data/pisaitems.rda')
76987aa1094eba7922561559f452a59cc847e5e8
f45e318e27acea2d99ff66e9f12bdc97413a0b73
/scripts/CGHcallPlus.R
9fb5b12d8df43425bdbf8082875c1558907ebc3d
[]
no_license
tgac-vumc/QDNAseq.snakemake
e311b9df21c1474b6eb5b66e7a2d45f863ba0dc1
af6b76b7301f4174bc69a8dcc87bcb2e5aacaa62
refs/heads/master
2023-08-19T13:43:19.523826
2023-08-04T12:03:00
2023-08-04T12:03:00
112,479,307
1
0
null
null
null
null
UTF-8
R
false
false
17,761
r
CGHcallPlus.R
#this script contain the functions: make_cghRawPlus, frequencyPlot, segmentDataWeighted, CGHregionsPlus, #regioningPlus, repdata , WECCA.heatmapPlus, mark.genes , mark.bed, add.cytobands , add.genes, plot.profiles msg <- snakemake@params[["suppressMessages"]] if (msg){ suppressMessages(library(CGHcall)) suppressMessages(library(CGHregions)) suppressMessages(library(WECCA)) suppressMessages(library(matrixStats)) suppressMessages(library(QDNAseq)) } else{ library(CGHcall) library(CGHregions) library(WECCA) library(matrixStats) library(QDNAseq) } # originally: QDNAseqReadCounts instead of QDNAseqSignals setMethod('plot', signature(x='cghRaw', y='missing'), getMethod('plot', signature=c(x='QDNAseqSignals', y='missing'))) setMethod('plot', signature(x='cghSeg', y='missing'), getMethod('plot', signature=c(x='QDNAseqSignals', y='missing'))) setMethod('plot', signature(x='cghCall', y='missing'), getMethod('plot', signature=c(x='QDNAseqSignals', y='missing'))) setMethod("frequencyPlot", signature(x="cghCall", y="missing"), frequencyPlotCalls) .CGHcallPlus <- new.env() evalq({ setMethod("frequencyPlot", signature(x="cghRegions", y="missing"), function (x, y, main='Frequency Plot', gaincol='red', losscol='blue', misscol=NA, build='GRCh37',... ) #TLos changed colors loss bleu, gain red { chrom <- chromosomes(x) pos <- bpstart(x) pos2 <- bpend(x) uni.chrom <- unique(chrom) chrom.lengths <- CGHbase:::.getChromosomeLengths(build)[as.character(uni.chrom)] chrom.ends <- integer() cumul <- 0 for (j in uni.chrom) { pos[chrom > j] <- pos[chrom > j] + chrom.lengths[as.character(j)] pos2[chrom > j] <- pos2[chrom > j] + chrom.lengths[as.character(j)] cumul <- cumul + chrom.lengths[as.character(j)] chrom.ends <- c(chrom.ends, cumul) } names(chrom.ends) <- names(chrom.lengths) calls <- regions(x) loss.freq <- rowMeans(calls < 0) gain.freq <- rowMeans(calls > 0) plot(NA, xlim=c(0, max(pos2)), ylim=c(-1,1), type='n', xlab='chromosomes', ylab='frequency', xaxs='i', xaxt='n', yaxs='i', yaxt='n', main=main,...) if (!is.na(misscol)) { rect(0, -1, max(pos2), 1, col=misscol, border=NA) rect(pos, -1, pos2, 1, col='white', border=NA) } rect(pos, 0, pos2, gain.freq, col=gaincol, border=gaincol) rect(pos, 0, pos2, -loss.freq, col=losscol, border=losscol) box() abline(h=0) if (length(chrom.ends) > 1) for (j in names(chrom.ends)[-length(chrom.ends)]) abline(v=chrom.ends[j], lty='dashed') ax <- (chrom.ends + c(0, chrom.ends[-length(chrom.ends)])) / 2 axis(side=1,at=ax,labels=uni.chrom,cex=.2,lwd=.5,las=1,cex.axis=1,cex.lab=1) axis(side=2, at=c(-1, -0.5, 0, 0.5, 1), labels=c('100%', ' 50%', '0%', '50%', '100%'), las=1) mtext('gains', side=2, line=3, at=0.5) mtext('losses', side=2, line=3, at=-0.5) ### number of data points mtext(paste(nrow(x), 'regions'), side=3, line=0, adj=0) }) make_cghRawPlus <- function (input) { if (class(input) == "character") input <- read.table(input, header = T, sep = "\t", fill = T, quote = "") if (class(input[, 2]) == "factor") input[, 2] <- as.character(input[, 2]) if (class(input[, 2]) == "character") { input[, 2] <- sub("^chr", "", input[, 2]) input[input[, 2] == "X", 2] <- "23" input[input[, 2] == "Y", 2] <- "24" input[input[, 2] == "MT", 2] <- "25" input[, 2] <- as.integer(input[, 2]) } if (any(duplicated(input[, 1]))) { replicate.probes <- unique(input[, 1][duplicated(input[, 1])]) uniques <- input[!input[, 1] %in% replicate.probes, ] replicates <- input[input[, 1] %in% replicate.probes, ] replicates.avg <- aggregate(replicates[, -1], list(probe=replicates[, 2]), median, na.rm=TRUE) input <- rbind(uniques, replicates.avg) } input <- input[order(input[, 2], input[, 3]), ] copynumber <- as.matrix(input[, 5:ncol(input)]) rownames(copynumber) <- input[, 1] if (ncol(copynumber) == 1) colnames(copynumber) <- colnames(input)[5] annotation <- data.frame(Chromosome = input[, 2], Start = input[, 3], End = input[, 4], row.names = input[, 1]) metadata <- data.frame(labelDescription = c("Chromosomal position", "Basepair position start", "Basepair position end"), row.names = c("Chromosome", "Start", "End")) dimLabels <- c("featureNames", "featureColumns") annotation <- new("AnnotatedDataFrame", data = annotation, dimLabels = dimLabels, varMetadata = metadata) result <- new("cghRaw", copynumber = copynumber, featureData = annotation) } environment(make_cghRawPlus) <- environment(CGHbase:::make_cghRaw) make_cghRaw <- make_cghRawPlus segmentDataWeighted <- function (input, method = "DNAcopy", ...) { if (method == "DNAcopy") { CNA.object <- DNAcopy::CNA(copynumber(input), chromosomes(input), bpstart(input), data.type = "logratio") cat("Start data segmentation .. \n") segmented <- segment(CNA.object, ...) numclone <- segmented$output$num.mark smrat <- segmented$output$seg numsmrat <- cbind(smrat, numclone) repdata <- function(row) { rep(row[1], row[2]) } makelist <- apply(numsmrat, 1, repdata) joined <- unlist(makelist) rm(makelist) joined <- matrix(joined, ncol = ncol(input), byrow = FALSE) joined <- CGHcall:::.assignNames(joined, input) result <- CGHcall:::.segFromRaw(input, joined) } result } CGHregionsPlus <- function(input, ...) { regions <- CGHregions:::CGHregions(input, ...) # End positions of regions should be the end position of the last data point of that region, # but instead CGHregions returns the start position of the last data point. # Check if that is indeed the case: if (class(input) == 'cghCall') { if (sum(regions@featureData@data$End %in% input@featureData@data$Start) > sum(regions@featureData@data$End %in% input@featureData@data$End)) for (row in rownames(regions@featureData@data)) regions@featureData@data[row, 'End'] <- input@featureData@data[input@featureData@data$Chromosome == regions@featureData@data[row, 'Chromosome'] & input@featureData@data$Start == regions@featureData@data[row, 'End'], 'End'][1] } regions } environment(CGHregionsPlus) <- environment(CGHregions:::CGHregions) CGHregions <- CGHregionsPlus regioningPlus <- function (cghdata.called, threshold = 0.00001, cghdata.regions = NULL) { find.reg.modus <- function(x) { if (nrow(x) == 1) return(x) splitter <- list() splitter[[1]] <- c(1) index.temp <- 1 j <- 1 for (i in 1:(dim(x)[1] - 1)) { if (all(x[i, ] == x[i + 1, ])) { index.temp <- c(index.temp, i + 1) splitter[[j]] <- index.temp } else { index.temp <- i + 1 j <- j + 1 splitter[[j]] <- index.temp } } region.details <- NULL for (i in 1:length(splitter)) { region.details <- rbind(region.details, c(min(splitter[[i]]), max(splitter[[i]]))) } modus <- which.max(region.details[, 2] - region.details[, 1] + 1) return(x[region.details[modus[1], 1], ]) } cat("CGHregions of hard call data...") if (is.null(cghdata.regions)) cghdata.regions <- CGHregionsPlus(cghdata.called, averror = threshold) cat("...done", "\n") print(paste("threshold used:", threshold, sep = " ")) calls.annotation <- pData(featureData(cghdata.called)) regions.annotation <- pData(featureData(cghdata.regions)) cat("Map regions to clones...") reg.to.clones <- list() counter <- 0 for (chr in unique(regions.annotation[, 1])) { reg.ann.temp <- regions.annotation[regions.annotation[, 1] == chr, 1:4] for (r in 1:dim(reg.ann.temp)[1]) { counter <- counter + 1 A1 <- which(calls.annotation[, 1] == chr) A2 <- which(calls.annotation[, 2] >= reg.ann.temp[r, 2]) A3 <- which(calls.annotation[, 3] <= reg.ann.temp[r, 3]) reg.to.clones[[counter]] <- intersect(intersect(A1, A2), A3) } } cat("...done", "\n") cghdata.probs <- numeric() for (i in 1:dim(calls(cghdata.called))[2]) { cghdata.probs <- cbind(cghdata.probs, cbind(probloss(cghdata.called)[, i], probnorm(cghdata.called)[, i], probgain(cghdata.called)[, i], probamp(cghdata.called)[, i])) } cat("Calculate mode soft call signature for each region...") cghdata.regprobs <- numeric() for (i in 1:length(reg.to.clones)) { cghdata.regprobs <- rbind(cghdata.regprobs, find.reg.modus(cghdata.probs[reg.to.clones[[i]], , drop = FALSE])) } cat("...done", "\n") softcalls.samplenames <- character() for (i in 1:dim(calls(cghdata.called))[2]) { if (dim(cghdata.regprobs)[2]/dim(calls(cghdata.called))[2] == 3) { softcalls.samplenames <- c(softcalls.samplenames, paste(c("probloss_", "probnorm_", "probgain_"), colnames(regions(cghdata.regions))[i], sep = "")) } if (dim(cghdata.regprobs)[2]/dim(calls(cghdata.called))[2] == 4) { softcalls.samplenames <- c(softcalls.samplenames, paste(c("probloss_", "probnorm_", "probgain_", "probamp_"), colnames(regions(cghdata.regions))[i], sep = "")) } } colnames(cghdata.regprobs) <- softcalls.samplenames rownames(cghdata.regprobs) <- rownames(regions(cghdata.regions)) regdata <- list() regdata$ann <- regions.annotation regdata$hardcalls <- regions(cghdata.regions) regdata$softcalls <- cghdata.regprobs return(regdata) } environment(regioningPlus) <- environment(WECCA:::regioning) regioning <- regioningPlus WECCA.heatmapPlus <- function (cghdata.regioned, dendrogram, build='GRCh37', ...) { nclasses <- sort(unique(as.numeric(cghdata.regioned$hardcalls))) cols <- c('lightgreen', 'darkgreen', 'lightgray', 'darkslategray') chr.color <- rep(1, nrow(cghdata.regioned$ann)) centromeres <- CGHbase:::.getCentromere(build) for (chr in unique(cghdata.regioned$ann$Chromosome)) chr.color[cghdata.regioned$ann$Chromosome == chr & (cghdata.regioned$ann$Start + cghdata.regioned$ann$End) / 2 > centromeres[chr]] <- 2 even <- cghdata.regioned$ann$Chromosome %% 2 == 0 chr.color[even] <- chr.color[even] + 2 chr.color <- cols[chr.color] Y <- rep(FALSE, dim(cghdata.regioned$hardcalls)[1]) for (i in 2:(dim(cghdata.regioned$ann)[1])) { if ((cghdata.regioned$ann[i - 1, 1] != cghdata.regioned$ann[i, 1])) { Y[i] <- TRUE } } Y[1] <- TRUE begin.chr <- rep("", dim(cghdata.regioned$ann)[1]) begin.chr[Y] <- cghdata.regioned$ann[Y, 1] color.coding <- c("-2"="darkblue", "-1"="blue", "0"="black", "1"="red", "2"="darkred")[as.character(nclasses)] #TLos changed colors loss bleu, gain red. heatmap(cghdata.regioned$hardcalls, Colv = as.dendrogram(dendrogram), Rowv=NA, col=color.coding, labRow=begin.chr, RowSideColors=chr.color, scale="none", ...) } environment(WECCA.heatmapPlus) <- environment(WECCA:::WECCA.heatmap) WECCA.heatmap <- WECCA.heatmapPlus mark.genes <- function(symbols, chrs=1:24, build='GRCh37', side=3, line=-1, ...) { genes <- AnnotationDbi::select(Homo.sapiens::Homo.sapiens, keys=keys(Homo.sapiens::Homo.sapiens, keytype='SYMBOL'), cols=c('CHRLOC', 'CHRLOCEND'), keytype='SYMBOL') genes$CHRLOCCHR[genes$CHRLOCCHR == 'X'] <- '23' genes$CHRLOCCHR[genes$CHRLOCCHR == 'Y'] <- '24' genes$CHRLOCCHR[genes$CHRLOCCHR == 'MT'] <- '25' genes <- genes[genes$CHRLOCCHR %in% as.character(1:25),] genes$CHRLOCCHR <- as.integer(genes$CHRLOCCHR) if (length(side) == 1) side <- rep(side, length(symbols)) if (length(line) == 1) line <- rep(line, length(symbols)) chrom <- genes$CHRLOCCHR pos <- abs(genes$CHRLOC) pos2 <- abs(genes$CHRLOCEND) uni.chrom <- chrs chrom.lengths <- CGHbase:::.getChromosomeLengths(build)[as.character(uni.chrom)] for (j in uni.chrom) { pos[chrom > j] <- pos[chrom > j] + chrom.lengths[as.character(j)] pos2[chrom > j] <- pos2[chrom > j] + chrom.lengths[as.character(j)] } genes$pos <- pos genes$pos2 <- pos2 for (i in 1:length(symbols)) { matches <- genes[genes$SYMBOL == symbols[i],] rect(matches$pos, par('usr')[3], matches$pos2, par('usr')[4], col='#88888888', border='#88888888') axis(side=side[i], at=matches$pos+(matches$pos2-matches$pos)/2, labels=rep(symbols[i], nrow(matches)), tick=FALSE, line=line[i], cex.axis=.75, ...) } } mark.bed <- function(bed, chrs=1:24, build='GRCh37', col='#88888888') { if (class(bed) == 'character') bed <- read.table(bed, sep='\t', as.is=TRUE) colnames(bed) <- c('chromosome', 'start', 'end', 'name', 'score', 'strand') bed$chromosome <- sub('^chr', '', bed$chromosome) bed$chromosome[bed$chromosome == 'X'] <- '23' bed$chromosome[bed$chromosome == 'Y'] <- '24' bed$chromosome[bed$chromosome %in% c('M', 'MT')] <- '25' bed$chromosome <- as.integer(bed$chromosome) # bed$start <- bed$start + 1 chrom <- bed$chromosome pos <- bed$start pos2 <- bed$end uni.chrom <- chrs chrom.lengths <- CGHbase:::.getChromosomeLengths(build)[as.character(uni.chrom)] for (j in uni.chrom) { pos[chrom > j] <- pos[chrom > j] + chrom.lengths[as.character(j)] pos2[chrom > j] <- pos2[chrom > j] + chrom.lengths[as.character(j)] } bed$pos <- pos bed$pos2 <- pos2 rect(bed$pos, -5.3, bed$pos2, 5.3, col=col, border=col) } add.cytobands <- function(dat, genome.build = 'GRCh37') { bands <- read.table(paste('http://www.cangem.org/download.php?platform=CG-PLM-6&flag=', genome.build, sep=''), sep='\t', header=TRUE, as.is=TRUE) colnames(bands) <- tolower(colnames(bands)) colnames(bands)[colnames(bands)=='chr'] <- 'chromosome' rownames(bands) <- bands[,1] bands$chromosome[bands$chromosome=='X'] <- '23' bands$chromosome[bands$chromosome=='Y'] <- '24' bands$chromosome[bands$chromosome=='MT'] <- '25' bands$chromosome <- as.integer(bands$chromosome) dat$cytoband <- NA tmp <- colnames(dat) colnames(dat) <- tolower(colnames(dat)) for (band in rownames(bands)) { index <- !is.na(dat$chromosome) & dat$chromosome == bands[band, 'chromosome'] & !is.na(dat$start) & dat$start >= bands[band, 'start'] & !is.na(dat$start) & dat$start <= bands[band, 'end'] if (length(index)>0) dat[index, 'startband'] <- bands[band, 'band'] index <- !is.na(dat$chromosome) & dat$chromosome == bands[band, 'chromosome'] & !is.na(dat$end) & dat$end >= bands[band, 'start'] & !is.na(dat$end) & dat$end <= bands[band, 'end'] if (length(index)>0) dat[index, 'endband'] <- bands[band, 'band'] } dat$startband[is.na(dat$startband)] <- 'unknown' dat$endband[is.na(dat$endband)] <- 'unknown' dat$cytoband <- paste(dat$startband, '-', dat$endband, sep='') dat$cytoband[dat$startband==dat$endband] <- dat$startband[dat$startband==dat$endband] dat$startband <- NULL dat$endband <- NULL colnames(dat) <- tmp dat } add.genes <- function(dat, genome.build = 'GRCh37') { if (!exists('genes')) genes <<- read.table(paste('http://www.cangem.org/download.php?platform=CG-PLM-26&flag=', genome.build, sep=''), sep='\t', header=TRUE, row.names=1, as.is=TRUE) # genes <- genes[-grep('pseudo', genes$type),] genes <- genes[genes$type %in% c('protein_coding', 'miRNA'),] genes$chromosome[genes$chromosome=='X'] <- '23' genes$chromosome[genes$chromosome=='Y'] <- '24' genes$chromosome[genes$chromosome=='MT'] <- '25' genes$chromosome <- as.integer(genes$chromosome) colnames(dat) <- tolower(colnames(dat)) for (region in rownames(dat)) { index <- genes$chromosome == dat[region, 'chromosome'] & genes$end > dat[region, 'start'] & genes$start < dat[region, 'end'] dat[region, 'genes'] <- sum(index) dat[region, 'symbols'] <- paste(genes[index, 'symbol'], collapse=';') } dat } plot.profiles <- function(cgh, directory, byChr=FALSE) { tmp <- sampleNames(cgh) if (!file.exists(directory)) dir.create(directory) if ('filter' %in% colnames(fData(cgh))) { chrs <- unique(chromosomes(cgh)[fData(cgh)$filter]) } else { chrs <- unique(chromosomes(cgh)) } for (i in 1:length(sampleNames(cgh))) { if (byChr) { for (chr in chrs) { png(file.path(directory, paste(tmp[i], '-chr', chr, '.png', sep='')), width=297, height=210, units='mm', res=150) plot(cgh[chromosomes(cgh) == chr,i], ylab=expression(normalized~log[2]~read~count), dotres=1) dev.off() } } else { png(file.path(directory, paste(tmp[i], '.png', sep='')), width=297, height=210, units='mm', res=150) plot(cgh[,i], ylab=expression(normalized~log[2]~read~count), dotres=1) dev.off() } } } }, envir=.CGHcallPlus) attach(.CGHcallPlus) # EOF
fc6af9ad9319360901ed4797eb2a1183250763f3
26e0c26e97e178d9cd8691a5bd7851d97470ca91
/R-libraries/spm/R/generate.MVU.R
e5fd8d31e4b93787259033bbf9f51b456ef851e5
[]
no_license
alistairdunn1/SPM
61ec762569cf7adb209dd78e0db01ac45b19845b
33a356d7b1dff6d2f03ef7008b04848fa688435d
refs/heads/master
2022-11-16T18:33:05.511891
2022-10-17T05:10:56
2022-10-17T05:10:56
179,891,504
1
6
null
2019-04-06T22:03:20
2019-04-06T22:03:20
null
UTF-8
R
false
false
1,170
r
generate.MVU.R
#' Generate a multivariate uniform distribution based on the bounds for the extimated parameters #' #' @author Sophie Mormede #' @param file the name of the input file containing the estimated fits #' @param path Optionally, the path to the file #' @param output.file The name of the output file to write randomly generated values #' @param sample.size The number f samples to generate #' #' @export #' "generate.MVU" <- function(file, path = "", output.file, sample.size = 1) { run <- extract(file, path) parbnds <- run$"estimate_summary"[[1]]$data rand <- runif(n = sample.size * nrow(parbnds), min = parbnds$lower_bound, max = parbnds$upper_bound * 1.0000000000001) rand <- matrix(rand, nrow = sample.size, byrow = T) colnames(rand) <- parbnds$parameter if (!missing(output.file)) { outfile <- spm.make.filename(file = output.file, path = path) write.table(x = signif(rand, 6), file = outfile, append = FALSE, quote = FALSE, sep = " ", row.names = FALSE, col.names = TRUE) } invisible(list("header" = names(rand), "parameters" = parbnds$value, "bounds" = parbnds[, c("lower_bound", "upper_bound")], "MVU" = rand)) }
856adf51db49ea4c78a22145bf97e3acd1d37907
2656a078cef4fbb1a32b78dc946e945b5424ba35
/man/blood.Rd
1b5183f8eed83e41ece3aeb2e0b3878b87aadee8
[]
no_license
fanatichuman/geomnet
fa5ccf2049eae8f6131160815442fff779cb221f
6aff9ca74a581e773e8b7f502863c8bef483e473
refs/heads/master
2021-01-24T20:25:07.135518
2016-07-20T16:00:24
2016-07-20T16:00:24
64,494,837
1
0
null
2016-07-29T16:27:48
2016-07-29T16:27:47
R
UTF-8
R
false
true
1,279
rd
blood.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.r \docType{data} \name{blood} \alias{blood} \title{Network of blood types (directed)} \format{A list of two data frames: \itemize{ \item the edges data set consists of three variables of length 27: \itemize{ \item from, to: factor variables of blood types describing the relationship 'is compatible with' \item group\_to: factor variable with levels 'same' and 'diff' for same or different blood type group not regarding the rho-gam factor. } \item the vertices data set consists of five variables and 32 rows: \itemize{ \item label: factor variable of blood types, \item type: factor variable of blood type, not regarding the rhesus factor, \item rho: factor variable: 'pos' and 'neg' describing the rhesus factor, \item Ethnicity: factor variable of four variables: 'Caucasians', 'African.American', 'Hispanic', and 'Asian', \item Predominance: numeric variable consisting of the percentage points of each blood type within each ethnicity. } }} \usage{ blood } \description{ A list of two datasets, vertices and edges, containing information on blood type (see \url{http://www.redcrossblood.org/learn-about-blood/blood-types}). The variables are as follows: } \keyword{datasets}
b95f31fb1d6899aba47d478251146d803144f1b2
78b7de62e2e5b80503c5077da973fb81e4b326bf
/Readme.R
e39f1460e769162de3a514a31666e05790b1d189
[]
no_license
salviadr/breast_cancer_panel
cd619049c36098338b9c49a5a483c90bc81ce729
e69a72c5b0b14b97dfdfddf47818a28203ad6ba1
refs/heads/master
2021-01-20T10:13:01.938473
2016-04-08T18:08:14
2016-04-08T18:08:14
null
0
0
null
null
null
null
UTF-8
R
false
false
1,560
r
Readme.R
## Do not run this, this is only for detail information of related analysis in BreastCancer project Here, we use "~" to present the main folder of breast_cancer. variants/: variants calling for our cohort data and controls. pedigree: All the pedigree information. code: Main code for variant statistics and single sample variant calling and filtering. families: AD and AR inherited models based variant calling for families. data: useful data tables. AJconVariantCalling: AJ controls variant tables. HIconVariantCalling: HI controls variant tables. trios: trios information. FreezeOneCommon: variant calling for AJ cases, we focused on the capture kits overlapped region for AJ cases and controls. HIdepth: variant depth from vcf files (HIs). AHdepth: variant depth from vcf files (AJs). genelist/: collected gene list information, such as, tumor suppressor, cancer driver, DNA repair and others. pedigree/: old version pedigree figures. depthOfcoverage/: Depth of coverage for different batches samples both case and control based on bam files. code: fix bad read group and limited number jobs in our PowerEdge cluster, and depth calling for different batches. data: data source and tables for bam files. Regeneron, RGN3, RGN4, SSC: the case-control used in AJ analysis, depth information for samples. AJcontrol and HIcontrol: controls depth information for AJ and HI. WES_Sinai/: Regeneron WES and Sinai data comparsion. Panel/: Main analysis based on Panel gene sets. geneexpression and somatic_mutation: Data source from TCGA.
b9b3e5a3a7f31b437da6130f894ccbb973c2587b
863e9fd3a3a0d5a1b36d4486e3f3c23f48d247f5
/init.R
e920ccb2716f06ba0e98af8c772a2066cd0bedb0
[]
no_license
iceiony/customer_flow_snippets
ed224b9c6dc0b3b55779ec730b5b65d3059da002
b9c99428db91d0c5d11fa23598fcdbb67a0b9625
refs/heads/master
2020-05-25T14:22:10.304039
2017-03-14T11:00:18
2017-03-14T11:00:18
84,939,034
0
0
null
null
null
null
UTF-8
R
false
false
385
r
init.R
library('pryr') library('plyr') library('dplyr') library('reshape2') library('ggplot2') library('parallel') library('tictoc') library('ptw') library('zoo') # source all functions from mlp_functions folder sources <- lapply(list.files('functions', '[.]R$', full.names = T), source) elapsed <- function(msg){ toc() message(msg) tic() } start_date <- as.Date('2015-06-25')
11a9a87ad2f9c2d717649e67b9770fe4c5ec9ec4
acde47fe52279c49da31500d3262c886aed590e2
/R/grid3Covariates.R
1e31aa5f4951dda41452800870fbeb99c1cd4025
[]
no_license
wpgp/grid3Covariates
7943f07fa46a25f218de0456a6d5cc1de1396948
1685eeff1db8359052c82fb54f960433d0d1c01e
refs/heads/master
2020-03-22T10:44:42.474591
2018-07-06T03:27:05
2018-07-06T03:27:05
139,924,285
2
1
null
null
null
null
UTF-8
R
false
false
9,829
r
grid3Covariates.R
# Function to get time difference in human readable format # Input is start time and end time # If "frm" is set to "hms" then output will be h:m:s # otherwise only hours will be returned tmDiff <- function(start, end, frm="hms") { dsec <- as.numeric(difftime(end, start, units = c("secs"))) hours <- floor(dsec / 3600) if (frm == "hms" ){ minutes <- floor((dsec - 3600 * hours) / 60) seconds <- dsec - 3600*hours - 60*minutes out=paste0( sapply(c(hours, minutes, seconds), function(x) { formatC(x, width = 2, format = "d", flag = "0") }), collapse = ":") return(out) }else{ return(hours) } } # Function to download file from ftp server # # @param file_path is a path to a remoute file # @param dest_file is a path where downloaded file will be stored # @param username ftp username to WorldPop ftp server # @param password ftp password to WorldPop ftp server # @param quiet If TRUE, suppress status messages (if any), and the progress bar. # @param method Method to be used for downloading files. # Current download methods are "internal", "wininet" (Windows only) "libcurl", # "wget" and "curl", and there is a value "auto" # @rdname grid3DownloadFileFromFTP #' @importFrom utils read.csv grid3DownloadFileFromFTP <- function(file_path, dest_file, username, password, quiet, method="auto") { grid3FTP <- "ftp.worldpop.org.uk" credentials <- paste(username, password, sep = ":") file_remote <-paste0('ftp://',credentials,'@',grid3FTP ,file_path) tmStartDw <- Sys.time() checkStatus <- tryCatch( { utils::download.file(file_remote, destfile=dest_file,mode="wb",quiet=quiet, method=method) }, error=function(cond){ message(paste("URL does not seem to exist:", file_remote)) message("Here's the original error message:") message(cond) }, warning=function(cond){ message(paste("URL caused a warning:", file_remote)) message("Here's the original warning message:") message(cond) }, finally={ if (!quiet){ tmEndDw <- Sys.time() #message(paste("Processed URL:", file_remote)) message(paste("It took ", tmDiff(tmStartDw ,tmEndDw,frm="hms"), "to download" )) } } ) if(inherits(checkStatus, "error") | inherits(checkStatus, "warning")){ return(NULL) } else{ return(1) } } # grid3GetCSVFileAllCovariates function to download csv # file from WorldPop ftp server # containing a list of avalible Covariates. The csv file # will be stored in a temporary R folder with a temporary # file name and pattern grid3AllCovariates. This file will be used # internally during querying and downloading datasets. # # @param username ftp username to WorldPop ftp server # @param password ftp password to WorldPop ftp server # @param quiet If TRUE, suppress status messages (if any), and the progress bar. # @param frCSVDownload If TRUE, a new wpgAllCovariates.csv file will # be downloaded and the old one removed. # @rdname grid3GetCSVFileAllCovariates # @return Data frame of all covariates. #' @importFrom utils read.csv grid3GetCSVFileAllCovariates <- function(username, password, frCSVDownload=FALSE) { grid3AllCSVFilesPath <- paste0(tempdir(),"/grid3covariates.csv") if(!file.exists(grid3AllCSVFilesPath) | frCSVDownload){ credentials <- paste(username,password,sep = ":") file_remote <-paste0('/Covariates/grid3covariates.csv') grid3DownloadFileFromFTP(file_remote, grid3AllCSVFilesPath, username, password, quiet=TRUE) } df.all.Covariates = utils::read.csv(grid3AllCSVFilesPath, stringsAsFactors=FALSE) return(df.all.Covariates) } #' grid3ListCountries function will return a list of the country #' avalible to download #' #' @param username ftp username to WorldPop ftp server #' @param password ftp password to WorldPop ftp server #' @param verbose quiet If TRUE, suppress status messages (if any) #' @param frCSVDownload If TRUE, a new wpgAllCovariates.csv file will downloaded #' @rdname grid3ListCountries #' @return Dataframe #' @export grid3ListCountries <- function(username, password, verbose=FALSE, frCSVDownload=FALSE) { df <- grid3GetCSVFileAllCovariates(username, password, frCSVDownload) return(df[!duplicated(df$ISO3), c("ISO3")]) } #' grid3ListCountryCovariates function will return a data frame of #' avalible covariates for a country #' @param ISO3 a 3-character country code or vector of country codes #' @param username ftp username to WorldPop ftp server #' @param password ftp password to WorldPop ftp server #' @param detailed If TRUE, then more information will be given #' @param frCSVDownload If TRUE, a new wpgAllCovariates.csv file will downloaded #' @rdname grid3ListCountryCovariates #' @return Dataframe #' @export #' @examples #' grid3ListCountryCovariates( ISO3="USA", username="ftpUsername", password="ftpPassword" ) #' #' grid3ListCountryCovariates(ISO3=c("USA","AFG"), username="ftpUsername", password="ftpPassword" ) grid3ListCountryCovariates <- function(ISO3=NULL, username=NULL, password=NULL, detailed=FALSE, frCSVDownload=FALSE) { if (is.null(ISO3)) stop("Enter country ISO3" ) if (is.null(username)) stop("Enter ftp username" ) if (is.null(password)) stop("Enter ftp password" ) uISO3 <- toupper(ISO3) if (any(nchar(uISO3)!=3)){ stop( paste0("Country codes should be three letters. You entered: ", paste(uISO3, collapse=", ")) ) } df <- grid3GetCSVFileAllCovariates(username, password, frCSVDownload) if(any(!uISO3 %in% df$ISO3)){ warning( paste0("ISO3 code not found: ", paste(uISO3[which(!uISO3 %in% df$ISO3)])) ) } df.filtered <- df[df$ISO3 %in% uISO3,] if(nrow(df.filtered)<1){ stop( paste0("No ISO3 code found: ", paste(uISO3, collapse=", "))) } if (detailed){ return(df.filtered) }else{ keeps <- c("ISO3", "CvtName", "Description", "Year") return(df.filtered[keeps]) } } #' grid3GetCountryCovariate function will download files and return a list #' with the file paths to the requested covariates for one or more countries #' @param df.user data frame of files to download. Must contain ISO3, Folder, and RstName. #' If not supplied, must give ISO3, year, and covariate #' @param ISO3 a 3-character country code or vector of country codes. Optional if df.user supplied #' @param covariate Covariate name(s). Optional if df.user supplied #' @param destDir Path to the folder where you want to save raster file #' @param username ftp username to WorldPop ftp server #' @param password ftp password to WorldPop ftp server #' @param quiet Download Without any messages if TRUE #' @param frCSVDownload If TRUE, a new wpgAllCovariates.csv file will downloaded #' @param method Method to be used for downloading files. Current download methods #' are "internal", "wininet" (Windows only) "libcurl", "wget" and #' "curl", and there is a value "auto" #' @rdname grid3GetCountryCovariate #' @return List of files downloaded, including file paths #' @export #' @examples #' grid3GetCountryCovariate(df.user = NULL,'NPL','px_area','G:/WorldPop/','ftpUsername','ftpPassword') grid3GetCountryCovariate <- function(df.user=NULL, ISO3=NULL, covariate=NULL, destDir=tempdir(), username=NULL, password=NULL, quiet=TRUE, frCSVDownload=FALSE, method="auto") { if (!dir.exists(destDir)) stop( paste0("Please check destDir exists: ", destDir)) if (is.null(username)) stop("Error: Enter ftp username" ) if (is.null(password)) stop("Error: Enter ftp password" ) if(!is.null(df.user)){ # provide a full data frame if(!is.data.frame(df.user)){ stop("Error: Expecting a data.frame argument") } if(!all(c("ISO3","Folder","CvtName") %in% names(df.user))){ stop("Error: must supply ISO3, CvtName, and Folder data.") } else { df.filtered <- unique(df.user) df.filtered$CvtName <- gsub(pattern=paste(tolower(df.filtered$ISO3), sep="", collapse="|"), replacement="", x=df.filtered$RstName) } } else{ # if not providing a data.frame if (is.null(ISO3)) stop("Error: Enter country ISO3" ) if (is.null(covariate)) stop("Error: Enter covariate" ) df <- grid3GetCSVFileAllCovariates(username, password, frCSVDownload) ISO3 <- toupper(ISO3) covariate <- tolower(covariate) # allow filtering by vectors df.filtered <- df[df$ISO3 %in% ISO3 & df$CvtName %in% covariate, ] } if (nrow(df.filtered)<1){ stop( paste0("Entered Covariates: ", paste(covariate, collapse=", ")," not present in WP. Please check name of the dataset")) } credentials <- paste(username,password,sep = ":") # preallocate return storage outFiles <- vector(mode="character", length=nrow(df.filtered)) # loop over all inputs for(i in 1:nrow(df.filtered)){ file_remote <- paste0(df.filtered[i,"Folder"],'/', df.filtered[i,"CvtName"],'.tif') file_local <- paste0(destDir,'/', df.filtered[i,"CvtName"],'.tif') ftpReturn <- grid3DownloadFileFromFTP(file_remote, file_local, username, password, quiet=quiet, method=method) if(!is.null(ftpReturn)){ outFiles[i] <- file_local } else{ outFiles[i] <- NULL } } returnList <- as.list(df.filtered[c("ISO3","CvtName")]) returnList$filepath <- outFiles return(returnList) }
9bac926122dba11337b3437d5f79aa4665ebf643
39c168444d709b04c268b16eac3d9f56d6dea0be
/man/batch_bam.Rd
2fc92e7f81619a2e8fde4a488aafadfc4ecefda5
[ "MIT" ]
permissive
EcoGRAPH/clusterapply
d17d49970d9816809120aec1a7cb2106df26adf5
d8ac1faff4dccd6e4778d9d5ca71840b2782ff81
refs/heads/master
2023-03-14T12:36:33.766296
2021-03-05T02:23:52
2021-03-05T02:23:52
262,955,495
0
0
null
null
null
null
UTF-8
R
false
true
1,502
rd
batch_bam.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/batch_bam.R \name{batch_bam} \alias{batch_bam} \title{Run a set of separate but similar mgcv::bam models in a single function call, with the possibility of replacing arguments if the regression results in an error.} \usage{ batch_bam(data = NULL, bamargs = NULL, bamargs_fallback = NULL, over = NULL) } \arguments{ \item{data}{The dataframe in which all the data for regressions are to be found. This dataframe should contain a column that splits it into separate frames over which mgcv::bam will be applied.} \item{bamargs}{A named list of arguments to be passed to each bam. For example, this could be bamargs=list('formula' = 'y ~ te(x,t)', 'discrete' = TRUE)} \item{bamargs_fallback}{If the regression defined by bamargs returns an error, any named arguments in this named list overwrite the arguments in bamargs and the regression is attempted again. for example, we could have the simpler model bamargs_fallback=list('formula' = 'y ~ s(x))'} \item{over}{A character string giving the name of the column in data which is used to split and pass subsets of the data to bam.} } \value{ This function returns a named list of bam objects, and possibly errors if bamargs and bamargs_fallback fail to produce a model for some levels of over. } \description{ Run a set of separate but similar mgcv::bam models in a single function call, with the possibility of replacing arguments if the regression results in an error. }
e9e3bd701cc3feec6d92a796dea98ec81122e2c4
c47a9b3d8c234674c595a9b928b902de84f0264b
/behavior/DropSubjects.R
6374784a13d5451fb241cc5447cdab9ffc6ebf0c
[]
no_license
tanyaberde/targetdetection
416ba80c2ef336834a9c14cddba32828209fe30c
7fc297a235745c85d8d7b2775aebd8c924cd514e
refs/heads/master
2020-05-04T23:18:02.804409
2019-04-04T16:58:38
2019-04-04T16:58:38
179,539,251
0
0
null
null
null
null
UTF-8
R
false
false
211
r
DropSubjects.R
# Drop subjects because #reasons Subject.Drops <- c( # "example sub number here" "94" ) # Drop cases where subject numbers match the ones in Subject.Drops dat1 <- dat1[!((dat1$Subject) %in% Subject.Drops),]
cb629e21ae6da151d2a758a476150a5b66d1add5
3d1268e3945bebc98467d7dfec97997c94a7c709
/plot4.R
43f2886fbed6d8595f44221f6e5aa463fc5a2b40
[]
no_license
LizPS/ExData_Plotting1
d0c654eeebefa0dd03321d936783055d27715936
e438f822510fdaafd0c05a42d132e448cf20d0d7
refs/heads/master
2020-12-25T00:55:11.197046
2014-08-04T23:25:50
2014-08-04T23:25:50
null
0
0
null
null
null
null
UTF-8
R
false
false
1,414
r
plot4.R
##This script assumes data are unzipped and in working directory. #Read in and subset data (to save processing time, if objects are already in #memory execute from line 15) col_classes <- c(rep("character", 2), rep("numeric", 7)) data <- read.table("household_power_consumption.txt", sep=";", na.strings ="?", nrows = 2075259, stringsAsFactors = FALSE, header = TRUE, colClasses = col_classes) data$datetime <- as.POSIXct(paste(data$Date, data$Time), format="%d/%m/%Y %H:%M:%S") data$Date <- as.Date(data$Date, "%d/%m/%Y") #overwrite data in memory with subset to reduce memory use begin <- as.Date("2007-02-01") end <- as.Date("2007-02-02") data <- subset(data, Date %in% c(begin, end)) png(filename = "plot4.png", bg = "transparent", width = 480, height = 480) par(mfrow = c(2,2)) #make plot A plot(data$datetime, data$Global_active_power, type = "l", xlab = "", ylab = "Global Active Power") #make plot B with(data, plot(datetime, Voltage, type = "l")) #make plot C plot(data$datetime, data$Sub_metering_1, type = "l", xlab = "", ylab = "Energy sub metering") lines(data$datetime, data$Sub_metering_2, type = "l", col="red") lines(data$datetime, data$Sub_metering_3, type = "l", col="blue") legend("topright",colnames(data[7:9]), bty = "n", lwd = 1, col = c("black","red","blue")) #make plot D with(data, plot(datetime, Global_reactive_power, type = "l")) dev.off()
6bf3ffc6b2d6f06d421af880e00b0bfb8e399c90
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/checkmate/examples/checkFileExists.Rd.R
5421e115b53d70799b67bd299499d5dacc22a09d
[]
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
539
r
checkFileExists.Rd.R
library(checkmate) ### Name: checkFileExists ### Title: Check existence and access rights of files ### Aliases: checkFileExists check_file_exists assertFileExists ### assert_file_exists testFileExists test_file_exists expect_file_exists ### checkFile assertFile assert_file testFile expect_file ### ** Examples # Check if R's COPYING file is readable testFileExists(file.path(R.home(), "COPYING"), access = "r") # Check if R's COPYING file is readable and writable testFileExists(file.path(R.home(), "COPYING"), access = "rw")
80d9061893d699f076b5b0b580ebf3ade349b188
8d47c5151a31d7d9d0a5c1f9a9678b95cbe176a1
/plot2.R
f89a32b4c120f377c135de796cc1f1fd34211cd4
[]
no_license
pennyg7610/Exploratory_DA_A2
b4535d7dd31d49f191f433745c2379dbd716c4fc
624fc16ee5314d716366c816935d2d10301e318d
refs/heads/main
2023-08-27T19:35:11.650281
2021-10-29T19:48:42
2021-10-29T19:48:42
422,606,779
0
0
null
null
null
null
UTF-8
R
false
false
1,189
r
plot2.R
# Assignment : #The overall goal of this assignment is to explore the National Emissions Inventory database and see what it say about fine particulate matter pollution in the United states over the 10-year period 1999–2008. You may use any R package you want to support your analysis. #Question 2 #Have total emissions from PM2.5 decreased in the Baltimore City, Maryland (fips == "24510") from 1999 to 2008? Use the base plotting system to make a plot answering this question. #set packages library(data.table) #read in files summarySCC_PM25 <- readRDS("~/Coursera/Exploratory_DA_A2/summarySCC_PM25.rds") Source_Classification_Code <- readRDS("~/Coursera/Exploratory_DA_A2/Source_Classification_Code.rds") #clean the file to reflect total emmisions by year charmcity<- subset(summarySCC_PM25, summarySCC_PM25$fips == "24510") Baltemiss<- aggregate(Emissions ~ year, data= charmcity, FUN = sum) #making the plot # Open png file png("plot2.png", width = 480, height = 480) # Create the plot plot(Baltemiss$year, Baltemiss$Emissions, type = "o", main = expression("Baltimore Emissions by Year"), ylab = expression("Baltimore Emissions"), xlab = "Year") # Close the file dev.off()
99bd3fcfdc02fc591b29573052d1845302630ae9
5c94c3965af6cdc2c715ffdb073254f0cfd34dab
/R Code - PMD Launcher/383C_FinalProject_RCode.R
980bf5a3016d0f97fd983098380d2b432c2ed5d1
[]
no_license
jestarling/penalized-matrix-decomp
f11bfdce46e4f4620986bd43a23bb0704cc0a878
a66d4a21d775b1c5aa301efc1785b3caa7eb7a47
refs/heads/master
2021-06-09T05:48:59.813524
2016-12-05T15:00:37
2016-12-05T15:00:37
null
0
0
null
null
null
null
UTF-8
R
false
false
16,579
r
383C_FinalProject_RCode.R
#SDS 385 Final Project #Jesse Miller & Jennifer Starling #Fall 2016 rm(list=ls()) #Clean workspace. library(stats) #For KDE estimation in histograms. setwd("/Users/jennstarling/UTAustin/2016_Fall_SDS 383C_Statistical Modeling 1/Final Project/penalized-matrix-decomp") source(file="./R Code/Penalized_Matrix_Decomp_Functions.R") #Read in Penalized Matrix Decomp functions. #------------------------------------------------------------ #DATA LOADING: #Read in data. data2014 = read.csv(file="./Data/2014FA_AllData.csv",header=T) data2015 = read.csv(file="./Data/2015FA_AllData.csv",header=T) data = rbind(data2014,data2015) #Alternative: Load Rdata object directly. load("./Data/data.Rdata") #------------------------------------------------------------ #DATA PROCESSING: #Create Y variable as Y=1 (pass), Y=0 (fail) based on Math.GPA >= 1.5. #Note - this is already in data set, named Math.P.F. data$Y = data$Math.P.F #passing.grades = c("A+","A","A-","B+","B","B-","C+","C","C-") #data$Y = ifelse(data$Math.Grade %in% passing.grades,1,ifelse(data$Math.Grade=="",NA,0)) #Restrict data set to only cases where Y != NA, ie where pass/fail known. data = data[!is.na(data$Y),] #Restrict data to just the calculus classes 408C, 408N, 408K. data = data[data$Math.Course %in% c("408C","408N","408K"),] #Set up some initial dimensional information. n = nrow(data) #Total number of obs for both years combined. n2014 = sum(data$YEAR==2014) #Total number of obs for 2014 only. n2015 = nrow(data$YEAR==2015) #Total number of obs for 2015 only. p = ncol(data)-5 #Number of predictors (excl ID, Year, Math.GPA, Math.P.F., Y). #################################################################### ### TOY EXAMPLES OF PENALIZED MATRIX DECOMPOSITION: ### #################################################################### #Example 1: Illustrate missing data imputation. #Set up X matrix. X = matrix(rnorm(20),nrow=5,ncol=4) n = nrow(X) p = ncol(X) #Randomly select values to set to NA. n.elems = nrow(X) * ncol(X) na.locs = sample(1:n.elems,size=n.elems*.5,replace=F) Xmiss = X Xmiss[na.locs] = NA K=ncol(X) lambdas = 10 #Want a large lambda, not trying to induce sparsity in features here. missing.test = sparse.matrix.factorization.rankK(X,K, lambdaU= lambdas, lambdaV=lambdas, maxiter=20,tol=1E-6) round(Xmiss,2) round(missing.test$X.rebuilt,2) #------------------------------------------------------------ #Example 2: A simulated matrix with no missing values. #Illustrates how decreasing lambda penalty terms selects features. X = matrix(rnorm(20),nrow=5,ncol=4) n = nrow(X) p = ncol(X) #Paper notes that if you want u and v to be equally sparse, set a constant c, #and let lambdaU = c*sqrt(n), and let lambdaV = c * sqrt(p). c = .9 lambdaU = c*sqrt(n) lambdaV = c*sqrt(p) K = 1 #Set a K value for testing. We'll use Rank 1 here. c = seq(1,.1,by=-.2) tests = list() #Empty vector for holding test cases. lamU = rep(0,length(c)) #Empty vector to store lambdaU values for each c. lamV = rep(0,length(c)) #Empty vector to store lambdaV values for each c. nonzero.x.cols = rep(0,length(lambdas)) #Empty vector for holding sparsity info. #Loop through test cases. for (i in 1:length(c)){ lambdaU = c[i]*sqrt(n) lambdaV = c[i]*sqrt(p) tests[[i]] = sparse.matrix.factorization.rankK(X,K, lambdaU, lambdaV, maxiter=20,tol=1E-6) Xnew = tests[[i]]$X.rebuilt nonzero.x.cols[i] = nonzero.col.info(Xnew)$num.nonzero.cols #Store lambda values. lamU[i] = lambdaU lamV[i] = lambdaV } #Display results. for (i in 1:length(tests)){ print(tests[[i]]$X.rebuilt) } cbind(c,lambdaU=round(lamU,3),lambdaV=round(lamV,3),nonzero.x.cols) ################################################################################## ### IMPUTING MISSING CONTINUOUS DATA USING PENALIZED MATRIX FACTORIZATION. ### ################################################################################## #----------------------------------------------------------------- #IMPUTING MISSING CONTINUOUS DATA USING PENALIZED MATRIX FACTORIZATION. #---------------------------------- #1. Identify continuous predictors to be included in the imputation. head(data) cols.continuous.all = c(13:16,18,20:28,30:38,39:44,45:50) #45-51 are AP scores. 18 is UTMA score. X = data.matrix(data[,cols.continuous.all]) #Subset of just the desired continuous data cols. #Cols.continuous.all includes 21-28 and 31-38, which subset does not. #These cols include the breakdowns of ALEKS-1 and ALEKS-H. #NOTE: This technique works well when predictors have same scale. #If predictors have vastly different scales, X must be scaled #first to ensure logical predictions. #Since we are working with a few different groups of predictors, #each which is related to a certain #type of test, it makes sense to work in groups. #Some info about how much data is missing: nrow(X) * ncol(X) #Total data points in X. sum(is.na(X)) #Total points missing in X. sum(is.na(X)) / (nrow(X) * ncol(X)) #Proportion of data missing in X. #---------------------------------- #2. Impute all missing values for continuous columns at once. #Scale and center data. (By hand, so can back-transform.) col.means = colMeans(X,na.rm=T) col.sdevs = sqrt(apply(X,2,function(a) var(a,na.rm=T))) X.scaled = scale(X) #Confirm col.means and col.sdevs are the correct values used by scale(X). attr(scale(X),"scaled:scale") attr(scale(X),"scaled:scale") #Impute missing values for all continuous predictors at once. pmd = sparse.matrix.factorization.rankK(X.scaled,K=ncol(X),lambdaU=1000,lambdaV=1000,maxiter=20) X.filled.scaled = pmd$X.rebuilt head(X.scaled) head(X.filled.scaled) #Reverse scaling. X.filled = X.filled.scaled #Placeholder to initialize X.filled matrix. for (i in 1:ncol(X.filled.scaled)){ X.filled[,i] = X.filled.scaled[,i] * col.sdevs[i] + col.means[i] } colnames(X.filled) = colnames(X) #---------------------------------- #3. Verify Results: #Eyeball results. head(X) head(X.filled) #Sanity check ranges of the output for each column. range_orig = apply(X, 2, function(x) round(range(x,na.rm=T),2)) range_imputed = apply(X.filled, 2, function(x) round(range(x,na.rm=T),2)) cbind.data.frame(orig.min = range_orig[1,], orig.max = range_orig[2,], imput.min = range_imputed[1,], imput.max = range_imputed[2,]) #Histograms to compare distributions before and after imputing data. #SATs & ACTs: jpeg(file='/Users/jennstarling/UTAustin/2016_Fall_SDS 383C_Statistical Modeling 1/Final Project/LaTeX Files/SAT_ACT_hist.jpg') par(mfrow=c(2,3)) idx = c(23:28) #SAT and ACT variable indices. for (i in idx){ hist(X[,i],freq=F,main=paste(colnames(X)[i])) points(density(X.filled[,i]),col='blue',type='l') } dev.off() #GPA, UTMA values: jpeg(file='/Users/jennstarling/UTAustin/2016_Fall_SDS 383C_Statistical Modeling 1/Final Project/LaTeX Files/GPA_hist.jpg') par(mfrow=c(2,3)) idx = c(1:5) for (i in idx){ hist(X[,i],freq=F,main=paste(colnames(X)[i])) points(density(X.filled[,i]),col='blue',type='l') } dev.off() #AP Score values: jpeg(file='/Users/jennstarling/UTAustin/2016_Fall_SDS 383C_Statistical Modeling 1/Final Project/LaTeX Files/AP_score_hist.jpg') par(mfrow=c(2,3)) idx = c(30:35) for (i in idx){ hist(X[,i],freq=F,main=paste(colnames(X)[i])) points(density(X.filled[,i]),col='blue',type='l') } dev.off() #SCORE values: jpeg(file='/Users/jennstarling/UTAustin/2016_Fall_SDS 383C_Statistical Modeling 1/Final Project/LaTeX Files/SCORE_hist.jpg') par(mfrow=c(3,6)) idx = c(5:22) for (i in idx){ hist(X[,i],freq=F,main=paste(colnames(X)[i])) points(density(X.filled[,i]),col='blue',type='l') } dev.off() #---------------------------------- #4. Reconstruct entire data set, and save data object. #Data set containing only continuous variables. #Missing values imputed. data.cont.new = cbind(X.filled,Y=data$Y) #Data set containing all predictors. #Missing values imputed (for continuous predictors only). data.categorical = data[,-c(cols.continuous.all,ncol(data))] #Save continuous vars, minus y col. data.all.new = cbind(data.categorical,data.cont.new) #Cbind data set back together. #Save old data (just continuous predictors). #Will be used to compare regression improvements. data.cont.old = cbind(X,Y=data$Y) save(data.all.new,file='./Data/data.all.new.Rdata') save(data.cont.new,file='./Data/data.cont.new.Rdata') save(data.cont.old,file='./Data/data.cont.old.Rdata') ###################################################################### ### LOGISTIC REGRESSION WITH IMPUTED DATA VERSUS MISSING DATA. ### ###################################################################### #Compare the results of a logistic regression before and after data imputation. #This quick check involves holding out 30% of the data, and obtaining #a 'test error' for the held out 30%. This is performed for the continuous variables #only, with and without imputed data. y_idx = ncol(data.cont.new) #Col index for y column. #1. Set up training and test data. train.rows = sample(nrow(X),nrow(X)*.7,replace=F) train.missing = data.cont.old[train.rows,] test.missing = data.cont.old[-train.rows,] train.filled = data.cont.new[train.rows,] test.filled = data.cont.new[-train.rows,] #2. Perform logistic regression and calculate test error using data set with missing values. lm.with.missing = glm(Y ~ ., family=binomial,data=as.data.frame(train.missing)) pred.missing = predict.glm(lm.with.missing,newdata=as.data.frame(test.missing[,-y_idx]),type='response') yhat.missing = ifelse(pred.missing >= .5,1,0) yhat.temp = yhat.missing #To handle values that are predicted as NA due to missing data. yhat.temp[is.na(yhat.missing)] = 999 test.err.missing = sum(test.missing[,y_idx] != yhat.temp) / length(yhat.missing) test.err.missing #Display results. paste(sum(is.na(yhat.missing)),'out of ',length(yhat.missing),' values predicted as NA due to missing data.') #---------------------------------- #Test error for data with imputed values. lm.filled = glm(Y ~ ., family=binomial,data=as.data.frame(train.filled)) pred.filled = predict.glm(lm.filled,newdata=as.data.frame(test.filled[,-y_idx]),type='response') yhat.filled = ifelse(pred.filled >= .5,1,0) test.err.filled = sum(test.filled[,y_idx] != yhat.filled) / length(yhat.filled) test.err.filled #Conclusion: Imputing the missing data using penalized matrix decomposition drastically #decreased the logistic regression test error from .78 to .23 #A few things: #No additional model fitting or analysis has been done. Model could of course be improved in many ways. #Could look at using this functionality for variable selection, as well. ################################################################### ### COMPARING WITH IMPUTATION USING PREDICTOR MEANS. ### ################################################################### #Create a data set of just continuous predictors, which will be used #to impute the means of the missing data. col.means = colMeans(data.cont.old[,-ncol(data.cont.old)],na.rm=T) #Col means, removing Y col. #Replace all NA values in each column with the respective column means. data.cont.means = data.cont.old #Start with the data set with missing values. for (i in 1:length(col.means)){ #-1 because excluding Y, which has no missing values. data.cont.means[is.na(data.cont.means[,i]), i] = col.means[i] } #Perform logistic regression using means-imputed data set, for comparison. #Set up test and train data sets. train.means = data.cont.means[train.rows,] test.means = data.cont.means[-train.rows,] #Test error for data with mean-imputed values. lm.means = glm(Y ~ ., family=binomial,data=as.data.frame(train.means)) pred.means = predict.glm(lm.means,newdata=as.data.frame(test.means[,-y_idx]),type='response') yhat.means = ifelse(pred.means >= .5,1,0) test.err.means = sum(test.means[,y_idx] != yhat.means) / length(yhat.means) test.err.means ################################################################# ### COMPARISON: MATRIX METHOD vs IMPUTATION USING SVD. ### ################################################################# library(bcv) #impute.svd imputes the missing entries using a low-rank SVD approximation estimated by the EM algorithm. data.cont.svd = impute.svd(X[,-y_idx],k=35,maxiter=20) data.cont.svd = cbind(data.cont.svd$x,data$Y) colnames(data.cont.svd) = c(colnames(X),"Y") #View ranges as sanity check. apply(data.cont.svd,2,range) train.svd = data.cont.svd[train.rows,] test.svd = data.cont.svd[-train.rows,] lm.svd = glm(Y ~ ., family=binomial,data=as.data.frame(train.svd)) pred.svd = predict.glm(lm.svd,newdata=as.data.frame(test.svd[,-y_idx]),type='response') yhat.svd = ifelse(pred.svd >= .5,1,0) test.err.svd = sum(test.svd[,y_idx] != yhat.svd) / length(yhat.svd) test.err.svd ################################################################### ### VARIABLE SELECTION USING PENALIZED MATRIX FACTORIZATION. ### ################################################################### #The following is an example of how decreasing the lambda penalty can #perform variable selection on the continuous variables. #In this case, we are not worried about the scale of the values, so we #will analyze all continuous predictors together. #Data set setup for variable selection. We will use the imputed data. Xfull = scale(data.cont.new[,-36]) n = nrow(Xfull) p = ncol(Xfull) #Vector of c values, since imposing equal sparisty on u and v. #c = seq(.5,.01,-.1) c = c(.3,.2,.1,.05,.01) #Initialization. tests = list() #Empty vector for holding test cases. models = list() #Store each logistic regression model. test.errors = rep(0,length(c)) #Empty vector for holding test error for each predictor subset. lamU = rep(0,length(c)) #Empty vector to store lambdaU values for each c. lamV = rep(0,length(c)) #Empty vector to store lambdaV values for each c. nonzero.x.cols = rep(0,length(c)) #Empty vector for holding sparsity info. interesting.predictors = list() #Empty list for holding interesting predictors for each lambda. n.nonzero.cols = rep(0,length(c)) #Empty vector for holding number of interesting predictors. #Loop through test cases. for (i in 1:length(c)){ #----------------------------------------- #Set up penalty parameters. lambdaU = c[i]*sqrt(n) lambdaV = c[i]*sqrt(p) #----------------------------------------- #Run matrix factorization. tests[[i]] = sparse.matrix.factorization.rankK(Xfull,K=ncol(Xfull), lambdaU, lambdaV, maxiter=20,tol=1E-6) #Store rebuilt X matrix and number of nonzero columns. Xnew = tests[[i]]$X.rebuilt Xnew.col.info = nonzero.col.info(Xnew) n.nonzero.cols[i] = Xnew.col.info$num.nonzero.cols interesting.predictors[[i]] = colnames(Xfull)[Xnew.col.info$nonzero.cols.idx] #Store lambda values. lamU[i] = lambdaU lamV[i] = lambdaV #----------------------------------------- #Perform logistic regression on subset of interesting predictors. data.temp = cbind(Xfull[,interesting.predictors[[i]]],Y=data$Y) y_idx = ncol(data.temp) #Set up train/test data. train.rows = sample(nrow(Xfull),nrow(Xfull)*.7,replace=F) train.temp = data.temp[train.rows,] test.temp = data.temp[-train.rows,] #Set up model. lm.temp = glm(Y ~ ., family=binomial,data=as.data.frame(train.temp)) pred.temp = predict.glm(lm.temp,newdata=as.data.frame(test.temp[,-y_idx]),type='response') yhat.temp = ifelse(pred.temp >= .5,1,0) test.err.temp = sum(test.temp[,y_idx] != yhat.temp) / length(yhat.temp) test.err.temp #Store model and test error. models[[i]] = lm.temp test.errors[i] = test.err.temp } #Pick out model with minimum test error. test.errors min = which(test.errors == min(test.errors)) test.errors[min] interesting.predictors[[min]] n.nonzero.cols[min] #Plot test error as a function of number of predictors. jpeg(file='/Users/jennstarling/UTAustin/2016_Fall_SDS 383C_Statistical Modeling 1/Final Project/LaTeX Files/test.errs.jpg') plot(n.nonzero.cols,test.errors,type='l',col='blue',main='Test Error vs Number of Predictors', xlab='Number of Predictors',ylab='Test Error') abline(h=.2159,col='black') legend(20,.25,lty=c(1,1),col=c('blue','black'),legend=c('Test error','Full model test error')) dev.off() npred = lapply(interesting.predictors,length) var.sel.results = list(c=c,lambdaU=lamU,lambdaV=lamV,models=interesting.predictors,test.errors=test.errors,n.predictors=npred) save(var.sel.results,file='/Users/jennstarling/UTAustin/2016_Fall_SDS 383C_Statistical Modeling 1/Final Project/varsel.Rdata')
81da0104f6fa6a93d73930913b6e763590c5f8c4
3ad6528b225c3e29c8cd1ba7e2897d4eb0a7ac6d
/man/showSparkTable.Rd
a7e031493c4a4fc3cb31c8e0c191aa0be776a70d
[]
no_license
cran/sparkTable
1ca21474c32f41c04e048f40c8a97d2b2e55bb85
81c0f57f43aad2b76ccff03b795c3d5f08ddc29b
refs/heads/master
2021-01-17T09:33:53.766221
2016-12-13T18:55:10
2016-12-13T18:55:10
17,699,843
0
1
null
null
null
null
UTF-8
R
false
false
2,914
rd
showSparkTable.Rd
\name{showSparkTable-methods} \docType{methods} \alias{showSparkTable} \alias{showSparkTable-methods} \alias{showSparkTable,sparkTable-method} \alias{showSparkTable,data.frame-method} \title{ Look at your sparkTable in a shiny App} \description{ ~~ Methods for function \code{showSparkTable} ~~ } \section{Methods}{ \describe{ \item{\code{signature(object = "sparkTable")}}{ %% ~~describe this method here~~ } }} \usage{ showSparkTable(object, outputDir=tempdir(),outputType="html", filename=NULL, graphNames="out", ...) } \arguments{ \item{object}{an object of class 'sparkTable' or 'data.frame'} \item{outputDir}{a path to a directory for the output (Default=temporary directory)} \item{outputType}{a character vector of length one specifying the desired output format: \itemize{ \item 'tex': latex output is produced (does not work) \item 'html': html output is procuded }} \item{filename}{ the filename of the output (minus '.tex' or '.html'} \item{graphNames}{ the main part of the single graphic files that are produced (minus '-someIndex.extension'} \item{...}{additional parameters to be passed to \code{\link{export}} and \code{\link{summaryST}}} } \seealso{\code{\link{export}}} \examples{ \dontrun{ data(pop,package="sparkTable") b <- newSparkBox() l <- newSparkLine() bb <- newSparkBar() content <- list(function(x) { round(mean(x),2) }, b, l, bb, function(x) { round(tail(x,1),2) } ) names(content) <- paste("column",1:length(content),sep="") varType <- rep("value",length(content)) pop <- pop[,c("variable","value","time")] pop$time <- as.numeric(as.character(pop$time)) xx <- reshapeExt(pop, varying=list(2)) x1 <- newSparkTable(xx, content, varType) showSparkTable(x1) #Example Hist+Box with 2 variables in 10 different groups datEx <- data.frame( variable=sample(paste("Cat",1:10,sep="_"),1000,replace=TRUE), value=rnorm(1000),value2=rlnorm(1000) ) b <- newSparkBox() h <- newSparkHist() content <- list( function(x) { round(mean(x),2) }, function(x) { round(median(x),2) }, function(x) { round(quantile(x,.25),2) }, function(x) { round(quantile(x,.75),2) }, b, h, function(x) { round(mean(x),2) }, function(x) { round(median(x),2) }, function(x) { round(quantile(x,.25),2) }, function(x) { round(quantile(x,.75),2) }, b, h ) names(content) <- c( paste(c("Mean","Median","Q25","Q75","Boxplot","Histogram"),"_v1",sep=""), paste(c("Mean","Median","Q25","Q75","Boxplot","Histogram"),"_v2",sep="") ) varType <- c(rep("value",length(content)/2),rep("value2",length(content)/2)) datEx <- reshapeExt(datEx, varying=list(2,3)) x2 <- newSparkTable(datEx, content, varType) showSparkTable(x2) #Example for the data.frame method (uses summaryST) data2 <- data.frame(x1=rnorm(100),x2=rnorm(100)+1,x3=rnorm(100)+5) showSparkTable(data2) } }
69199b2f2d5ab2a06aa97b956c2f423caa5d3672
2228506fa1b15001d3e80d273939cf2184f60736
/man/NEATSimulation.RunSingleGeneration.Rd
1f2245f015109d66afa098a1a91dc5edc8134269
[]
no_license
ah-box/RNeat
5030a789fcf9c2fdea3b6806ddcb338967d0f680
f7c7eec76f595acfb4f5ee28ad54f150244d0d49
refs/heads/master
2023-03-20T12:14:48.302788
2016-10-23T14:04:18
2016-10-23T14:04:18
58,329,758
1
0
null
null
null
null
UTF-8
R
false
true
802
rd
NEATSimulation.RunSingleGeneration.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/neat.R \name{NEATSimulation.RunSingleGeneration} \alias{NEATSimulation.RunSingleGeneration} \title{Runs a single generation} \usage{ NEATSimulation.RunSingleGeneration(simulation, createVideo = F, videoPath = "videos", videoName = "", framesPerSecond = 1) } \arguments{ \item{simulation}{Takes a NEATSimulation class} \item{createVideo}{True/False to save a video of the highest fitness simulation} \item{videoPath}{Path to where to save the video} \item{videoName}{Name of the video} \item{framesPerSecond}{The frames per second of the video} } \value{ NEATSimulation class with new generation of genomes } \description{ Takes in a simulation, runs all the genomes, evaluates fitness and breeds the new generation }
d5c8221a182b7c4f7b71e7c83fda2b122f645413
5445ecc3d101ef8ced80cdd759e25fa2fe05387e
/tools/predictSGRNA/man/predictSGRNA-package.Rd
45dcc88cb988e4739fb446bd85552148d7696ef4
[]
no_license
bmerritt1762/GRIBCG
d1aafed826a8ea1ea5c308243aa6abe49fd6934e
ad5622345fb67f9fa19ff32e6d90f95ac664b0ab
refs/heads/master
2020-04-09T00:08:15.505907
2018-12-14T01:45:24
2018-12-14T01:45:24
159,854,713
0
0
null
null
null
null
UTF-8
R
false
false
819
rd
predictSGRNA-package.Rd
\name{predictSGRNA-package} \alias{predictSGRNA-package} \alias{predictSGRNA} \docType{package} \title{ Predict sgRNA efficiency } \description{ The predictSGRNA package predicts sgRNA efficiency from position dependent dinucleotide model of Kuan et al. (2017). } \details{ \tabular{ll}{ Package: \tab predictSGRNA\cr Type: \tab Package\cr Version: \tab 1.0\cr Date: \tab 2016-06-13\cr License: \tab GPL (>= 2)\cr } } \author{ Pei Fen Kuan Maintainer: Pei Fen Kuan <peifen.kuan@stonybrook.edu> } \references{ P.F. Kuan, S. Powers, S. He, K. Li, X. Zhao and B. Huang (2017). A systematic evaluation of nucleotide properties for CRISPR sgRNA design. BMC Bioinformatics, 18:297, DOI: 10.1186/s12859-017-1697-6. } \seealso{ \code{\link{predictSGRNA}} } \examples{ head(exampleData) predictSGRNA(exampleData,'TestFile') }
6e4dfb8ba52651fdb8315f623a1332e741c9e4f5
96ef0481a0f4baa05237718907608e31dcf10304
/KalmanFilter.R
e2b43981f46b653255ff29e9b905a4ac6820e86e
[]
no_license
yuhenghuang/Rcpp
8ba67c65b4a5e6f32375e251b1170e3b172d455c
5c6fb11c347fc2e72bb8d98c29a0ae4552ce8d31
refs/heads/master
2023-01-09T00:40:39.292823
2020-10-23T13:25:35
2020-10-23T13:25:35
282,114,511
0
0
null
null
null
null
UTF-8
R
false
false
141
r
KalmanFilter.R
library(Rcpp) sourceCpp("KalmanFilter.cpp") pos = matrix(c(1:1000/500, sin(1:1000/500)), ncol = 2, byrow = TRUE) res <- KalmanFilter(pos)
afe4d42f76db94d3c9fb0fde37c18834f23d0994
5fc35d4a81175339460430f42c9cc2146a8d06eb
/Transformada Wavelet Haar Y Arbol de Decisiones/wavelets.r
d16ec01a719f9e5810a537727958fc1c4ffdf102
[ "MIT" ]
permissive
juusechec/MiniProgramasR
135ec3c1fa4564c08397fcfaa9e052ccafac30ff
bdcb67ab4364397c4b7d729b76a5ff813b4e3948
refs/heads/master
2021-07-08T18:32:20.029522
2017-10-05T03:37:50
2017-10-05T03:37:50
103,343,923
0
0
null
null
null
null
UTF-8
R
false
false
2,490
r
wavelets.r
library(wavelets) k <- c(1,2,3,4) w <- dwt(k, filter="haar") w@V[[1]] # http://www.bearcave.com/misl/misl_tech/wavelets/matrix/index.html a <- c(1,1,0,0, 1,-1,0,0, 0,0,1,1, 0,0,1,-1) a <- matrix(a, nrow = 4, ncol = 4) b <- matrix(k,nrow=4, ncol = 1) x <- (1/sqrt(2)) * a %*% b y <- c(x) ai <- y[seq(1, 3, 2)] #library(wavelets) # https://stackoverflow.com/questions/19677229/r-haar-wavelet-transform k <- c(4,6,10,12,8,6,5,5) w <- dwt(k, filter="haar") w@V[[1]] # http://www.bearcave.com/misl/misl_tech/wavelets/matrix/index.html a <- c(1,1,0,0,0,0,0,0, 1,-1,0,0,0,0,0,0, 0,0,1,1,0,0,0,0, 0,0,1,-1,0,0,0,0, 0,0,0,0,1,1,0,0, 0,0,0,0,1,-1,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0,1,-1) a <- matrix(a, nrow = 8, ncol = 8) b <- matrix(k,nrow=8, ncol = 1) x <- (1/sqrt(2)) * a %*% b y <- c(x) ai <- y[seq(1, 7, 2)] #library(wavelets) # https://stackoverflow.com/questions/19677229/r-haar-wavelet-transform # 40 muestras haar vs jorge k <- rep(c(4,6,10,12,8,6,5,8),4) w <- dwt(k, filter="haar") bi <- c(w@V[[1]]) # http://www.bearcave.com/misl/misl_tech/wavelets/matrix/index.html a <- c(1,1,0,0,0,0,0,0, 1,-1,0,0,0,0,0,0, 0,0,1,1,0,0,0,0, 0,0,1,-1,0,0,0,0, 0,0,0,0,1,1,0,0, 0,0,0,0,1,-1,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0,1,-1) a <- matrix(a, nrow = 8, ncol = 8) b <- matrix(k,nrow=8, ncol = length(k)/8) x <- (1/sqrt(2)) * a %*% b y <- c(x) ai <- y[seq(1, length(y)-1, 2)] # para 80 muestras nivel = 80 k <- rep(c(4,6,10,12,8,6,5,5,23,1),8) # length 80 a <- c() estado = FALSE for (index in c(1:nivel)){ estado = !estado arreglo = rep(0,nivel) myIndice = 0 if (index %% 2 == 0){# par myIndice = index -1 } else { myIndice = index } par = c() if (estado) { par = c(1,1) } else { par = c(1,-1) } iInf = myIndice-1 iSup = myIndice+2 #print(paste("Indice", iInf, iSup)) #print(arreglo[0:iInf]) #print(arreglo[iSup:length(arreglo)]) if (iInf == 0){ arreglo = c(par, arreglo[iSup:length(arreglo)]) } else if (iSup == length(arreglo)+1){ arreglo=c(arreglo[1:iInf], par) } else { arreglo=c(arreglo[1:iInf], par, arreglo[iSup:length(arreglo)]) } #print(paste("Estado", estado)) #print(paste("Par", par)) #print(arreglo) #print(paste("Indice", index)) a <- c(a,arreglo) } a <- matrix(a, nrow=nivel, ncol=nivel) b <- matrix(k, nrow=nivel, ncol=1) x <- (1/sqrt(2)) * a %*% b y <- c(x) ai <- y[seq(1, nivel, 2)]
93e5d46e4e01b8f53ce1982a0f1ed4b364ce3615
9cb1e9d2d096090a3fe5a79e2bc5758bb3e243f0
/constants.R
75185225f4919a91ad8f145989e91a8b0b8e60c7
[ "MIT" ]
permissive
anuraagpolisetty/ADS-Dashboard
7754869becdee7b7335ba177a6817cd90b4fdb72
74d2703b0cde43b39168cb65612d03d5481d886c
refs/heads/master
2022-08-28T07:29:12.486227
2020-06-01T05:34:21
2020-06-01T05:34:21
266,222,323
0
0
null
null
null
null
UTF-8
R
false
false
3,846
r
constants.R
# library(googledrive) # source("auth.R", local = T) # This file is used to store all constant variables that can be accessed from any other file. # Anyt changes or additions to this file will update accordingly in the overall dashboard. # You can add a new center to the 'centers' variable which will automatically create a new # tab for the center. # Be sure to use '<<-' to store global variables that can be accessed from any other file # If you would like to add a new center, add it to the end of this comma-seperated list. # Replace the "New Center" line with the name of the center and delete the '#' symbol centers <<- c("ACRS", "Greenwood", "IDIC", "Pike Market", "Sunshine Garden", "Wallingford", "Sound Generations", "South Park", "Generations With Pride", "Southeast", "Central Area Senior Center" , "New Center" ) # Add new survey questions by adding it to the end of this comma-seperated list all_questions <<- c("Do more volunteer work", "See friends more often make new friends", "Take better care of my health", "Eat meals that are better for me", "Have more energy", "Feel happier or more satisfied with my life", "Have something to look forward to each day", "Know where to ask if I need a service such as a ride to a doctor or an aide", "Feel more able to stay independent", "Feel that the senior center has had a positive effect on my life", "Learn new things", "Have learned about services and benefits", "Am more physically active", "Would recommend the senior center to a friend or family member" # ,"Extra question" ) batches <<- c("2015-1", "2015-2", "2016-1", "2016-2", "2017-1", "2017-2", "2018-1", "2018-2", "2019-1", "2019-2", "2020-1", "2020-2") # Add in 2021-1 and 2021-2 in here when necessary answers <<- c("Almost Never", "Sometimes", "Most of the Time", "Not applicable") sectors <<- c('Social', 'Physical', 'Positivity', 'Services', 'Independence', 'Overall') index <<- c('SocialIndex', 'PhysicalIndex', 'PositiveIndex', 'ServicesIndex', 'IndependenceIndex', 'OverallIndex') # Same as above, change the income brackets by changing this list of choices income_brackets <<- c("Very Low: Less than $18550 for 1 person; or $21,2000 for 2 people", "Low: Less for than $30,900 for 1 person; or $35,300 for 2 people", "Moderate: Less than $44,750 for 1 person; or $51,150 for 2 people", "Above Moderate: More than $44,750 for 1 person; or $51,150 for 2 people", "N/A") race_ethnicity <<- c("American Indian or Alaska Native", "Asian, Asian-American", "Black, African-American, Other African", "Hawaiian Native or Pacific Islander", "Hispanic, Latino", "Other", "White or Caucasian", "Two or More", "N/A") # Keep all spreadsheet IDs and center names in a single globally-accessible dataframe # Updates google sheets even when a new center is added # drive_auth(path = ".secrets") # drive_auth(cache = ".secrets", email = TRUE) # # ids <- vector() # for (c in centers) { # id <- drive_get(c)$id # # # IF no sheet id is found, create a new google sheet (with column names) # if(length(id) == 0) { # id <- createNewSheet(c) # } # # # Continue saving sheet id to center_ids dataframe # ids[c] <- id # } # ## Store all center IDs in globally-accessible dataframe # center_ids <<- data.frame(center=centers, id=ids)
9859bf6c0fff867d1922f207c883ff07161fa63c
1fd808eaaf20f57ebab987fa5034b9b43b52ce8f
/source/composite variables/01-horizontal_general.R
950b2129340d0ac6e2624f304a0763226c8abe8f
[]
no_license
Ashire/som_mcna_19
aada6d5814de0f89ab0cb0d2e0b1bf4f4fd57dd0
14158867b6c0183a366181f9e594fa540dec767e
refs/heads/master
2020-09-23T06:12:46.301327
2019-11-21T04:07:20
2019-11-21T04:07:20
225,424,915
0
0
null
2019-12-02T16:53:45
2019-12-02T16:53:44
null
UTF-8
R
false
false
4,471
r
01-horizontal_general.R
#general recoding response <- response %>% #Dates: converting dates from excel format dplyr::mutate(today = as_date(today, origin = "1899-12-30"), left_aoo = as_date(left_aoo, origin = "1899-12-30"), arrived_current = as_date(arrived_current, origin = "1899-12-30"), diff_today_aoo = as.period(today - left_aoo) %/% months(1)) %>% dplyr::rename(diff_today_current = difference_arrived_today_days, diff_current_aoo = difference_arrived_left_days) %>% dplyr::mutate(diff_today_current = as.period(today - arrived_current) %/% months(1), diff_current_aoo = as.period(arrived_current - left_aoo) %/% months(1)) %>% dplyr::rename(diff_today_aoo_months = diff_today_aoo, diff_today_current_months = diff_today_current, diff_current_aoo_months = diff_current_aoo) response <- response %>% ### income_middle_point new_recoding(target = income_middle, source = average_income) %>% recode_to(to = 200, where.selected.exactly = "200more") %>% recode_to(to = 175, where.selected.exactly = "151_200") %>% recode_to(to = 125, where.selected.exactly = "101_150") %>% recode_to(to = 80, where.selected.exactly = "61_100") %>% recode_to(to = 45, where.selected.exactly = "31_60") %>% recode_to(to = 15, where.selected.exactly = "less30") %>% recode_to(to = 10, where.selected.exactly = "none") %>% ### education new_recoding(target = spent_education_middle) %>% recode_to(to = 5, where.selected.exactly = "usd_0_9", source = cash_bracket_education) %>% recode_to(to = 30, where.selected.exactly = "usd_10_50", source = cash_bracket_education) %>% recode_to(to = 75, where.selected.exactly = "usd_50_100", source = cash_bracket_education) %>% recode_to(to = 100, where.selected.exactly = "usd_more_100", source = cash_bracket_education) %>% # recode_to(to = 0, where.selected.exactly = "no", source = pay_education) %>% # recode_to(to = "dd", where.selected.exactly = "dnk") %>% ### health new_recoding(target = spent_health_middle, source = cash_bracket_treatment) %>% recode_to(to = 5, where.selected.exactly = "usd_0_9") %>% recode_to(to = 30, where.selected.exactly = "usd_10_50") %>% recode_to(to = 75, where.selected.exactly = "usd_50_100") %>% recode_to(to = 100, where.selected.exactly = "usd_more_100") %>% recode_to(to = 0, where.selected.exactly = "no", source = pay_health) %>% # recode_to(to = "dd", where.selected.exactly = "dnk") %>% ### water new_recoding(target = spent_water_middle, source = how_much_pay_water) %>% recode_to(to = 30, where.selected.exactly = "less_than_10") %>% recode_to(to = 45, where.selected.exactly = "11_20_month") %>% recode_to(to = 75, where.selected.exactly = "21_30_month") %>% recode_to(to = 105, where.selected.exactly = "31_40_month") %>% recode_to(to = 135, where.selected.exactly = "41_50_month") %>% recode_to(to = 150, where.selected.exactly = "50_more_month") %>% # recode_to(to = "dd", where.selected.exactly = "dnk") %>% ### food new_recoding(target = spent_food_middle, source = spent_food) %>% recode_to(to = 30, where.selected.exactly = "less10") %>% recode_to(to = 45, where.selected.exactly = "11_20") %>% recode_to(to = 75, where.selected.exactly = "21_30") %>% recode_to(to = 105, where.selected.exactly = "31_40") %>% recode_to(to = 135, where.selected.exactly = "41_50") %>% recode_to(to = 165, where.selected.exactly = "51_60") %>% recode_to(to = 195, where.selected.exactly = "61_70") %>% recode_to(to = 225, where.selected.exactly = "71_80") %>% recode_to(to = 255, where.selected.exactly = "81_90") %>% recode_to(to = 285, where.selected.exactly = "91_100") %>% recode_to(to = 300, where.selected.exactly = "100more") %>% # recode_to(to = "dd", where.selected.exactly = "dnk") %>% end_recoding() y_n_to_zero <- function(dataset, y_n_col) { y_n_col_sym <- sym(y_n_col) score_col <- sym(sub(pattern = "_y_n", x = y_n_col, replacement = "")) dataset_r <- dataset %>% dplyr::mutate(!!score_col := ifelse(!!y_n_col_sym == "no", 0, !!score_col)) return(dataset_r[[score_col]]) } fcs_y_n_names <- grep("y_n", names(response), value = T) new_fcs <- lapply(fcs_y_n_names, y_n_to_zero, dataset = response) %>% do.call(cbind, .) %>% as.data.frame() fcs_names <- sub(pattern = "_y_n", x = fcs_y_n_names, replacement = "") names(new_fcs) <- fcs_names response[, fcs_names] <- new_fcs
ed27df0eaaded8ae3af56424b3a7c23e8fad385d
ca9391015da1e043c1ef54d05cf57343653b12bb
/Rscripts/bmaPredictionNormalizedWeights.R
1983aab3e7049a0b6f8d42bc284dfb43ea437cd3
[]
no_license
shahanesanket/Multi-temporal-Classification-of-satellite-images
0862e85cd72f53e662989f89114003b0c1898ce0
dc169fbe97d8e851881bdfceae4dac8fdaa981d9
refs/heads/master
2021-01-18T16:48:32.055109
2017-03-31T05:16:16
2017-03-31T05:16:16
86,773,384
0
0
null
2017-03-31T03:19:16
2017-03-31T03:19:16
null
UTF-8
R
false
false
2,677
r
bmaPredictionNormalizedWeights.R
library(e1071) setwd("C:/Users/Sanket Shahane/Google Drive/MS/ALDA/Project/Multi-Temporal-Classification/TrainingData/ValidationData") dataset1=read.csv("ValidationData-2015-04-19.csv") dataset2=read.csv("ValidationData-2015-12-31.csv") dataset3=read.csv("ValidationData-2016-01-16.csv") dataset4=read.csv("ValidationData-2016-03-20.csv") setwd("C:/Users/Sanket Shahane/Google Drive/MS/ALDA/Project/Multi-Temporal-Classification/TrainingData/AccuracyTestingData") dataset1=read.csv("AccuracyData-2015-04-19.csv") dataset2=read.csv("AccuracyData-2015-12-31.csv") dataset3=read.csv("AccuracyData-2016-01-16.csv") dataset4=read.csv("AccuracyData-2016-03-20.csv") dataset1 = dataset1[,-c(1,2,3)] dataset2 = dataset2[,-c(1,2,3)] dataset3 = dataset3[,-c(1,2,3)] dataset4 = dataset4[,-c(1,2,3)] setwd("C:/Users/Sanket Shahane/Google Drive/MS/ALDA/Project/Multi-Temporal-Classification/Rscripts") load("image1.BMAmodel.LogWeighted.rda") load("image2.BMAmodel.LogWeighted.rda") load("image3.BMAmodel.LogWeighted.rda") load("image4.BMAmodel.LogWeighted.rda") bmaPrediction <- function(sample,i){ if(nrow(sample)!=4){ print("error in input") return(NULL) } w1 = image1.BMAmodel.LogWeighted[[3]] w2 = image2.BMAmodel.LogWeighted[[3]] w3 = image3.BMAmodel.LogWeighted[[3]] w4 = image4.BMAmodel.LogWeighted[[3]] s = w1+w2+w3+w4 w1 = w1/s w2 = w2/s w3 = w3/s w4 = w4/s w1 = 1 - w1 w2 = 1 - w2 w3 = 1 - w3 w4 = 1 - w4 #print(w1) #print(w2) #print(w3) #print(w4) #print(paste("Weights:",w1,w2,w3,w4)) p1 = data.frame(predict(image1.BMAmodel.LogWeighted[[1]],sample[1,-1],type="raw"))*w1 p2 = data.frame(predict(image2.BMAmodel.LogWeighted[[1]],sample[2,-1],type="raw"))*w2 p3 = data.frame(predict(image3.BMAmodel.LogWeighted[[1]],sample[3,-1],type="raw"))*w3 p4 = data.frame(predict(image4.BMAmodel.LogWeighted[[1]],sample[4,-1],type="raw"))*w4 currProbabilities = rbind(p1,p2,p3,p4) currProbabilities = apply(currProbabilities,2,mean) #print(currProbabilities) class = as.integer(which.max(currProbabilities)) #print(class) # write this class to a data frame return(class) } outputDataFrame = dataset1 outputDataFrame = cbind(outputDataFrame,data.frame(NaN)) for (i in seq(1,nrow(outputDataFrame),1)) { sample = rbind(dataset1[i,],dataset2[i,],dataset3[i,],dataset4[i,]) class = bmaPrediction(sample,i) outputDataFrame[i,10] = class } sum(outputDataFrame[,1]==outputDataFrame[,10])/nrow(outputDataFrame) # Mean accuracy of 4 models: 0.8958333 #Normal BMA Acc=Trainset #0.9289617 #Normal BMA Accuracytest set #0.9111111
cdc2be40276701455b1df9817083ccf92e4a2a3a
c388b308e3136df65dc7c5c82e4cbd686192ba8f
/R/ggkaryo.R
08ed6e3ce0e103839d70b815366d169ad9f49f3c
[ "MIT" ]
permissive
ggirelli/ggkaryo2
1e9cf61e18f7f8fe056c68e6411a598dcb4474c0
0bd19c109479eeb98748186d4b0e11e26f7bb661
refs/heads/master
2021-06-20T09:49:11.443808
2020-06-25T04:57:31
2020-06-25T04:57:31
185,577,333
1
0
MIT
2020-06-25T04:57:33
2019-05-08T09:43:26
R
UTF-8
R
false
false
29,784
r
ggkaryo.R
#' ggkaryo: a class for karyotype plotting and overlaying. #' #' The \\code{ggkaryo} class allows to plot (labeled) ideograms and to overlay #' them with data track profiles and also highlight loci of interes (lois). #' #' @import methods #' @export ggkaryo #' @exportClass ggkaryo #' #' @importFrom cowplot theme_cowplot #' @importFrom ggplot2 aes #' @importFrom ggplot2 aes_string #' @importFrom ggplot2 element_blank #' @importFrom ggplot2 geom_polygon #' @importFrom ggplot2 geom_segment #' @importFrom ggplot2 ggplot #' @importFrom ggplot2 guides #' @importFrom ggplot2 guide_legend #' @importFrom ggplot2 scale_color_brewer #' @importFrom ggplot2 scale_fill_manual #' @importFrom ggplot2 theme #' @importFrom ggplot2 theme_set #' @importFrom ggplotify as.grob #' @importFrom grid grid.newpage #' @importFrom grid grid.draw #' @importFrom grid viewport #' @importFrom grid pushViewport #' @importFrom grid upViewport #' @import data.table #' @import methods #' @import RColorBrewer #' #' @field n_chrom (numerical) number of chromosomes, default: 24 #' @field hetero (character) heterosome labels (without "chr"), #' default: c("X", "Y") #' @field chrom_width (numerical) width of the ideograms, default: 1 #' @field chrom_padding (numerical) space between ideograms, default: 5 #' @field track_palette_name (character) name of RColorBrewer palette for track #' filling #' @field lois_palette_name (character) name of RColorBrewer palette for lois #' color #' @field giemsa_palette (character) vector of colors for the giemsa bands #' @field giemsa_levels (character) vector of giemsa band levels #' @field opposite (logical) to plot profiles on both sides of the ideogram #' @field data (list) contains ggkaryo data for plotting #' #' @examples #' require(data.table) #' require(ggkaryo2) #' #' # Load example data #' data('giemsa', package='ggkaryo2') #' data('track', package='ggkaryo2') #' data('lois', package='ggkaryo2') #' #' # Plot ideogram #' ggk = ggkaryo(giemsa) #' ggk$plot_full() #' #' # Plot ideogram with boxes around chromosome arms and labels #' ggk = ggkaryo(giemsa, show_arm_boxes=T, show_chrom_labels=T) #' ggk$plot_full() #' #' # Plot ideogram with one profile track #' ggk = ggkaryo(giemsa) #' binnedTrack = track #' ggk$add_track("track", binnedTrack, 1e5) #' ggk$plot_full() #' #' # Plot ideogram with two profile tracks on the same side #' ggk = ggkaryo(giemsa) #' binnedTrack2 = copy(binnedTrack) #' binnedTrack2[, value := value*abs(rnorm(nrow(binnedTrack2)))] #' ggk$add_track("track 1", binnedTrack, 1e5) #' ggk$add_track("track 2", binnedTrack2, 1e5) #' ggk$plot_full() #' #' # Plot ideogram with two profile tracks on opposite sides #' ggk = ggkaryo(giemsa, opposite=TRUE) #' binnedTrack2 = copy(binnedTrack) #' binnedTrack2[, value := value*abs(rnorm(nrow(binnedTrack2)))] #' ggk$add_track("track 1", binnedTrack, 1e5) #' ggk$add_track("track 2", binnedTrack2, 1e5) #' ggk$plot_full() #' #' # Plot ideogram with two profile tracks on opposite sides and central lois #' ggk = ggkaryo(giemsa) #' binnedTrack2 = copy(binnedTrack) #' binnedTrack2[, value := value*abs(rnorm(nrow(binnedTrack2)))] #' ggk$add_track("track 1", binnedTrack, 1e5) #' ggk$add_track("track 2", binnedTrack2, 1e5) #' loiData = lois #' ggk$add_lois("Sample type", loiData, "center", "sample") #' ggk$plot_full() #' #' # Plot ideogram with two profile tracks on opposite sides and central lois #' # Showing all legends #' ggk = ggkaryo(giemsa, show_arm_boxes=T, show_chrom_labels=T, #' show_giemsa_guide = T, show_tracks_guide = T) #' binnedTrack2 = copy(binnedTrack) #' binnedTrack2[, value := value*abs(rnorm(nrow(binnedTrack2)))] #' ggk$add_track("track 1", binnedTrack, 1e5) #' ggk$add_track("track 2", binnedTrack2, 1e5) #' loiData = lois #' ggk$add_lois("Sample type", loiData, "center", "sample") #' ggk$plot_full() #' ggkaryo <- setRefClass("ggkaryo", fields = list( n_chrom = "numeric", hetero = "character", chrom_width = "numeric", chrom_padding = "numeric", track_palette_name = "character", lois_palette_name = "character", giemsa_palette = "character", giemsa_levels = "character", opposite = "logical", data = "list", show_giemsa_guide = "logical", show_tracks_guide = "logical", show_arm_boxes = "logical", show_chrom_labels = "logical" ), method = list( initialize = function(giemsa, ..., n_chrom=24, hetero=c("X", "Y"), chrom_width=1, chrom_padding=5, track_palette_name="Paired", lois_palette_name="Dark2", giemsa_palette=c( "#DDDDDD", "#C0C0C0", "#A8A8A8", "#808080", "#545454", "#404040", "#000000", "#FF0000", "#C4FFFC", "#AFE6FF"), giemsa_levels=c( "gneg", "gpos25", 'gpos33', "gpos50", 'gpos66', "gpos75", "gpos100", "acen", "gvar", "stalk"), opposite=FALSE, show_giemsa_guide = F, show_tracks_guide = F, show_arm_boxes = F, show_chrom_labels = F ) { "Initializer method. See \\code{ggkaryo} description for more details" stopifnot(length(giemsa_levels) == length(giemsa_palette)) stopifnot(chrom_width > 0) stopifnot(chrom_padding >= chrom_width) callSuper(..., n_chrom=n_chrom, hetero=hetero, chrom_width=chrom_width, chrom_padding=chrom_padding, track_palette_name=track_palette_name, lois_palette_name=lois_palette_name, giemsa_palette=giemsa_palette, giemsa_levels=giemsa_levels, opposite=opposite, data=list(tracks=list(), lois=list(), plot=list()), show_giemsa_guide=show_giemsa_guide, show_tracks_guide=show_tracks_guide, show_arm_boxes=show_arm_boxes, show_chrom_labels=show_chrom_labels ) names(.self$giemsa_palette) = giemsa_levels .self$prep4karyo(giemsa) }, chrom2id = function(chrom) { "Converts a chromosome signature (seqname) to a numerical id. \\describe{ \\item{\\code{chrom}}{ (string) chromosome signature (e.g., 'chr1' or '1')} } \\describe{\\item{returns}{numeric: chromosome numerical ID}}" if ( grepl("^chr", chrom) ) chrom = gsub("^chr", "", chrom) if ( grepl(":", chrom) ) { return(floor(as.numeric(gsub(":", ".", chrom)))) } else { if ( chrom %in% hetero ) { return(.self$n_chrom-length(.self$hetero)+which(.self$hetero==chrom)) } else { return(as.numeric(chrom)) } } }, chromID2x = function(chromID) { "Retrieve the position of a chromosome on the X axis. \\describe{ \\item{\\code{chromID}}{(numeric)} } \\describe{\\item{returns}{numeric: chromosome position on the X axis}}" return((chromID-1)*(.self$chrom_width + .self$chrom_padding)) }, norm2x = function(chromID, norm, position) { "Converts normalized score to X coordinate in the ggkaryo plot. \\describe{ \\item{\\code{chromID}}{(numeric)} \\item{\\code{norm}}{(numeric) normalized score} \\item{\\code{position}}{(character) 'left' or 'right'} } \\describe{\\item{returns}{numeric: normalized score X coordinate}}" padding = .self$chrom_padding if ( .self$opposite ) padding = padding / 2 if ( "right" == position ) { return(.self$chromID2x(chromID)+.self$chrom_width+norm*padding) } else { stopifnot(.self$opposite) return(.self$chromID2x(chromID)-norm*padding) } }, read_giemsa = function(giemsa) { "Reads a Giemsa bed file. Adds chromID, bandID, and X columns. \\describe{ \\item{\\code{giemsa}}{(character) path to giemsa BED5+ file} \\item{\\code{giemsa}}{(data.table) data table with giemsa BED5+ data} } \\describe{\\item{returns}{data.table: adjusted giemsa data.table}}" if ( is(giemsa, "character") ) { stopifnot(file.exists(giemsa)) giemsa = fread(giemsa) } stopifnot(is.data.table(giemsa)) stopifnot(ncol(giemsa) >= 5) giemsa = giemsa[, 1:5] colnames(giemsa) = c("chrom", "start", "end", "name", "value") giemsa[, chromID := unlist(lapply(chrom, .self$chrom2id))] giemsa[, x := unlist(lapply(chromID, .self$chromID2x))] giemsa[, bandID := paste0(chrom, ":", start, "-", end)] return(giemsa) }, prep4bands = function() { "Prepares data for plotting chromosome bands. Builds .self\\$data[['bands']] object." stopifnot("giemsa" %in% names(.self$data)) stopifnot(is.data.table(.self$data[['giemsa']])) non_acen_bands = data.table( chrom = rep(.self$data[["giemsa"]]$chrom, each = 4), chromID = rep(.self$data[["giemsa"]]$chromID, each = 4), y = c(t(cbind( .self$data[["giemsa"]]$start, .self$data[["giemsa"]]$start, .self$data[["giemsa"]]$end, .self$data[["giemsa"]]$end))), x = c(t(cbind( .self$data[["giemsa"]]$x, .self$data[["giemsa"]]$x+.self$chrom_width, .self$data[["giemsa"]]$x+.self$chrom_width, .self$data[["giemsa"]]$x))), value = rep(.self$data[["giemsa"]]$value, each = 4), bandID = rep(.self$data[["giemsa"]]$bandID, each = 4) ) non_acen_bands = non_acen_bands[non_acen_bands$value != "acen",] .self$data[["bands"]] = non_acen_bands if ( 0 != .self$data[["giemsa"]][value == "acen", .N] ) { acen_data = .self$data[["giemsa"]][value == "acen", .( start = min(start), end = max(end), name = NA, value = "acen", x = x[1], bandID = bandID[1] ), by = c("chrom", "chromID")] acen_bands = data.table( chrom = rep(acen_data$chrom, each = 4), chromID = rep(acen_data$chromID, each = 4), y = c(t(cbind(acen_data$start, acen_data$start, acen_data$end, acen_data$end))), x = c(t(cbind(acen_data$x, acen_data$x+.self$chrom_width, acen_data$x, acen_data$x+.self$chrom_width))), value = rep(acen_data$value, each = 4), bandID = rep(acen_data$bandID, each = 4) ) .self$data[["bands"]] = rbind(.self$data[["bands"]], acen_bands) } .self$data[["bands"]][, value := factor(value, levels = .self$giemsa_levels)] NULL }, prep4boxes = function() { "Prepares data for plotting chromosome arm boxes. Chromosome arms are identified based on the 'acen' bands that are used to divide each chromosomes in two arms. Builds .self\\$data[['boxes']] object." stopifnot("giemsa" %in% names(.self$data)) stopifnot(is.data.table(.self$data[['giemsa']])) select_chrom_arms = function(chrom_data) { chrom_x = .self$chromID2x(chrom_data[1, chromID]) acen_band_ids = which(chrom_data$value == "acen") if ( 0 == length(acen_band_ids) ) { acen_band_ids = c(nrow(chrom_data)+1) } if ( ! 1 %in% acen_band_ids ) { p_arm_data = chrom_data[1:(min(acen_band_ids)-1), .( x = c(chrom_x, chrom_x, chrom_x+.self$chrom_width, chrom_x+.self$chrom_width, chrom_x), y = c(min(start), max(end), max(end), min(start), min(start)), arm_id = "p" )] } else { p_arm_data = NULL } if ( ! nrow(chrom_data) %in% acen_band_ids ) { q_arm_data = chrom_data[(max(acen_band_ids)+1):nrow(chrom_data), .( x = c(chrom_x, chrom_x, chrom_x+.self$chrom_width, chrom_x+.self$chrom_width, chrom_x), y = c(min(start), max(end), max(end), min(start), min(start)), arm_id = "q" )] } else { q_arm_data = NULL } return(rbind(q_arm_data, p_arm_data)) } .self$data[["boxes"]] = .self$data[["giemsa"]][, select_chrom_arms(.SD), by="chrom"] NULL }, prep4labels = function() { "Prepares data for plotting chromosome labels. Builds .self\\$data[['chrom_labels']] object." stopifnot("giemsa" %in% names(.self$data)) stopifnot(is.data.table(.self$data[['giemsa']])) .self$data[['chrom_labels']] = .self$data[["giemsa"]][, .( x = min(x) + .self$chrom_width/2, y = -5 * 10**(ceiling(abs(log10(max(.self$data[["giemsa"]]$end))))-3) ), by = c("chrom", "chromID")] NULL }, prep4plot = function() { "Prepares for plotting. Builds .self\\$data[['plot']] object." stopifnot("bands" %in% names(.self$data)) stopifnot(is.data.table(.self$data[['bands']])) if ( .self$opposite ) { xlim = c(.self$data[['bands']][, min(x)]-.self$chrom_padding/2, .self$data[['bands']][, max(x)]+.self$chrom_padding/2) } else { xlim = c(.self$data[['bands']][, min(x)], .self$data[['bands']][, max(x)]+.self$chrom_padding) } .self$data$plot$baseLayer = ggplot(.self$data[['bands']], aes(x=x, y=-y) ) + geom_polygon(aes(fill=value, group=bandID) ) + scale_fill_manual(values=.self$giemsa_palette ) + theme(axis.line = element_blank(), axis.ticks = element_blank(), axis.title = element_blank(), axis.text = element_blank(), plot.margin = grid::unit(c(0, 0, 0, 0), "points"), legend.position = "top", legend.background = element_rect(color = "black"), legend.margin = margin(10, 10, 10, 10), legend.box.margin = margin(5, 5, 5, 5), legend.title = element_text(face = "bold") ) + guides(fill = F ) + ylim(c(-.self$data[['bands']][, max(y)], 5e6) ) + xlim(xlim ) if ( .self$show_giemsa_guide ) { .self$data$plot$baseLayer = .self$data$plot$baseLayer + guides( fill = guide_legend(title = "Giemsa", nrow = 1)) } else { .self$data$plot$baseLayer = .self$data$plot$baseLayer + guides(fill = F ) + theme(plot.margin = grid::unit(c(59.5, 0, 0, 0), "points")) } .self$data$plot$trackLayer = ggplot(.self$data[['bands']], aes(x=x, y=-y) ) + geom_polygon(aes(group=bandID), fill = NA ) + theme(axis.line = element_blank(), axis.ticks = element_blank(), axis.title = element_blank(), axis.text = element_blank(), plot.margin = grid::unit(c(0, 0, 0, 0), "points"), legend.position = "top", legend.justification = c(1, 1), legend.background = element_rect(color = "black"), legend.margin = margin(10, 10, 10, 10), legend.box.margin = margin(5, 5, 5, 5), legend.title = element_text(face = "bold") ) + ylim(c(-.self$data[['bands']][, max(y)], 5e6) ) + xlim(xlim ) if ( .self$show_tracks_guide ) { .self$data$plot$trackLayer = .self$data$plot$trackLayer + guides( fill = guide_legend(title = "Tracks", nrow = 1), color = guide_legend(nrow = 1) ) } else { .self$data$plot$trackLayer = .self$data$plot$trackLayer + guides( fill = F, color = F ) + theme(plot.margin = grid::unit(c(59.5, 0, 0, 0), "points")) } if ( !.self$show_giemsa_guide & !.self$show_tracks_guide ) { .self$data$plot$baseLayer = .self$data$plot$baseLayer + theme( plot.margin = grid::unit(c(0, 0, 0, 0), "points")) .self$data$plot$trackLayer = .self$data$plot$trackLayer + theme( plot.margin = grid::unit(c(0, 0, 0, 0), "points")) } NULL }, prep4karyo = function(giemsa) { "Builds a data.table to plot the ideograms and (optionally) boxes around each chromosome arm. \\describe{ \\item{\\code{giemsa}}{(character) path to giemsa BED5+ file} \\item{\\code{giemsa}}{(data.table) data table with giemsa BED5+ data} } \\describe{\\item{returns}{data.table: adjusted giemsa data.table}}" .self$data[["giemsa"]] = .self$read_giemsa(giemsa) .self$prep4bands() .self$prep4boxes() .self$prep4labels() .self$prep4plot() NULL }, get_color = function(color, trackID) { "Extracts, in order, track colors from the .self\\$track_palette_name. See RColorBrewer for more details. \\describe{ \\item{\\code{color}}{(character) a color or 'auto'} \\item{\\code{trackID}}{(numeric) track number} }" if ( "auto" == color ) { nTracks = max(3, length(.self$data[["tracks"]])) color = brewer.pal(nTracks, .self$track_palette_name)[trackID] } color }, get_next_position = function(position) { "Selects position for the next track in such a fashion to balance out left/right sides of the ideograms. \\describe{ \\item{\\code{position}}{(character) 'right', 'left', or 'auto'} }" stopifnot(position %in% c("auto", "right", "left")) if ( "auto" == position ) { if ( 0 == length(.self$data[['tracks']]) ) return("right") if ( !.self$opposite ) { position = "right" } else { position_count = table(unlist(lapply(.self$data[['tracks']], function(x) x$position))) position_count = data.table( label = c("right", "left"), n = c( max(0, position_count["right"], na.rm = T), max(0, position_count["left"], na.rm = T) ) ) if ( position_count[1, n] == position_count[2, n] ) { return("right") } else { return(position_count[which.min(position_count$n), label]) } } } position }, bin_track = function(track, size, step, method="within", fun.aggreg=mean, ...) { "Bins a track based on provided bin size and step. Regions from the track are assigned to the bins when they are completely include ('within' method) or overlap even partially ('overlap' method). \\describe{ \\item{\\code{track}}{(data.table) BED5+ track data table} \\item{\\code{size}}{(numeric) bin size in nt} \\item{\\code{step}}{(numeric) bin step in nt} \\item{\\code{method}}{(string) either 'within' or 'overlap'} \\item{\\code{fun.aggreg}}{(function) how to aggregate values in bins} \\item{\\code{...}}{(mixed) additional parameters to pass to fun.aggreg} } \\describe{\\item{returns}{data.table: binned track}}" stopifnot(is.data.table(track)) stopifnot(ncol(track) >= 5) stopifnot(method %in% c("within", "overlap")) track = track[, 1:5] colnames(track) = c("chrom", "start", "end", "name", "value") track[, chromID := unlist(lapply(chrom, .self$chrom2id))] mk_bins = function(chrom_data, size, step) { "Generates a list of bins of given size and step." end = max(chrom_data$end, na.rm = T) starts = seq(0, end-step, by=step) data.table(start = starts, end = starts+size, value = 0) } select_overlap = function(data, start, end) data$start > start | data$end <= end select_within = function(data, start, end) data$start > start & data$end <= end bin_chrom = function(chrom_data, size, step, method, fun.aggreg=mean, ...) { "Bin chromosome data using given size and step." select_regions = ifelse("within"==method, select_within, select_overlap) chrom_data = chrom_data[order(start)] bins = mk_bins(chrom_data, size, step) for ( bi in 1:nrow(bins) ) { ri = which(select_regions(chrom_data, bins[bi, start], bins[bi, end])) bins[bi, value := fun.aggreg(chrom_data[ri, value], ...)] } return(bins) } track[, bin_chrom(.SD, size, step, method, fun.aggreg, na.rm=T), by=c("chrom", "chromID")][, .(chrom, start, end, paste0("bin_", 1:.N), value)] }, add_track = function(name, track, step, position = "auto", color = "auto", alpha = .5) { "Adds a profile to the current ggkaryo plot. The input track must have already been binned with a consistent step. A consistent step is needed to automatically set any gap to 0 in the profile. Builds .self\\$data[['tracks']]. \\describe{ \\item{\\code{name}}{(character) track name for legend} \\item{\\code{track}}{(character) path to BED5+ file} \\item{\\code{track}}{(data.table) BED5+ data table} \\item{\\code{step}}{(numerical) bin step in nt} \\item{\\code{position}}{(character) one of auto|left|right. 'left' can be used only if opposite=T was used when initializing the ggkaryo object} \\item{\\code{color}}{(character) either 'auto' or a color string} \\item{\\code{alpha}}{(numerical) opacity level.} }" position = .self$get_next_position(position) stopifnot(alpha <= 1 & alpha > 0) if ( is(track, "character") ) { stopifnot(file.exists(track)) track = data.table::fread(track) } stopifnot(is.data.table(track)) stopifnot(ncol(track) >= 5) track = track[, 1:5] colnames(track) = c("chrom", "start", "end", "name", "value") track[, chromID := unlist(lapply(chrom, .self$chrom2id))] #track[is.na(value), value := 0] track = track[order(start)] track = track[order(chromID)] track[, norm := value - min(value, na.rm = T)] track[, norm := value / max(value, na.rm = T)] track[is.na(norm), norm := 0] stopifnot(all(track[, .(v=unique(diff(start))), by=chrom]$v == step)) set_gaps_to_zero = function(chrom_data, step) { "Adds 0s where gaps are detected in the track." id = which(diff(chrom_data$start) != step) if ( 0 == length(id) ) return(chrom_data) basepoints = chrom_data[c(id[1], id[1]+1),] basepoints[, norm := 0] if ( 1 == length(id) ) { return(do.call(rbind, list( chrom_data[1:id[1],], basepoints, chrom_data[(id[1]+1):nrow(chrom_data),]))) } else { out = do.call(rbind, list( chrom_data[1:id[1],], basepoints, do.call(rbind, lapply(2:length(id), FUN = function(ii) { basepoints = chrom_data[c(id[ii], id[ii]+1),] basepoints[, norm := 0] rbind(chrom_data[(id[ii-1]+1):id[ii],], basepoints) })), chrom_data[(id[length(id)]+1):nrow(chrom_data),] )) return(out) } } track = track[, set_gaps_to_zero(.SD, step), by = chrom] add_chrom_ends = function(chrom_data) { "Sets the chromosome ends to 0." pre = chrom_data[1,] pre$value = NA; pre$norm = 0 pos = chrom_data[nrow(chrom_data),] pos$value = NA; pos$norm = 0 do.call(rbind, list(pre, chrom_data, pos)) } track = track[, add_chrom_ends(.SD), by=chrom] nTracks = length(.self$data[['tracks']]) track$trackname = name .self$data[['tracks']][[nTracks+1]] = list( data = track, name = name, position = position, color = color, alpha = alpha) }, add_lois = function(name, loiData, position, colorName, alpha = 1) { "Adds details on Loci Of Interest (loi) to the current ggkaryo plot. Builds .self\\$data[['lois']]. \\describe{ \\item{\\code{name}}{(character) loi track name for legend} \\item{\\code{loiData}}{(character) path to BED5+ loi file} \\item{\\code{loiData}}{(data.table) data.table with BED5+ loi data} \\item{\\code{position}}{(character) either 'left', 'right' or 'center'} \\item{\\code{colorName}}{(character) column with color factors} \\item{\\code{alpha}}{(numeric) opacity level} }" stopifnot(position %in% c("left", "right", "center")) if ( !.self$opposite ) stopifnot(position %in% c("right", "center")) stopifnot(alpha <= 1 & alpha > 0) if ( is(loiData, "character") ) { stopifnot(file.exists(loiData)) loiData = data.table::fread(loiData) } stopifnot(is.data.table(loiData)) stopifnot(ncol(loiData) >= 5) stopifnot(colorName %in% names(loiData)) loiData = loiData[, .SD, .SDcols=c(1:5, which(names(loiData)==colorName))] colnames(loiData) = c("chrom", "start", "end", "name", "value", colorName) loiData[, chromID := unlist(lapply(chrom, .self$chrom2id))] loiData[is.na(value), value := 0] loiData[, colorName] = factor(unlist(loiData[, .SD, .SDcols=colorName])) .self$data[['lois']] = list(data=loiData, name = name, position=position, color=colorName, alpha=alpha) }, add_arm_boxes = function() { "Adds boxes around chromosome arms." .self$data$plot$baseLayer = .self$data$plot$baseLayer + geom_path( data=.self$data[['boxes']], aes(group=paste0(chrom, "_", arm_id)), color="black") }, add_chrom_labels = function() { "Adds chromosome labels." .self$data$plot$baseLayer = .self$data$plot$baseLayer + geom_text( data = .self$data[['chrom_labels']], aes(label = chrom), size = 5, angle = 45, hjust = 0.1, vjust = 0.5 ) }, plot_base = function() { "Plots the current ggkaryo object (only basic layers)." theme_set(theme_cowplot()) .self$prep4plot() print(.self$data$plot$baseLayer) }, add_lois_overlay = function() { "Overlays track profiles to a ggkaryo plot." if ( 0 != length(.self$data[['lois']]) ) { lois = .self$data[['lois']] padding = .self$chrom_padding if ( .self$opposite ) padding = padding/2 if ( lois$position == "right" ) { lois$data[, x := .self$chromID2x(lois$data$chromID)+.self$chrom_width] lois$data[, xend := .self$chromID2x(lois$data$chromID )+.self$chrom_width+padding] } if ( lois$position == "left" ) { lois$data[, x := .self$chromID2x(lois$data$chromID)-padding] lois$data[, xend := .self$chromID2x(lois$data$chromID)] } if ( lois$position == "center" ) { lois$data[, x := .self$chromID2x(lois$data$chromID)+.self$chrom_width] lois$data[, xend := .self$chromID2x(lois$data$chromID)] } lois$data[, y := (start+end)/2] `+.uneval` <- function(a,b) { `class<-`(modifyList(a,b), "uneval") } .self$data$plot$trackLayer = .self$data$plot$trackLayer + geom_segment( data=lois$data, aes(xend=xend, yend=-y ) + aes_string(color=lois$color), alpha=lois$alpha ) + scale_color_brewer(palette=.self$lois_palette_name ) if ( .self$show_tracks_guide ) { .self$data$plot$trackLayer = .self$data$plot$trackLayer + guides( color = guide_legend(title = lois$name)) } } else { if ( .self$show_giemsa_guide ) { .self$data$plot$trackLayer = .self$data$plot$trackLayer + guides(color = F ) + theme(plot.margin = grid::unit(c(59.5, 0, 0, 0), "points"),) } else { .self$data$plot$trackLayer = .self$data$plot$trackLayer + guides(color = F ) + theme(plot.margin = grid::unit(c(0, 0, 0, 0), "points"),) } } }, add_track_overlay = function() { "Overlays track profiles to a ggkaryo plot." nTracks = length(.self$data[['tracks']]) if ( 0 != nTracks ) { for ( trackID in 1:nTracks ) { track = .self$data[['tracks']][[trackID]] track$data[, x := .self$norm2x(chromID,norm,track$position), by=chrom] track$data[, y := start+(end-start)/2] .self$data$plot$trackLayer = .self$data$plot$trackLayer + geom_polygon( data = as.data.frame(track$data), aes(group = chrom, fill = trackname), alpha = track$alpha) } if ( .self$show_tracks_guide ) { colorList = unlist(lapply(1:length(.self$data$tracks), function(i) { .self$get_color(.self$data$tracks[[i]]$color, i) })) nameList = unlist(lapply(.self$data$tracks, function(x) x$name)) .self$data$plot$trackLayer = .self$data$plot$trackLayer + scale_fill_manual( values = colorList, labels = nameList ) } else { .self$data$plot$trackLayer = .self$data$plot$trackLayer + guides(fill = F) } } else { if ( .self$show_giemsa_guide ) { .self$data$plot$trackLayer = .self$data$plot$trackLayer + guides(fill = F ) + theme(plot.margin = grid::unit(c(59.5, 0, 0, 0), "points"),) } else { .self$data$plot$trackLayer = .self$data$plot$trackLayer + guides(fill = F ) + theme(plot.margin = grid::unit(c(0, 0, 0, 0), "points"),) } } }, prep4fullplot = function() { "Prepares to plot the full ggkaryo object." .self$prep4plot() .self$add_lois_overlay() .self$add_track_overlay() if ( .self$show_arm_boxes ) .self$add_arm_boxes() if ( .self$show_chrom_labels ) .self$add_chrom_labels() }, plot_full = function(doPrep = T) { "Plots the current ggkaryo object with tracks and lois." if ( doPrep ) .self$prep4fullplot() theme_set(theme_cowplot()) p1 = as.grob(.self$data$plot$baseLayer) p2 = as.grob(.self$data$plot$trackLayer) p = grid.newpage() grid.draw(p1) vp = viewport(width=1, height=1, default.unit = "npc") pushViewport(vp) grid.draw(p2) upViewport() } ) )
db8adb13ff048b4c635aaa4b717d9a93a97da525
d921a3508ec3d708ab4453368ad3cd8a5858105e
/man/summary_tab.Rd
9d5800f8f923c56c9ebbfb237f8b2db26c960ba9
[]
no_license
taotliu/abcde
0cbd119df461f62d1892dce0033e7fc217be222e
9a86d44eec7d09cd0ed1b4ecc937b79d246aa5b6
refs/heads/master
2021-06-25T07:17:42.961026
2020-11-25T22:08:34
2020-11-25T22:08:34
143,824,989
0
0
null
null
null
null
UTF-8
R
false
true
512
rd
summary_tab.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/abcde.R \name{summary_tab} \alias{summary_tab} \title{A Summary Table Function} \usage{ summary_tab(xx, ref = NULL) } \arguments{ \item{xx}{Data of which a summary table is needed.} \item{ref}{A parent data, of which xx is a subset; useful when do stratified analyses} } \description{ This function allows you to generate a summary table of your data. } \examples{ summary_tab() summary_tab(iris) } \keyword{Summary} \keyword{Table}
98c1697da4c5b3369897e1e087ac6d9c4eb5c0ed
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/WufooR/examples/user_info.Rd.R
355df26151f4a2dcabbaea7f76ec84ed09d732d8
[]
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
210
r
user_info.Rd.R
library(WufooR) ### Name: user_info ### Title: Return information about the user ### Aliases: user_info ### ** Examples ## No test: user_info(debugConnection = 1L, domain = "wufoo.eu") ## End(No test)
e318f2f92ce3b1e0f2027c44f4e36193a4ee9ffc
5d50889012cb657cac8ba5e27d7f531b8f29dac2
/man/mycph.Rd
7d9da2d07e328ddc5ee080304429d2bc082b3390
[]
no_license
cardiomoon/moonBook
30a2fd5df73b3447ff7d7147d8c3f30d4afac9e9
eeb0afdc39f548ed1b384c3fc9eaafcdce3d2206
refs/heads/master
2023-03-18T08:10:09.957246
2023-03-12T11:37:17
2023-03-12T11:37:17
27,332,967
31
9
null
null
null
null
UTF-8
R
false
true
935
rd
mycph.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/mycph.R \name{mycph} \alias{mycph} \title{Perform coxph of individual expecting variables} \usage{ mycph(formula, data, digits = 2) } \arguments{ \item{formula}{An object of class "formula". Left side of ~ must be a variable of class Surv and the right side of ~ must have variables in an additive way.} \item{data}{A data.frame contains data for analysis.} \item{digits}{An integer indicating the number of decimal places (round) or significant digits to be used. Default value is 2.} } \value{ a data.frame consist of hazard ratio and 95\% confidence intervals and the p values. } \description{ Perform coxph of individual expecting variables } \examples{ require(survival) data(cancer) attach(colon) colon$TS=Surv(time,status==1) out=mycph(TS~.,data=colon) out HRplot(out,type=2,show.CI=TRUE,main="Hazard ratios of all individual variables") }
86d9d3eefb79854a5c8b53f7f438a1c662181fbd
f3f5b8a3ee512ac1d3e540eb9e293642a2373ce7
/결손그룹_최종.R
a90a28d823d7d0994bfaa852fa75e72a2ed149e1
[]
no_license
Yang-Munil/diabetes_related_occupation_in_Korean_population
184abc2440f2c9a7dee28f2524692524de19d218
36ce066fb6dc794068d56bcccc4091f5a13e2fa4
refs/heads/main
2023-07-08T14:55:10.525942
2021-08-12T10:42:56
2021-08-12T10:42:56
346,424,723
0
0
null
null
null
null
UTF-8
R
false
false
4,714
r
결손그룹_최종.R
library(scorecardModelUtils) library(ggplot2) library(Rprofet) df3 <- read.csv("C:/rproject/df3_columns.csv") binned <- BinProfet(df3, id= "TPR_NO_ENC", target= "TARGET", num.bins = 5) ## Binning variables WOE_dat <- WOEProfet(binned, "TPR_NO_ENC", "TARGET", 3:281) Score_dat <- ScorecardProfet(WOE_dat, target="TARGET", id= "TPR_NO_ENC", PDO = 50, BaseOdds = 10, BasePts = 1000, reverse = TRUE) df3_scorecard <- Score_dat$Scorecard Score_dat$Scorecard # 변수 WOE 시각화 names(binned) WOEplotter(binned, target= "TARGET", var= "A07_SNP_AMT_DUE_1Y_Bins") # 합치기 WOEplotter(binned, target= "TARGET", var= "A07_SNP_CNT_DUE_FIX_3Y_Bins") WOEplotter(binned, target= "TARGET", var= "A07_SNP_IN_ACCT_VR_1Y_Bins") WOEplotter(binned, target= "TARGET", var= "A09_SEIZ_CNT_SGG_Bins") WOEplotter(binned, target= "TARGET", var= "A02_CNP_AMT_3Y_Bins") WOEplotter(binned, target= "TARGET", var= "A02_CNP_CNT_Bins") WOEplotter(binned, target= "TARGET", var= "C1L120003_Bins") WOEplotter(binned, target= "TARGET", var= "C1L120014_Bins") WOEplotter(binned, target= "TARGET", var= "C1M123W06_Bins") WOEplotter(binned, target= "TARGET", var= "C1N2B3003_Bins") WOEplotter(binned, target= "TARGET", var= "C1Z000798_Bins") # 합치기 WOEplotter(binned, target= "TARGET", var= "C1Z000951_Bins") WOEplotter(binned, target= "TARGET", var= "C1Z001221_Bins") WOEplotter(binned, target= "TARGET", var= "C1Z001222_Bins") WOEplotter(binned, target= "TARGET", var= "C20220000_Bins") WOEplotter(binned, target= "TARGET", var= "C23220000_Bins") WOEplotter(binned, target= "TARGET", var= "D20110000_Bins") WOEplotter(binned, target= "TARGET", var= "D20131000_Bins") # 합치기 WOEplotter(binned, target= "TARGET", var= "D2Z000061_Bins") WOEplotter(binned, target= "TARGET", var= "KGRAD_Bins") # 합치기 WOEplotter(binned, target= "TARGET", var= "U5Z20K010_Bins") WOEplotter(binned, target= "TARGET", var= "U5Z21K010_Bins") WOEplotter(binned, target= "TARGET", var= "A09_SEIZ_BOOL_3Y_Bins") WOEplotter(binned, target= "TARGET", var= "A09_SEIZ_CNT_SGG_3Y_Bins") WOEplotter(binned, target= "TARGET", var= "A02_CNP_AMT_3YB_Bins") # 수정 WOEplotter(binned, target= "TARGET", var= "A02_CNP_SNP_CNT_MM_3Y_3YB_Bins") # 스코어기준점 추출 write.csv(df3_scorecard, "df3_scorecard_final.csv") ## Less points means more likely to default df3_score <- Score_dat$Results # 결손그룹 체납자, 수납자 df3_score$TARGET[df3_score$TARGET == 0] <- '체납자' df3_score$TARGET[df3_score$TARGET == 1] <- '수납자' df3_score$TARGET <- as.factor(df3_score$TARGET) ggplot(df3_score, aes(x=Score, fill = TARGET, color = TARGET)) + geom_histogram(aes(y=..density..), alpha=0.5, position = "dodge", binwidth = 15) + theme(legend.position = "top") + theme_minimal() + theme(legend.position = "top") + ggtitle("결손그룹 체납자, 수납자 스코어 분포(파일럿)") + theme(plot.title = element_text(family = "serif", face = "bold", hjust = 0.5, size = 20, color = "black")) + labs(x="스코어", y="인원수") + theme(axis.title = element_text(family = "serif", face = "bold", hjust = 0.5, size = 20, color = "black")) # 12월 파일럿 결과 df3 <- read.csv("C:/rproject/df3_12월.csv") df3$TARGET <- as.factor(df3$TARGET) ggplot(df3, aes(x=mySum, fill = TARGET, color = TARGET)) + geom_histogram(aes(y=..density..), alpha=0.5, position = "dodge", binwidth = 15) + theme(legend.position = "top") + theme_minimal() + theme(legend.position = "top") + ggtitle("12월 결손그룹 체납자, 수납자 스코어 분포(파일럿)") + theme(plot.title = element_text(family = "serif", face = "bold", hjust = 0.5, size = 20, color = "black")) + labs(x="스코어", y="인원수") + theme(axis.title = element_text(family = "serif", face = "bold", hjust = 0.5, size = 20, color = "black")) # 01월 파일럿 결과 df3 <- read.csv("C:/rproject/df3_01월.csv") df3$TARGET <- as.factor(df3$TARGET) ggplot(df3, aes(x=mySum, fill = TARGET, color = TARGET)) + geom_histogram(aes(y=..density..), alpha=0.5, position = "dodge", binwidth = 5) + theme(legend.position = "top") + theme_minimal() + theme(legend.position = "top") + ggtitle("01월 결손그룹 체납자, 수납자 스코어 분포(파일럿)") + theme(plot.title = element_text(family = "serif", face = "bold", hjust = 0.5, size = 20, color = "black")) + labs(x="스코어", y="인원수") + theme(axis.title = element_text(family = "serif", face = "bold", hjust = 0.5, size = 20, color = "black"))
dcf2f502764a41d474456286fa46ecaef0fbeba0
4e0b9875be157f920d06100903de632847f47939
/homework/hw7/cs571-hw7.R
a2822e7c5fc637be116d24e9fdb9e112ec0b611f
[]
no_license
ldfaiztt/cs571
3dab49591b62eaa2140a9aa433f989e874623489
1476ec0cb7050acc9333bada453c6aaae1f24967
refs/heads/master
2021-01-18T05:53:45.474261
2013-12-05T15:52:40
2013-12-05T15:52:40
null
0
0
null
null
null
null
UTF-8
R
false
false
415
r
cs571-hw7.R
# CS 571, Duke University, Fall 2013 # Matt Dickenson - mcd31 # Homework 6 setwd('~/github/cs571/homework/hw7') # Problem 2 beta02 = rbeta(1000, 0.2, 0.2) beta1 = rbeta(1000, 1, 1) beta10 = rbeta(1000, 10, 10) pdf("betasamps.pdf", height=6, width=2) par(mfrow=c(3,1)) hist(beta02, main="", xlab="alpha=(0.2, 0.2)") hist(beta1, main="", xlab="alpha=(1, 1)") hist(beta10, main="", xlab="alpha=(10, 10)") dev.off()
0f76f8ca4c467e850765d4355bb34b334009746e
86283f02afb6a0727cf66e671c82dbaed7139734
/Friendship/postana.R
8403d01136628654af709c3403ac68c47552f226
[ "MIT" ]
permissive
joshloyal/mcr
8c8d79848ef04c9e3c4fbcefef36d915ffab9e80
2142d86e8222604b7cb6147a5d19232fc33fdf29
refs/heads/master
2021-09-17T06:58:01.063476
2018-06-29T02:33:56
2018-06-29T02:33:56
null
0
0
null
null
null
null
UTF-8
R
false
false
682
r
postana.R
### load("result.RData") thetaZ<-apply(thetaZ.iter[-c(6:7),],1,quantile,probs=c(.025,.5,.975)) thetaX<-apply(thetaX.iter,1,quantile,probs=c(.025,.5,.975)) colnames(thetaZ)<-c("alpha1","alpha2","beta1","beta2","beta3","h") colnames(thetaX)<-c("b","a","c1","c2") thetaZ<-thetaZ[,c(3:5,1,2,6)] apply(thetaZ1.iter,1,quantile,probs=c(.025,.5,.975)) apply(thetaX1.iter,1,quantile,probs=c(.025,.5,.975)) acf(thetaZ.iter[8,] )$acf[11] pdf("hfmix.pdf",height=3,width=8,family="Times") par(mfrow=c(1,1),mar=c(3,3,1,1),mgp=c(1.75,.75,0)) plot( t(thetaZ.iter)[,8] ,type="l",xlab="iteration",ylab=expression(h)) abline(h=median(t(thetaZ.iter)[,8] ),lty=2) dev.off()
071fc55f2ded0a6936375c26caf55ea84b216492
29585dff702209dd446c0ab52ceea046c58e384e
/heatex/R/heatex.R
05170c96cf1c5c637130f5eeaefb0c86f18d5a6d
[]
no_license
ingted/R-Examples
825440ce468ce608c4d73e2af4c0a0213b81c0fe
d0917dbaf698cb8bc0789db0c3ab07453016eab9
refs/heads/master
2020-04-14T12:29:22.336088
2016-07-21T14:01:14
2016-07-21T14:01:14
null
0
0
null
null
null
null
UTF-8
R
false
false
3,603
r
heatex.R
# heatex.R # created: 14 February 2013 # last revised: 18 February 2013 heatex<-function(df){ # define constants ArAd<-0.70 # ratio of body area exposed to radiation versus the total body surface area. 0.70 for seated posture and 0.73 for standing l<-2430 # latent heat of evaporation of sweat m.coef<- 0.0001694 # permeance coefficient of the skin emit<-0.97 # emittance from the outer surface of a clothed body sigma<-0.0000000567 # Stefan-Boltzmann constant feff<-0.71 # effective radiation area of a clothed body # Calculations #-------------------------------- # Environmental variables #--------------------------------- # convert deg C to Kelvin tdb_K<-df$tdb + 273.16 # mean radiant temperature tr<-((1+(0.222 * (df$va ^0.5))) * (df$tg - df$tdb)) + df$tdb # convective heat transfer, hc hc<-8.3 * (df$va * 0.6) # radiative heat transfer coefficient, hr hr<-4 * emit * sigma * ArAd * ((273.2 + ((df$tcl + tr)/2)) ^ 3) # combined heat transfer coefficient, h h<- hc + hr # evaporative heat transfer coefficient, he he<-16.5 * hc # convert Pa from mmHg to kpa pa_kpa<-df$pa * 0.1333 #--------------------------- # Physiological Variables #--------------------------- # convert deg C to kelvin tskf_K<-df$tskf + 273.16 # body surface area, AD ad<-0.00718 * df$wt^0.425 * df$ht ^ 0.725 # mean body temperature, Tb tbi<-(0.33 * df$tski + 0.67 * df$tci) tbf<-(0.33 * df$tskf + 0.67 * df$tcf) # saturated water vapor pressure at the skin surface, Ps ps<-1.92 * df$tskf -25.3 ps_kpa<-ps * 0.1333 # convert mmHg to kPa #---------------------------- # Clothing variables #---------------------------- # clothing area factor, fcl fcl<- 1 + (0.31 * (df$icl/0.155)) # effective clothing insulation, Icle icle<-df$icl - ((fcl-1)/(0.155 * fcl * h)) # permeation efficiency factor of clothing, fpcl fpcl<- 1/(1+(0.344 * hc * icle)) # intrinsic thermal resistance of clothing, Rc rc<-(df$tskf - df$tdb)/hc # intrinsic evaporative resistance of clothing, Re re<-(ps_kpa - pa_kpa)/he #----------------------------------- # Partitional Calorimetry Equations #----------------------------------- # energy equivalent of oxygen, EE ee<-(0.23 * df$rer + 0.77) * 21166 # metabolic free energy production, M m<-(((ee * df$vo2 * df$time)/(df$time * 60))/ad) # mechanical efficiency, n n<-df$workrate/(m * ad) # internal heat production, Hi hi<-(m * (1-n)) # body heat storage, S s<-((3474 * df$bmi * (tbf - tbi))/(df$time * 60))/ad # heat transfer via conduction, K # convert deg C to kelvin tcl_K<-df$tcl + 273.16 k<-ad * ((tskf_K - tcl_K)/rc) # heat transfer via radiation, R. For radiation from clothing surface, replace tskf with tcl. r<-emit * sigma * fcl * feff *(df$tskf^4 - tr^4) # heat transfer via convection, C. If convection from a clothed surface, change tskf_K to tcl_K. conv<-(ad * fcl * hc * (tskf_K - tdb_K))/ ad # required evaporative heat loss, Ereq ereq<-hi - k - r- conv - s # maximal evaporative capacity of the environment, Emax emax<-fpcl * he * (ps_kpa - pa_kpa) # skin wettedness, w w<- ereq/ emax # Evaporative heat transfer via skin diffusion, Ed ed<-(l * m.coef * (ps - df$pa)) # Heat transfer by sweat evaporation from the skin surface, Esw esw<-((((df$bmi*1000) - ((df$bmf*1000) + df$sweat - df$fluidfood - df$urinefaeces))-((0.019 * df$vo2 * (44 - df$pa)) * df$time))*2430)/((df$time * 60) * ad) # Heat transfer via evaporation from the skin surface, Esk esk<- ed + esw # Return output results<-data.frame(tr,hc,hr,h,he,pa_kpa,fcl,icle,fpcl,rc,re,ad,tbi,tbf,ps,ps_kpa,m,n,hi,s,k,r,conv,ereq,emax,w,ed,esw,esk) } # End heatex function
d927dc3819418bb857f78a73545a3bf041c24fd4
2757ff6eccdbc5da6bb2b587de706767430eb1fb
/clp_dep/clp_dep.R
a37c040e6d4fea33da40c5db732139ab66da4ac9
[]
no_license
jakob-petereit/R_scripts
8257ae1eb21297a47b64b055b23f83405247e3b2
6f4f45ce7ba498cb7c8d9eedb5dcbc770f49605d
refs/heads/master
2020-06-13T21:15:18.980876
2019-08-05T20:16:09
2019-08-05T20:16:09
194,787,728
0
0
null
null
null
null
UTF-8
R
false
false
71,409
r
clp_dep.R
# libraries --------------------------------------------------------------- library(DEP) library(tidyverse) library(data.table) library(fitdistrplus) library(Biostrings) library(SummarizedExperiment) ###### read data --------------------------------------------------------------- data <- fread('data/proteinGroups.txt') data <- filter(data, Reverse != "+", `Potential contaminant` != "+") colnames(data) ##### Data preparation ####### #extract gene names from fasta header and sort data2 <- data %>% rowwise() %>% mutate(Gene.names=paste(filter(as.tibble(unlist(strsplit(`Fasta headers`,'|',fixed = T))),str_detect(value,'AT.G')==F,str_detect(value,'Chr')==F,is.na(as.numeric(value)))$value, collapse = ';')) data2 <- data2[,c(1,2,ncol(data2),3:(ncol(data2)-1))] ## remove pool and blank data2 <- data2[,which(str_detect(colnames(data2),'blan')==F)] data2 <- data2[,which(str_detect(colnames(data2),'pool')==F)] data2 <- data2[,which(str_detect(colnames(data2),'clp2p_4')==F)] ##add better annotations of complex I and remainder cI_anno <- fread('data/complex I annotation.csv', header = T) %>% dplyr::select(1:3) %>% as.tibble() cI_anno <- cI_anno %>% mutate(ACC=gsub(pattern = ', ',replacement = '/',x = ACC)) %>% mutate(ACC1=sapply(strsplit(ACC,'/'),'[',1), ACC2=sapply(strsplit(ACC,'/'),'[',2), ACC3=sapply(strsplit(ACC,'/'),'[',3)) %>% dplyr::select(-ACC) %>% gather(nr,ACC,ACC1:ACC3) %>% dplyr::select(-nr) %>% na.omit() %>% mutate(ACC=toupper(substr(ACC,1,9))) %>% dplyr::select(-group) all_anno <- readAAStringSet('data/Arabidopsis_thaliana.TAIR10.pep.all.fa') %>% as.data.frame() %>% rownames_to_column() %>% mutate(ACC=sapply(strsplit(rowname,'[.]'),'[',1), desc=sapply(strsplit(rowname,'symbol:',fixed=T),'[',2), desc=ifelse(is.na(desc),sapply(strsplit(rowname,' description:',fixed=T),'[',2),sapply(strsplit(desc,' description:',fixed=T),'[',1)), desc=sapply(strsplit(desc,';',fixed=T),'[',1), desc=sapply(strsplit(desc,' [Source',fixed=T),'[',1)) %>% dplyr::select(ACC,desc) all_anno <- all_anno %>% left_join(cI_anno) %>% mutate(desc=ifelse(is.na(Name),desc,Name)) %>% dplyr::select(-Name) %>% as.tibble() %>% distinct(ACC, .keep_all = T) #extract gene names from fasta header and sort data3 <- separate_rows(data2,`Majority protein IDs`, convert = T) %>% mutate(`Majority protein IDs`=toupper(substr(`Majority protein IDs`,1,9))) %>% left_join(all_anno, by=c('Majority protein IDs'='ACC')) data3 <- data3[,c(1:3,221,4:220)] data3 <- data3 %>% as.tibble() %>% dplyr::distinct(`Majority protein IDs`,desc,.keep_all = T) ##take best names(remove unknown) data3 <- data3 %>% mutate(Gene.names=ifelse(str_detect(desc,'unknown')==T,Gene.names,desc)) #check for duplicated gene names and remove isoform duplications in gene names data3$Gene.names %>% duplicated() %>% any() data2 <- data3 %>% rowwise() %>% mutate(Gene.names=paste(unique(unlist(strsplit(Gene.names, ';'))),collapse=';')) # Make unique names using the annotation in the "Gene.names" column as primary names and the annotation in "Protein.IDs" as name for those that do not have an gene name. data_unique <- make_unique(data2, "Gene.names", "Protein IDs", delim = ";") ##### Generate a SummarizedExperiment object and run DEP ####### # Generate a SummarizedExperiment object by parsing condition information from the column names LFQ_columns <- grep("LFQ.", colnames(data_unique)) # get LFQ column numbers data_se <- make_se_parse(data_unique, LFQ_columns) data_se # #normal distribution ? # #before log2 # data_dist <- data_unique[,which(str_detect(colnames(data_unique),'LFQ')==T)] %>% # gather(column,value) # descdist(data_dist$value) # hist(data_dist$value,col = 'royalblue',breaks = 500,xlim = c(0,50000000)) # #after # data_dist_after <- assay(data_se) %>% as.data.frame() %>% # gather(column,value) %>% # na.omit() # descdist(data_dist_after$value) # hist(data_dist_after$value, col='royalblue') # Less stringent filtering: # Filter for proteins that are identified in 2 out of 3 replicates of at least one condition data_filt2 <- filter_missval(data_se, thr = 1) data_filt <- data_filt2 # Normalize the data data_norm <- normalize_vsn(data_filt) # Impute missing data using random draws from a Gaussian distribution centered around a minimal value (for MNAR) data_imp <- impute(data_norm, fun = "MinProb", q = 0.01) data_diff_manual <- test_diff(data_imp, type = "manual", test = c("clp1s__vs_wts_", "clp2s__vs_wts_",'clp1p__vs_wtp_','clp2p__vs_wtp_')) data_diff <- data_diff_manual # Denote significant proteins based on user defined cutoffs --------------- dep <- add_rejections(data_diff, alpha = 0.1, lfc = log2(1)) dep <- add_rejections(data_diff, alpha = 0.05, lfc = log2(1)) data_results <- get_results(dep) data_results %>% filter(significant) %>% nrow() ##### PCA PLOT ####### # Plot the first and second principal components plot_pca(dep, x = 1, n=nrow(dep),y = 2, point_size = 4) ##### Cor Matrix ####### # Plot the Pearson correlation matrix plot_cor(dep, significant = TRUE, lower = 0, upper = 1, pal = "Reds") ##### Heatmap ####### # Plot a heatmap of all significant proteins with the data centered per protein plot_heatmap(dep, type = "centered", kmeans = TRUE, k = 6, col_limit = 4, show_row_names = F, indicate = c("condition", "replicate")) # Plot a heatmap of all significant proteins (rows) and the tested contrasts (columns) plot_heatmap(dep, type = "contrast", kmeans = TRUE, k = 6, col_limit = 10, show_row_names = FALSE) ##### Volcano Plot ####### # Plot a volcano plot for the contrast "Ubi6 vs Ctrl"" plot_volcano(dep, contrast = "clp1s__vs_wts_", label_size = 3, add_names = TRUE) plot_volcano(dep, contrast = "clp2s__vs_wts_", label_size = 3, add_names = TRUE) ##### Barplots of a protein of interest ####### #change levels dep_save <- dep dep@colData$condition <- gsub('_', '',dep@colData$condition) dep@colData$condition <- factor(dep@colData$condition, levels = c('wtp','clp1p','clp2p','wts','clp1s','clp2s',4)) # Plot a barplot for USP15 and IKBKG plot_single(dep, proteins = ' presequence protease 1 ') # Plot a barplot for the protein USP15 with the data centered plot_single(dep, proteins = ' lon protease 1 ', type = "centered") ##### Results table ####### # Generate a results table dep <- add_rejections(data_diff, alpha = 0.1, lfc = log2(1)) data_results <- get_results(dep) # Number of significant proteins data_results %>% filter(significant) %>% nrow() # Column names of the results table colnames(data_results) #custom single plot #old #remove 'significant' colnames data_results <- data_results[,which(str_detect(colnames(data_results),'significant')==F)] #long format(gather) data_long <- data_results %>% gather(sample,value,3:ncol(.)) %>% mutate(type=sapply(strsplit(sample,'__'),'[',3), type=ifelse(is.na(type)==T,sapply(strsplit(sample,'__'),'[',2),type), sample=sapply(strsplit(sample,'__'),'[',1), fraction=ifelse(sample %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(sample,1,nchar(sample)-1)) %>% dplyr::select(-sample) %>% rowwise() %>% spread(key = type,value = value) %>% mutate(ID=substr(ID,1,9)) #levels for genotype and fraction data_long$genotype <- factor(data_long$genotype, levels = c('wt','clp1','clp2')) data_long$fraction <- factor(data_long$fraction, levels = c('membrane','soluble')) #plot gene of interest dep <- add_rejections(data_diff, alpha = 0.1, lfc = log2(1)) # rownames(dep) <- ifelse(substr(rownames(dep),nchar(rownames(dep)), # nchar(rownames(dep)))==' ', # substr(rownames(dep),2,nchar(rownames(dep))-1), # substr(rownames(dep),2,nchar(rownames(dep)))) prot_of_interest <- 'AT1G48030' subset <- dep[filter(data_long,ID==prot_of_interest)$name[1]] means <- rowMeans(assay(subset), na.rm = TRUE) df_reps <- data.frame(assay(subset)) %>% rownames_to_column() %>% gather(ID, val, -rowname) %>% left_join(., data.frame(colData(subset)),by = "ID") df_reps$replicate <- as.factor(df_reps$replicate) df_reps <- df_reps %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), fraction=ifelse(condition %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(condition,1,nchar(condition)-1)) df <- df_reps %>% group_by(condition, rowname) %>% summarize(mean = mean(val,na.rm = TRUE), sd = sd(val, na.rm = TRUE), n = n()) %>% mutate(error = qnorm(0.975) * sd/sqrt(n), CI.L = mean - error, CI.R = mean + error) %>% as.data.frame() %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), fraction=ifelse(condition %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(condition,1,nchar(condition)-1)) rowname <- df$rowname[1] #levels df$genotype <- factor(df$genotype, levels = c('wt','clp1','clp2')) df$fraction <- factor(df$fraction, levels = c('membrane','soluble')) ggplot(df, aes(genotype, mean)) + geom_hline(yintercept = 0) + geom_col(colour = "black", fill = "grey") + geom_errorbar(aes(ymin = CI.L, ymax = CI.R), width = 0.3,size=1.2) + geom_jitter(data = df_reps, aes(genotype, val, col = replicate),alpha=0.5, size = 5, position = position_dodge(width = 0.3)) + labs(title=paste(prot_of_interest,rowname, sep=' - '),x = "sample", y = expression(log[2] ~ "Centered intensity" ~ "(?95% CI)"), col = "Rep") + facet_wrap(~fraction) + theme_DEP2() ###no log #remove 'significant' colnames data_results <- data_results[,which(str_detect(colnames(data_results),'significant')==F)] #long format(gather) data_long <- data_results %>% gather(sample,value,3:ncol(.)) %>% mutate(type=sapply(strsplit(sample,'__'),'[',3), type=ifelse(is.na(type)==T,sapply(strsplit(sample,'__'),'[',2),type), sample=sapply(strsplit(sample,'__'),'[',1), fraction=ifelse(sample %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(sample,1,nchar(sample)-1)) %>% dplyr::select(-sample) %>% rowwise() %>% spread(key = type,value = value) %>% mutate(ID=sapply(strsplit(ID,'[.]'),'[',1)) #### #plot gene of interest dep <- add_rejections(data_diff, alpha = 0.1, lfc = log2(1)) # rownames(dep) <- ifelse(substr(rownames(dep),nchar(rownames(dep)), # nchar(rownames(dep)))==' ', # substr(rownames(dep),2,nchar(rownames(dep))-1), # substr(rownames(dep),2,nchar(rownames(dep)))) prot_of_interest <- filter(data3, `Majority protein IDs` %in% cI_anno$ACC) %>% dplyr::select(2,3) %>% dplyr::rename(desc=Gene.names,ID=`Majority protein IDs`) subset <- dep[unique(filter(data_long,ID %in% prot_of_interest$ID)$name)] means <- rowMeans(assay(subset), na.rm = TRUE) df_reps <- data.frame(assay(subset)) %>% rownames_to_column() %>% gather(ID, val, -rowname) %>% left_join(., data.frame(colData(subset)),by = "ID") desc <- dplyr::select(data_long,name,ID) %>% left_join(prot_of_interest) %>% na.omit() %>% dplyr::rename(ACC=ID) df_reps <- left_join(df_reps,desc,by=c('rowname'='name')) %>% distinct() df_reps$replicate <- as.factor(df_reps$replicate) df_reps <- df_reps %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), fraction=ifelse(condition %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(condition,1,nchar(condition)-1)) %>% mutate(val=2^val, facet=paste(ACC,desc,sep = ' - ')) df <- df_reps %>% group_by(condition, rowname) %>% summarize(mean = mean(val,na.rm = TRUE), sd = sd(val, na.rm = TRUE), n = n()) %>% mutate(error = qnorm(0.975) * sd/sqrt(n), CI.L = mean - error, CI.R = mean + error) %>% as.data.frame() %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), fraction=ifelse(condition %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(condition,1,nchar(condition)-1)) %>% left_join(desc,by=c('rowname'='name')) %>% mutate(facet=paste(ACC,desc,sep = ' - ')) %>% distinct() rowname <- df$rowname[1] #levels df$genotype <- factor(df$genotype, levels = c('wt','clp1','clp2')) df$fraction <- factor(df$fraction, levels = c('membrane','soluble')) df_reps$genotype <- factor(df_reps$genotype, levels = c('wt','clp1','clp2')) df_reps$fraction <- factor(df_reps$fraction, levels = c('membrane','soluble')) facet=unique(df$facet) #order of facets ACC_order <- data.frame(ACC=toupper(c('At5g08530','At4g02580','At5g37510','At1g16700','At1g79010','At5g11770','AtMg00070','AtMg00510','AtMg00516','AtMg01120','AtMg01275','AtMg00285','AtMg01320','AtMg00990','AtMg00650', 'AtMg00580','AtMg00513','AtMg0060','AtMg00665','AtMg00270','At5g67590','At3g03070','At3g08610','At5g47890','At3g03100','At1g67785','At5g52840','At5g08060','At2g20360', 'At1g72040','At2g46540','At3g12260','At5g18800','At3g06310','At2g42210','At1g04630','At2g33220','At4g16450','At1g76200','At2g02510','At1g14450','At2g31490','At2g02050','At5g47570', 'At4g34700','At1g49140','At3g18410','At3g57785','At2g42310','At4g00585','At4g20150','At3g62790','At2g47690','At1g19580','At1g47260','At5g66510','At5g63510','At3g48680', 'At1g67350','At2g27730','At1g18320','At3g07480','At5g14105','At1g68680','At3g10110','At1g72170','At2g28430','At1g72750'))) ACC_order <- ACC_order %>% left_join(dplyr::select(df,ACC,desc)) %>% distinct(ACC,.keep_all = T) %>% mutate(facet=paste(ACC,desc,sep = ' - ')) %>% distinct(facet) df$facet <- factor(df$facet, levels=(ACC_order$facet)) df_reps$facet <- factor(df_reps$facet, levels=(ACC_order$facet)) #all single plots #ggplot(df, aes(fraction, mean/1000000, fill=genotype)) + geom_hline(yintercept = 0) + # geom_bar(stat='identity',position=position_dodge(width=1)) + #geom_errorbar(aes(ymin = CI.L/1000000, ymax = CI.R/1000000),position=position_dodge(width=1), width = 0.3,size=1.2) + #geom_jitter(data = df_reps, aes(fraction, val/1000000,group=genotype, col = replicate),alpha=0.5, # size = 1, position = position_dodge(width = 1)) + #labs(title='LFQ Raw intensities CLP',x = "", y = ("LFQ Intensity" ~ "(?95% CI) [Million Area Count]"), col = "Rep") + #facet_wrap(~facet,scales='free') + #scale_fill_manual(values=c('#339900','#0066cc','#990033'))+ #scale_y_continuous(label=unit_format(suffix=' M'))+ #theme(axis.text.x = element_text(angle=0,hjust=0.5)) #stats library(broom) all_ttest <- data.frame() for (prot in unique(df$ACC)){ for(frac in unique(df$fraction)){ stat=filter(df_reps,ACC==prot,fraction==frac) stat=tidy(pairwise.t.test(stat$val,stat$genotype,p.adjust.method = 'BH')) %>% as.data.frame() %>% mutate(fraction=frac,ACC=prot, p.value=round(p.value,digits=3)) %>% filter(group2=='wt') %>% dplyr::select(-group2) %>% dplyr::rename(genotype=group1) all_ttest=bind_rows(all_ttest,stat) } } df <- left_join(df,all_ttest) %>% mutate(p.value=ifelse(is.na(p.value),'1',p.value),sig=ifelse(p.value <= 0.05,'*','')) df$genotype <- factor(df$genotype, levels = c('wt','clp1','clp2')) df$fraction <- factor(df$fraction, levels = c('membrane','soluble')) df_reps$genotype <- factor(df_reps$genotype, levels = c('wt','clp1','clp2')) df_reps$fraction <- factor(df_reps$fraction, levels = c('membrane','soluble')) #single all plots for (chart in unique(df$facet)){ filename=gsub('/','_',chart) p <-ggplot(filter(df, facet==chart), aes(fraction, mean/1000000, fill=genotype)) + geom_hline(yintercept = 0) + geom_bar(stat='identity',position=position_dodge(width=1)) + geom_errorbar(aes(ymin = CI.L/1000000, ymax = CI.R/1000000),position=position_dodge(width=1), width = 0.3,size=1.2) + geom_jitter(data = filter(df_reps, facet==chart), aes(fraction, val/1000000,group=genotype, col = replicate),alpha=0.5, size = 3, position = position_dodge(width = 1)) + geom_text(aes(y=CI.R/1000000+CI.R/1000000*0.1,label=sig),stat='identity',position=position_dodge(width=1))+ labs(title=chart,x = "", y = ("LFQ Intensity" ~ "(?95% CI) [Million Area Count]"), col = "Rep") + scale_fill_manual(values=c('#339900','#0066cc','#990033'))+ scale_y_continuous(label=number_format(suffix=' M'))+ theme_DEP2()+ theme(axis.text.x = element_text(angle=0,hjust=0.5)) ggsave(filename = paste0(filename,'.png'),path = 'images',device = 'png',dpi=1080,plot = p) message(paste0(filename,' done!')) } ## custom mutant overlap volcano #data dep <- add_rejections(data_diff, alpha = 0.1, lfc = log2(1)) data_results <- get_results(dep) #long format(gather) data_long <- data_results %>% gather(sample,value,3:ncol(.)) %>% mutate(type=sapply(strsplit(sample,'__'),'[',3), type=ifelse(is.na(type)==T,sapply(strsplit(sample,'__'),'[',2),type), sample=sapply(strsplit(sample,'__'),'[',1), fraction=ifelse(sample %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(sample,1,nchar(sample)-1)) %>% dplyr::select(-sample) %>% rowwise() %>% filter(type != 'significant') %>% spread(key = type,value = value) %>% mutate(ID=sapply(strsplit(ID,'[.]'),'[',1)) #filter for both mutants under 0.1pvalue, and use lowest FC and highest pvalue data_volcano <- data_long %>% filter(genotype !='wt') %>% group_by(ID,fraction) %>% mutate(colour_p=ifelse(max(p.adj) <= 0.1,'red','blue')) %>% mutate(min_ratio=min(abs(ratio)), max_p=max(p.adj)) %>% filter(abs(ratio)==min_ratio) %>% dplyr::select(-min_ratio) %>% mutate(colour_r=ifelse(ratio <=-0.4 | ratio >= 0.4,'red','blue')) %>% mutate(sig=ifelse(colour_p=='blue'|colour_r=='blue','non_sig','sig')) %>% distinct(ID,fraction, .keep_all = T) #add good annotation desc_volcano <- data2 %>% dplyr::select(Gene.names,`Majority protein IDs`) %>% dplyr::rename(desc=Gene.names,ACC=`Majority protein IDs`) #hand curate some annotation desc_volcano <- desc_volcano %>% mutate(desc=ifelse(ACC=='AT5G08690','ATP synth beta2', ifelse(ACC=='AT5G62270','mucin related AT5G62270', ifelse(ACC=='AT1G26460','PPR AT1G26460', ifelse(ACC=='AT3G02650','PPR AT3G02650', ifelse(ACC=='AT5G64670','PPR AT5G64670',desc)))))) desc_volcano <- desc_volcano %>% mutate(desc=ifelse(ACC=='AT3G62530','ARM repeat', ifelse(ACC=='AT4G21020','Late embryo abundant', ifelse(ACC=='AT5G55200','CoChaperone GrpE', ifelse(ACC=='AT3G19740','p-loop hydrolase', ifelse(ACC=='AT4G36680','PPR AT4G36680', ifelse(ACC=='AT1G70190','Ribo L7/L12',desc))))))) #merge annnotation into volcano data data_volcano <- data_volcano %>% left_join(desc_volcano, by=c('ID'='ACC')) #levels data_volcano$sig <- factor(data_volcano$sig, levels=c('sig','non_sig')) ## format data for plot #change-log10 pvalue high numbers to a maximum of 7.5 #change symbol of >7.5 to op arrow data_volcano <- data_volcano %>% mutate(max_p_adj=ifelse(-log10(max_p) > 7.5,0.0000000316215,max_p), pch=ifelse(-log10(max_p) > 7.5,17,16), ratio_adj=ifelse(ratio > 3.5,3.5,ifelse(ratio < -3.5,-3.5,ratio))) library(ggrepel) p <- ggplot(data_volcano, aes(x=ratio_adj,y=-log10(max_p_adj),col=sig))+ geom_point(pch=data_volcano$pch,alpha=0.75,size=2)+ geom_text_repel(data=filter(data_volcano,sig=='sig'),aes(label=desc),col='black',size=2.5, fontface='bold')+ facet_wrap(~fraction)+ scale_colour_manual(values=c('#990000','#99ccff'))+ theme(legend.position = 'none', axis.title = element_text(face='bold',size = 18), axis.text = element_text(face='bold',size = 16), strip.text = element_text(face='bold',size=18), title = element_text(face='bold',size=18))+ labs(title='Clp vs col-O', x='log2 fold change', y='-log10 p-value') ggsave(filename = paste0('volcano','.png'),path = 'images',device = 'png',dpi=1080,plot = p) ###custom table significant genes dep <- add_rejections(data_diff, alpha = 0.1, lfc = log2(1)) data_results <- get_results(dep) data_results <- data_results[,which(str_detect(colnames(data_results),'significant')==F)] data_results <- data_results[,which(str_detect(colnames(data_results),'p.val')==F)] data_results <- data_results[,which(str_detect(colnames(data_results),'center')==F)] data_results <- data_results[,c(2,1,3,5,7,9,4,6,8,10)] write.csv(data_results,'data/results_clp.csv') #mapman annotation data_results <- data_results %>% mutate(ID=substr(ID,1,9)) mapman <- fread('data/X4_Araport11_R1.0.txt') %>% mutate_all(.,funs(gsub("'","",.))) %>% dplyr::rename(ID=IDENTIFIER) %>% mutate(ID=toupper(substr(ID,1,9))) %>% dplyr::select(-NAME) data_results <- data_results %>% left_join(mapman) ##complex I subunits cI_agi <- data_long %>% filter(ID %in% cI_anno$ACC) cI_agi <- cI_agi$ID dep <- add_rejections(data_diff, alpha = 1, lfc = log2(1)) subset <- dep[unique(filter(data_long,ID %in% cI_agi)$name)] means <- rowMeans(assay(subset), na.rm = TRUE) df_reps <- data.frame(assay(subset)) %>% rownames_to_column() %>% gather(ID, val, -rowname) %>% left_join(., data.frame(colData(subset)),by = "ID") desc <- dplyr::select(data_long,name,ID) %>% filter(ID %in% cI_agi) %>% na.omit() %>% dplyr::rename(ACC=ID) %>% distinct(ACC, .keep_all = T) df_reps <- left_join(df_reps,desc,by=c('rowname'='name')) %>% distinct() %>% na.omit df_reps$replicate <- as.factor(df_reps$replicate) df_reps <- df_reps %>% filter(ID !='clp2s__4') %>% ungroup() %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), genotype=substr(condition,1,nchar(condition)-1)) %>% group_by(genotype,ACC,replicate) %>% mutate(val=2^mean(val), facet=paste(ACC,rowname,sep = ' - ')) %>% distinct(genotype,ACC,replicate,.keep_all = T) df <- df_reps %>% group_by(condition, rowname) %>% summarize(mean = mean(val,na.rm = TRUE), sd = sd(val, na.rm = TRUE), n = n()) %>% mutate(error = qnorm(0.975) * sd/sqrt(n), CI.L = mean - error, CI.R = mean + error) %>% as.data.frame() %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), genotype=substr(condition,1,nchar(condition)-1)) %>% left_join(desc,by=c('rowname'='name')) %>% mutate(facet=paste(ACC,rowname,sep = ' - ')) %>% distinct() rowname <- df$rowname[1] #levels df$genotype <- factor(df$genotype, levels = c('wt','clp1','clp2')) df_reps$genotype <- factor(df_reps$genotype, levels = c('wt','clp1','clp2')) facet=unique(df$facet) df$facet <- factor(df$facet, levels=unique(df$facet[order(df$rowname)])) df_reps$facet <- factor(df_reps$facet, levels=unique(df_reps$facet[order(df_reps$rowname)])) #all single plots p <- ggplot(df, aes(ACC, mean/1000000, fill=genotype)) + geom_hline(yintercept = 0) + geom_bar(stat='identity',position=position_dodge(width=1)) + geom_errorbar(aes(ymin = CI.L/1000000, ymax = CI.R/1000000),position=position_dodge(width=1), width = 0.3,size=1.2) + geom_jitter(data = df_reps, aes(ACC, val/1000000,group=genotype, col = replicate),alpha=0.5, size = 1, position = position_dodge(width = 1)) + labs(title='Complex I subunits',x = "", y = ("LFQ Intensity" ~ "(?95% CI) [Million Area Count]"), col = "Rep") + facet_wrap(~rowname,scales='free') + scale_fill_manual(values=c('#339900','#0066cc','#990033'))+ #scale_y_continuous(label=unit_format(suffix=' M'))+ theme(axis.text.x = element_blank(),axis.title.y = element_text(size=16,face='bold'),axis.text.y = element_text(size=12), strip.text = element_text(size=12,face='bold'),legend.text=element_text(size=14,face='bold'),legend.key.size = unit(2,'cm')) ggsave(filename = paste0('complex I survey','.png'),path = 'images',width=16,height = 10,device = 'png',dpi=1080,plot = p) ##mitochondrial encoded data_long %>% filter(str_detect(ID,'ATM')==T) %>% View() mito_agi <- data_long%>% filter(str_detect(ID,'ATM')==T) mito_agi <- mito_agi$ID dep <- add_rejections(data_diff, alpha = 1, lfc = log2(1)) subset <- dep[unique(filter(data_long,ID %in% mito_agi)$name)] means <- rowMeans(assay(subset), na.rm = TRUE) df_reps <- data.frame(assay(subset)) %>% rownames_to_column() %>% gather(ID, val, -rowname) %>% left_join(., data.frame(colData(subset)),by = "ID") desc <- dplyr::select(data_long,name,ID) %>% filter(ID %in% mito_agi) %>% na.omit() %>% dplyr::rename(ACC=ID) %>% distinct(ACC, .keep_all = T) df_reps <- left_join(df_reps,desc,by=c('rowname'='name')) %>% distinct() df_reps$replicate <- as.factor(df_reps$replicate) df_reps <- df_reps %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), fraction=ifelse(condition %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(condition,1,nchar(condition)-1)) %>% mutate(val=2^val, facet=paste(ACC,rowname,sep = ' - ')) df <- df_reps %>% group_by(condition, rowname) %>% summarize(mean = mean(val,na.rm = TRUE), sd = sd(val, na.rm = TRUE), n = n()) %>% mutate(error = qnorm(0.975) * sd/sqrt(n), CI.L = mean - error, CI.R = mean + error) %>% as.data.frame() %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), fraction=ifelse(condition %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(condition,1,nchar(condition)-1)) %>% left_join(desc,by=c('rowname'='name')) %>% mutate(facet=paste(ACC,rowname,sep = ' - ')) %>% distinct() rowname <- df$rowname[1] #levels df$genotype <- factor(df$genotype, levels = c('wt','clp1','clp2')) df$fraction <- factor(df$fraction, levels = c('membrane','soluble')) df_reps$genotype <- factor(df_reps$genotype, levels = c('wt','clp1','clp2')) df_reps$fraction <- factor(df_reps$fraction, levels = c('membrane','soluble')) facet=unique(df$facet) df$facet <- factor(df$facet, levels=unique(df$facet[order(df$rowname)])) df_reps$facet <- factor(df_reps$facet, levels=unique(df_reps$facet[order(df_reps$rowname)])) #all single plots p <- ggplot(filter(df,fraction=='soluble'), aes(fraction, mean/1000000, fill=genotype)) + geom_hline(yintercept = 0) + geom_bar(stat='identity',position=position_dodge(width=1)) + geom_errorbar(aes(ymin = CI.L/1000000, ymax = CI.R/1000000),position=position_dodge(width=1), width = 0.3,size=1.2) + geom_jitter(data = filter(df_reps,fraction=='soluble'), aes(fraction, val/1000000,group=genotype, col = replicate),alpha=0.5, size = 1, position = position_dodge(width = 1)) + labs(title='Mitochondrial encoded Proteins',x = "", y = ("LFQ Intensity" ~ "(?95% CI) [Million Area Count]"), col = "Rep") + facet_wrap(~rowname,scales='free') + scale_fill_manual(values=c('#339900','#0066cc','#990033'))+ #scale_y_continuous(label=unit_format(suffix=' M'))+ theme(axis.text.x = element_blank(),axis.title.y = element_text(size=16,face='bold'),axis.text.y = element_text(size=12), strip.text = element_text(size=12,face='bold'),legend.text=element_text(size=14,face='bold'),legend.key.size = unit(2,'cm')) ggsave(filename = paste0('mito encoded survey','.png'),path = 'images',width=16,height = 10,device = 'png',dpi=1080,plot = p) ##protease AGI protease_agi <- fread('data/protease_agi.csv') %>% mutate(Gene=toupper(substr(Gene,1,9))) dep <- add_rejections(data_diff, alpha = 1, lfc = log2(1)) subset <- dep[unique(filter(data_long,ID %in% protease_agi$Gene)$name)] means <- rowMeans(assay(subset), na.rm = TRUE) df_reps <- data.frame(assay(subset)) %>% rownames_to_column() %>% gather(ID, val, -rowname) %>% left_join(., data.frame(colData(subset)),by = "ID") desc <- dplyr::select(data_long,name,ID) %>% left_join(protease_agi, by=c('ID'='Gene')) %>% na.omit() %>% dplyr::rename(ACC=ID) %>% distinct(ACC, .keep_all = T) df_reps <- left_join(df_reps,desc,by=c('rowname'='name')) %>% distinct() df_reps$replicate <- as.factor(df_reps$replicate) df_reps <- df_reps %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), fraction=ifelse(condition %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(condition,1,nchar(condition)-1)) %>% mutate(val=2^val, facet=paste(ACC,Name,sep = ' - ')) df <- df_reps %>% group_by(condition, rowname) %>% summarize(mean = mean(val,na.rm = TRUE), sd = sd(val, na.rm = TRUE), n = n()) %>% mutate(error = qnorm(0.975) * sd/sqrt(n), CI.L = mean - error, CI.R = mean + error) %>% as.data.frame() %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), fraction=ifelse(condition %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(condition,1,nchar(condition)-1)) %>% left_join(desc,by=c('rowname'='name')) %>% mutate(facet=paste(ACC,Name,sep = ' - ')) %>% distinct() rowname <- df$rowname[1] #levels df$genotype <- factor(df$genotype, levels = c('wt','clp1','clp2')) df$fraction <- factor(df$fraction, levels = c('membrane','soluble')) df_reps$genotype <- factor(df_reps$genotype, levels = c('wt','clp1','clp2')) df_reps$fraction <- factor(df_reps$fraction, levels = c('membrane','soluble')) facet=unique(df$facet) df$facet <- factor(df$facet, levels=unique(df$facet[order(df$Name)])) df_reps$facet <- factor(df_reps$facet, levels=unique(df_reps$facet[order(df_reps$Name)])) #all single plots p <- ggplot(filter(df,fraction=='soluble'), aes(fraction, mean/1000000, fill=genotype)) + geom_hline(yintercept = 0) + geom_bar(stat='identity',position=position_dodge(width=1)) + geom_errorbar(aes(ymin = CI.L/1000000, ymax = CI.R/1000000),position=position_dodge(width=1), width = 0.3,size=1.2) + geom_jitter(data = filter(df_reps,fraction=='soluble'), aes(fraction, val/1000000,group=genotype, col = replicate),alpha=0.5, size = 1, position = position_dodge(width = 1)) + labs(title='LFQ Raw intensities CLP',x = "", y = ("LFQ Intensity" ~ "(?95% CI) [Million Area Count]"), col = "Rep") + facet_wrap(~facet,scales='free') + scale_fill_manual(values=c('#339900','#0066cc','#990033'))+ #scale_y_continuous(label=scales::number_format(suffix=' M'))+ theme(axis.text.x = element_blank(),axis.title.y = element_text(size=16,face='bold'),axis.text.y = element_text(size=12), strip.text = element_text(size=12,face='bold'),legend.text=element_text(size=14,face='bold'),legend.key.size = unit(2,'cm')) ggsave(filename = paste0('protease survey','.png'),path = 'images',width=16,height = 10,device = 'png',dpi=1080,plot = p) #stats library(broom) all_ttest <- data.frame() for (prot in unique(df$ACC)){ for(frac in unique(df$fraction)){ stat=filter(df_reps,ACC==prot,fraction==frac) stat=tidy(pairwise.t.test(stat$val,stat$genotype,p.adjust.method = 'BH')) %>% as.data.frame() %>% mutate(fraction=frac,ACC=prot, p.value=round(p.value,digits=3)) %>% filter(group2=='wt') %>% dplyr::select(-group2) %>% dplyr::rename(genotype=group1) all_ttest=bind_rows(all_ttest,stat) } } df <- left_join(df,all_ttest) %>% mutate(p.value=ifelse(is.na(p.value),'1',p.value),sig=ifelse(p.value <= 0.05,'*','')) df$genotype <- factor(df$genotype, levels = c('wt','clp1','clp2')) df$fraction <- factor(df$fraction, levels = c('membrane','soluble')) df_reps$genotype <- factor(df_reps$genotype, levels = c('wt','clp1','clp2')) df_reps$fraction <- factor(df_reps$fraction, levels = c('membrane','soluble')) #single all plots for (chart in unique(df$facet)){ filename=gsub('/','_',chart) p <-ggplot(filter(df, facet==chart), aes(fraction, mean/1000000, fill=genotype)) + geom_hline(yintercept = 0) + geom_bar(stat='identity',position=position_dodge(width=1)) + geom_errorbar(aes(ymin = CI.L/1000000, ymax = CI.R/1000000),position=position_dodge(width=1), width = 0.3,size=1.2) + geom_jitter(data = filter(df_reps, facet==chart), aes(fraction, val/1000000,group=genotype, col = replicate),alpha=0.5, size = 3, position = position_dodge(width = 1)) + geom_text(aes(y=CI.R/1000000+CI.R/1000000*0.1,label=sig),stat='identity',position=position_dodge(width=1))+ labs(title=chart,x = "", y = ("LFQ Intensity" ~ "(?95% CI) [Million Area Count]"), col = "Rep") + scale_fill_manual(values=c('#339900','#0066cc','#990033'))+ scale_y_continuous(label=number_format(suffix=' M'))+ theme_DEP2()+ theme(axis.text.x = element_text(angle=0,hjust=0.5)) ggsave(filename = paste0(filename,'.png'),path = 'images',device = 'png',dpi=1080,plot = p) message(paste0(filename,' done!')) } ##predicted targets predicted_agi <- fread('data/mito_clp_targets.tsv') %>% mutate(Gene=toupper(substr(AGI,1,9))) dep <- add_rejections(data_diff, alpha = 1, lfc = log2(1)) subset <- dep[unique(filter(data_long,ID %in% predicted_agi$Gene)$name)] means <- rowMeans(assay(subset), na.rm = TRUE) df_reps <- data.frame(assay(subset)) %>% rownames_to_column() %>% gather(ID, val, -rowname) %>% left_join(., data.frame(colData(subset)),by = "ID") desc <- dplyr::select(data_long,name,ID) %>% left_join(predicted_agi, by=c('ID'='Gene')) %>% na.omit() %>% dplyr::rename(ACC=ID) %>% distinct(ACC, .keep_all = T) df_reps <- left_join(df_reps,desc,by=c('rowname'='name')) %>% distinct() df_reps$replicate <- as.factor(df_reps$replicate) df_reps <- df_reps %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), fraction=ifelse(condition %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(condition,1,nchar(condition)-1)) %>% mutate(val=2^val, facet=paste(ACC,rowname,sep = ' - ')) df <- df_reps %>% group_by(condition, rowname) %>% summarize(mean = mean(val,na.rm = TRUE), sd = sd(val, na.rm = TRUE), n = n()) %>% mutate(error = qnorm(0.975) * sd/sqrt(n), CI.L = mean - error, CI.R = mean + error) %>% as.data.frame() %>% mutate(condition=sapply(strsplit(condition,'_'),'[',1), fraction=ifelse(condition %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(condition,1,nchar(condition)-1)) %>% left_join(desc,by=c('rowname'='name')) %>% mutate(facet=paste(ACC,rowname,sep = ' - ')) %>% distinct() rowname <- df$rowname[1] #levels df$genotype <- factor(df$genotype, levels = c('wt','clp1','clp2')) df$fraction <- factor(df$fraction, levels = c('membrane','soluble')) df_reps$genotype <- factor(df_reps$genotype, levels = c('wt','clp1','clp2')) df_reps$fraction <- factor(df_reps$fraction, levels = c('membrane','soluble')) facet=unique(df$facet) df$facet <- factor(df$facet, levels=unique(df$facet[order(df$Name)])) df_reps$facet <- factor(df_reps$facet, levels=unique(df_reps$facet[order(df_reps$Name)])) #all single plots p <- ggplot(filter(df,fraction=='soluble'), aes(fraction, mean/1000000, fill=genotype)) + geom_hline(yintercept = 0) + geom_bar(stat='identity',position=position_dodge(width=1)) + geom_errorbar(aes(ymin = CI.L/1000000, ymax = CI.R/1000000),position=position_dodge(width=1), width = 0.3,size=1.2) + geom_jitter(data = filter(df_reps,fraction=='soluble'), aes(fraction, val/1000000,group=genotype, col = replicate),alpha=0.5, size = 1, position = position_dodge(width = 1)) + labs(title='LFQ Raw intensities CLP',x = "", y = ("LFQ Intensity" ~ "(?95% CI) [Million Area Count]"), col = "Rep") + facet_wrap(~rowname,scales='free') + scale_fill_manual(values=c('#339900','#0066cc','#990033'))+ #scale_y_continuous(label=scales::number_format(suffix=' M'))+ theme(axis.text.x = element_blank(),axis.title.y = element_text(size=16,face='bold'),axis.text.y = element_text(size=12), strip.text = element_text(size=10),legend.text=element_text(size=14,face='bold'),legend.key.size = unit(2,'cm')) ggsave(filename = paste0('predicted survey','.png'),path = 'images/predicted',width=16,height = 10,device = 'png',dpi=1080,plot = p) df <- na.omit(df) #stats library(broom) all_ttest <- data.frame() for (prot in unique(df$ACC)){ for(frac in unique(df$fraction)){ stat=filter(df_reps,ACC==prot,fraction==frac) stat=tidy(pairwise.t.test(stat$val,stat$genotype,p.adjust.method = 'BH')) %>% as.data.frame() %>% mutate(fraction=frac,ACC=prot, p.value=round(p.value,digits=3)) %>% filter(group2=='wt') %>% dplyr::select(-group2) %>% dplyr::rename(genotype=group1) all_ttest=bind_rows(all_ttest,stat) } } df <- left_join(df,all_ttest) %>% mutate(p.value=ifelse(is.na(p.value),'1',p.value),sig=ifelse(p.value <= 0.05,'*','')) df$genotype <- factor(df$genotype, levels = c('wt','clp1','clp2')) df$fraction <- factor(df$fraction, levels = c('membrane','soluble')) df_reps$genotype <- factor(df_reps$genotype, levels = c('wt','clp1','clp2')) df_reps$fraction <- factor(df_reps$fraction, levels = c('membrane','soluble')) #single all plots for (chart in unique(df$facet)){ filename=gsub('/','_',chart) filename=gsub('%','_',filename) p <-ggplot(filter(df, facet==chart), aes(fraction, mean/1000000, fill=genotype)) + geom_hline(yintercept = 0) + geom_bar(stat='identity',position=position_dodge(width=1)) + geom_errorbar(aes(ymin = CI.L/1000000, ymax = CI.R/1000000),position=position_dodge(width=1), width = 0.3,size=1.2) + geom_jitter(data = filter(df_reps, facet==chart), aes(fraction, val/1000000,group=genotype, col = replicate),alpha=0.5, size = 3, position = position_dodge(width = 1)) + geom_text(aes(y=CI.R/1000000+CI.R/1000000*0.1,label=sig),stat='identity',position=position_dodge(width=1))+ labs(title=chart,x = "", y = ("LFQ Intensity" ~ "(?95% CI) [Million Area Count]"), col = "Rep") + scale_fill_manual(values=c('#339900','#0066cc','#990033'))+ scale_y_continuous(label=number_format(suffix=' M'))+ theme_DEP2()+ theme(axis.text.x = element_text(angle=0,hjust=0.5)) ggsave(filename = paste0(filename,'.png'),path = 'images/predicted',device = 'png',dpi=1080,plot = p) message(paste0(filename,' done!')) } ## plot CI kd kd <- fread('data/TPC2016-00768-LSBR1_Supplemental_Data_Set_2b.csv', skip = 1) kd <- kd[,c(2,3,4,144:147)] kd <- kd %>% dplyr::rename(AGI=`1st AGI`) %>% mutate(AGI=toupper(substr(AGI,1,9))) #filter for dep proteins kd <- kd %>% filter(AGI %in% df$AGI) #intersect in Complex I kd <- kd %>% left_join(cI_anno, by=c('AGI'='ACC')) %>% na.omit() #levels levels <- arrange(kd,`Average KD (d-1)`) %>% distinct(Name) kd$Name <- factor(kd$Name, levels=levels$Name) ggplot(kd, aes(Name,`Average KD (d-1)`))+ geom_bar(stat='identity',fill='darkgreen')+ coord_flip()+ theme(axis.title.y = element_blank())+ labs(title = 'Complex I kd - Lei') #intersect in predicted targets kd <- fread('data/TPC2016-00768-LSBR1_Supplemental_Data_Set_2b.csv', skip = 1) kd <- kd[,c(2,3,4,144:147)] kd <- kd %>% dplyr::rename(AGI=`1st AGI`) %>% mutate(AGI=toupper(substr(AGI,1,9))) #intersect with predicted AGi kd <- kd %>% left_join(predicted_agi, by=c('AGI'='Gene')) %>% na.omit() #filter for dep proteins kd <- kd %>% filter(AGI %in% df$AGI) #better name kd <- kd %>% mutate(desc=sapply(strsplit(description,': '),'[',2)) %>% mutate(desc=sapply(strsplit(desc,','),'[',1)) %>% mutate(desc=substr(desc,1,20)) %>% mutate(desc=sapply(strsplit(desc,' '),'[',1)) #custom fix some names kd <- kd %>% mutate(desc=ifelse(AGI=='AT2G20420','ATP citrate lyase', ifelse(AGI=='AT1G54220','Dihydrolipoamide acetyltransferase', ifelse(AGI=='AT3G55410','2-oxoglutarate dehydrogenase', ifelse(AGI=='AT4G02580','24 kDa subunit', ifelse(AGI=='AT5G20080','FAD/NAD(P)-binding oxidoreductase', ifelse(AGI=='AT1G24360','NAD(P)-binding', ifelse(AGI=='AT5G08670','ATP synthase alpha/beta family protein', ifelse(AGI=='AT4G02930','GTP binding Elongation factor Tu',desc))))))))) #levels levels <- arrange(kd,`Average KD (d-1)`) %>% distinct(desc) kd$desc <- factor(kd$desc, levels=levels$desc) ggplot(kd, aes(desc,`Average KD (d-1)`))+ geom_bar(stat='identity',fill='darkgreen')+ coord_flip()+ theme(axis.title.y = element_blank())+ labs(title = 'predicted targets kd - Lei') ## plot CI kd from Lon1 paper lei ## mitochondria solution kd <- fread('data/lei_degradation_rate_lon_mito.csv',skip=2) %>% as.tibble() %>% separate_rows(AGI, convert=T) %>% mutate(AGI=substr(AGI,1,9)) %>% distinct(AGI, .keep_all = T) #filter for dep proteins kd <- kd %>% filter(AGI %in% data_long$ID) #intersect in Complex I kd <- kd %>% left_join(cI_anno, by=c('AGI'='ACC')) %>% na.omit() #levels levels <- arrange(kd,`WT KD (Average)`) %>% distinct(Name) kd$Name <- factor(kd$Name, levels=levels$Name) ggplot(kd, aes(Name,`WT KD (Average)`))+ geom_bar(stat='identity',fill='darkgreen')+ coord_flip()+ theme(axis.title.y = element_blank())+ labs(title = 'Complex I kd - Lei - lon paper') ## plot CI kd from Lon1 paper lei ## mitochondria BN fractions #load data, convert to long format kd <- fread('data/lei_lon1_bn_deg_rates.csv',header = F) %>% as.tibble() colnames(kd) <- paste(kd[1,],gsub(' ','_',kd[2,]),sep='-') for (n in which(duplicated(colnames(kd))==T)){ colnames(kd)[n]=paste('wt',colnames(kd)[n],sep='%') } kd <- kd[3:nrow(kd),] colnames(kd)[1:5] <- gsub('-','',colnames(kd)[1:5]) kd <- kd %>% separate_rows(AGI, convert=T) %>% mutate(AGI=substr(AGI,1,9)) %>% distinct(AGI, .keep_all = T) kd <- kd %>% gather(sample,value,6:ncol(.)) #filter for average and wild type & split sample column into meta data kd <- kd %>% filter(str_detect(sample,regex('wt', ignore_case = T)) & str_detect(sample,regex('average', ignore_case = T))) %>% mutate(fraction=sapply(strsplit(sample,'_'),'[',2), mem_sol=sapply(strsplit(sapply(strsplit(sample,'-'),'[',2),'_'),'[',1)) #replace empty values with 0 (not found) kd <- kd %>% mutate(value=as.numeric(value), value=ifelse(is.na(value),0,value)) #filter for dep proteins kd <- kd %>% filter(AGI %in% data_long$ID) #intersect in Complex I kd <- kd %>% left_join(cI_anno, by=c('AGI'='ACC')) %>% na.omit() ##adjust soluble and insoluble fraction positions kd <- kd %>% mutate(fraction=as.numeric(gsub('F','',fraction)), fraction=ifelse(mem_sol=='Soluble',fraction+3,fraction), fraction=paste0('F',fraction)) #levels kd <- kd %>% group_by(fraction,mem_sol,Name) %>% mutate(max=max(value)) %>% ungroup() levels <- arrange(kd,mem_sol,max) %>% distinct(Name) kd$Name <- factor(kd$Name, levels=levels$Name) kd$fraction <- factor(kd$fraction, levels=rev(c('F1','F2','F3','F4','F5','F6','F7','F8', 'F9','F10','F11','F12','F13','F14','F15'))) kd <- kd %>% mutate(value=ifelse(value < 0, value==0.01,value)) #ccombined kd #library(RColorBrewer) p=ggplot(kd, aes(fraction,value,fill=mem_sol))+ geom_bar(stat='identity',alpha=0.5)+ coord_flip()+ facet_wrap(~Name,scales='free_y')+ theme(axis.title.y = element_blank(),axis.text.y = element_text(size=8,face = 'bold'))+ labs(title = 'Complex I kd - Lei - lon paper - bn gel')+ theme(legend.position = c(0.5,0.1),axis.title.x = element_blank())+ ylim(0,0.4)+ scale_fill_brewer(palette = 'Dark2') ggsave(filename = paste0('Complex I kd - Lei - lon paper - bn gel','.svg'),path = 'images/kd',device = 'svg',dpi=1080,plot = p) #add protein abundance quant <- fread('data/lei_abundance_lon_mito.csv') colnames(quant) <- c(as.character(quant[2,1:3]),paste(quant[1,4:ncol(quant)],quant[2,4:ncol(quant)],sep='-')) quant <- quant[3:nrow(quant),] quant <- quant %>% as_tibble(.name_repair = 'universal') %>% filter(Identified.Pep.NO..p.0.95.=='WT') %>% dplyr::select(-2) %>% gather(sample,count,3:ncol(.)) #fix AGI quant <- quant %>% separate_rows(Protein,convert = T) %>% mutate(Protein=substr(Protein,1,9)) %>% distinct(Protein,sample, .keep_all = T) #match Kd frame for left join quant <- quant %>% mutate(fraction=sapply(strsplit(sample, '[.]'),'[',2), mem_sol=ifelse(str_detect(sample,'Insoluble')==T,'Insoluble','Soluble'), fraction=as.numeric(gsub('F','',fraction)), fraction=ifelse(mem_sol=='Soluble',fraction+3,fraction), fraction=paste0('F',fraction)) quant <- quant %>% dplyr::rename(AGI=Protein) %>% dplyr::select(-2,-3) #join kd <- kd %>% left_join(quant) #ccombined quant #library(RColorBrewer) #heaps of eleves (taken from kd) kd <- kd %>% group_by(fraction,mem_sol,Name) %>% mutate(max=max(value)) %>% ungroup() levels <- arrange(kd,mem_sol,max) %>% distinct(Name) kd$Name <- factor(kd$Name, levels=levels$Name) kd$fraction <- factor(kd$fraction, levels=rev(c('F1','F2','F3','F4','F5','F6','F7','F8', 'F9','F10','F11','F12','F13','F14','F15'))) kd <- kd %>% mutate(value=ifelse(value < 0, value==0.01,value)) p=ggplot(kd, aes(fraction,as.numeric(count),fill=mem_sol))+ geom_bar(stat='identity',alpha=0.5)+ coord_flip()+ facet_wrap(~Name,scales='free')+ theme(axis.title.y = element_blank(),axis.text.y = element_text(size=8,face = 'bold'))+ labs(title = 'Complex I count - Lei - lon paper - bn gel')+ theme(legend.position = c(0.5,0.1),axis.title.x = element_blank())+ #ylim(0,0.4)+ scale_fill_brewer(palette = 'Dark2') ggsave(filename = paste0('Complex I kd - Lei - lon paper - bn gel','.svg'),path = 'images/kd',device = 'svg',dpi=1080,plot = p) ################ Figure 1c clp paper ######################################### ##data prep # # Generate a results table # # no pvalue cutoff # dep <- add_rejections(data_diff, alpha = 1, lfc = log2(1)) # # data_results <- get_results(dep) # data_results <- data_results[,which(str_detect(colnames(data_results),'significant')==F)] data_results <- fread('data/fig3a_data.csv') #long format(gather) data_long <- data_results %>% gather(sample,value,3:ncol(.)) %>% mutate(type=sapply(strsplit(sample,'__'),'[',3), type=ifelse(is.na(type)==T,sapply(strsplit(sample,'__'),'[',2),type), sample=sapply(strsplit(sample,'__'),'[',1), fraction=ifelse(sample %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(sample,1,nchar(sample)-1)) %>% dplyr::select(-sample) %>% rowwise() %>% spread(key = type,value = value) %>% mutate(ID=sapply(strsplit(ID,'[.]'),'[',1)) %>% filter(str_detect(genotype,'signif')==F) #Gene selection #clpp clpp <- 'AT5G23140' #most stabel house keeper overall #https://link.springer.com/article/10.1007/s13562-017-0403-0 Lon1 <- 'AT5G26860' #mito housekeeper vdac1 E1alpha <- 'AT1G59900' #selction sel <- c(clpp,Lon1,E1alpha) sel <- dplyr::filter(data_long,ID %in% sel) %>% distinct(name) #Plot counts #custom selection, Plotcounts() doesn't work on multiple Genes subset <- assay(dep[sel$name]) %>% as.data.frame() %>% rownames_to_column(var='gene') %>% as_tibble() %>% gather(sample,count,2:24) %>% mutate(genotype=ifelse(str_detect(sample,'clp1'),'clp1', ifelse(str_detect(sample,'clp2'),'clp2','WT')), fraction=ifelse(str_detect(sample,'p__')==T,'membrane','soluble'), desc=ifelse(gene=='CLPP2','CLPP2', ifelse(gene=='LON1','LON1', ifelse(gene=='E1 ALPHA','PDC E1 \U221D','failsave'))), raw_count=2^count) #little stars for pvalues :) res <- data_long %>% dplyr::filter(name %in% sel$name, fraction == 'soluble') %>% dplyr::select(name,fraction,genotype,p.adj) %>% mutate(p.adj=ifelse(genotype=='wt',1,p.adj), sig_level=ifelse(p.adj > 0.05,'', ifelse(p.adj <= 0.05 & p.adj > 0.005,'*', ifelse(p.adj <= 0.005,'*\n*','failsave'))), genotype=ifelse(genotype=='wt','WT',genotype), name=ifelse(name=='E1 ALPHA','PDC E1 \U221D',name)) %>% dplyr::rename(desc=name) #add median as ref y axis point y_ref <- subset %>% group_by(genotype,desc) %>% summarise(median=median(raw_count/1000000),max=max(raw_count/1000000)) res <- res %>% left_join(y_ref) #levels subset$genotype <- factor(subset$genotype, levels = c('WT','clp1','clp2')) subset$desc <- factor(subset$desc, levels = c('CLPP2','LON1','PDC E1 \U221D')) res$genotype <- factor(res$genotype, levels = c('WT','clp1','clp2')) res$desc <- factor(res$desc, levels = c('CLPP2','LON1','PDC E1 \U221D')) #plot g <- ggplot(dplyr::filter(subset,fraction=='soluble'), aes(genotype, raw_count/1000000, bg=genotype)) + facet_wrap(~desc,scales = 'free_y')+ stat_summary(fun.y = median, fun.ymin = median, fun.ymax = median, geom = "crossbar",col='black', size = 0.3)+ stat_summary(fun.y = median, fun.ymin = median, fun.ymax = median, geom = "bar",col='black', size = 0.15,alpha= 0.6)+ geom_point(pch = 21,size=2,color='black',alpha=0.5)+ geom_text(data=res,aes(genotype,c(0.65,0.6,rep(1,7)),label=sig_level),size=6, lineheight = 0.25)+ expand_limits(y=0)+ scale_colour_manual(values=c('#339900','#3399cc','#3366cc'))+ scale_fill_manual(values=c('#339900','#3399cc','#3366cc'))+ labs(title='Mitochondrial protein abundance',y='LFQ intensity [M]')+ theme(axis.title.x = element_blank(),legend.position = 'none', axis.text.x = element_text(face=c('plain','italic','italic'),size=8, angle = 30), axis.title.y = element_text(face='bold',size='8'), axis.text.y = element_text(face='bold',size=8), strip.text = element_text(face='bold',size=8), title=element_text(size=10)) #save ggsave('Prot_KO_figure1.pdf',device = 'pdf',dpi=1080,plot = g,height = 6.52,width = 6,units = 'cm') ################ Figure 3a clp paper ######################################### library(data.table) library(tidyverse) ## custom mutant overlap volcano # #only run if pre existing data is not good # #data changed to p=0.05 # dep <- add_rejections(data_diff, alpha = 0.05, lfc = log2(1)) # data_results <- get_results(dep) # data_results %>% filter(significant) %>% nrow() #write table s dep seems to perform differently every time #write_csv(data_results,'data/fig3a_data.csv') #read data rom premade DEP data_results <- fread('data/fig3a_data.csv') #long format(gather) data_long <- data_results %>% gather(sample,value,3:ncol(.)) %>% mutate(type=sapply(strsplit(sample,'__'),'[',3), type=ifelse(is.na(type)==T,sapply(strsplit(sample,'__'),'[',2),type), sample=sapply(strsplit(sample,'__'),'[',1), fraction=ifelse(sample %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(sample,1,nchar(sample)-1)) %>% dplyr::select(-sample) %>% rowwise() %>% filter(type != 'significant') %>% spread(key = type,value = value) %>% mutate(ID=sapply(strsplit(ID,'[.]'),'[',1)) #filter for both mutants under 0.1pvalue, and use lowest FC and highest pvalue data_volcano <- data_long %>% filter(genotype !='wt') %>% group_by(ID,fraction) %>% mutate(colour_p=ifelse(max(p.adj) <= 0.05,'red','blue')) %>% mutate(min_ratio=min(abs(ratio)), max_p=max(p.adj)) %>% filter(abs(ratio)==min_ratio) %>% dplyr::select(-min_ratio) %>% mutate(colour_r=ifelse(ratio <=-0.4 | ratio >= 0.4,'red','blue')) %>% mutate(sig=ifelse(colour_p=='blue'|colour_r=='blue','non_sig','sig')) %>% distinct(ID,fraction, .keep_all = T) # #add good annotation # desc_volcano <- data2 %>% # dplyr::select(Gene.names,`Majority protein IDs`) %>% # dplyr::rename(desc=Gene.names,ACC=`Majority protein IDs`) # #hand curate some annotation # # desc_volcano <- desc_volcano %>% # mutate(desc=ifelse(ACC=='AT5G08690','ATP synth beta2', # ifelse(ACC=='AT5G62270','mucin related AT5G62270', # ifelse(ACC=='AT1G26460','PPR AT1G26460', # ifelse(ACC=='AT3G02650','PPR AT3G02650', # ifelse(ACC=='AT5G64670','PPR AT5G64670',desc)))))) # # desc_volcano <- desc_volcano %>% # mutate(desc=ifelse(ACC=='AT3G62530','ARM repeat', # ifelse(ACC=='AT4G21020','Late embryo abundant', # ifelse(ACC=='AT5G55200','CoChaperone GrpE', # ifelse(ACC=='AT3G19740','p-loop hydrolase', # ifelse(ACC=='AT4G36680','PPR AT4G36680', # ifelse(ACC=='AT1G70190','Ribo L7/L12',desc))))))) # # #write table, hand curate and reimport # #filter desk for significant proteins # #sig_ids <- filter(data_volcano, sig=='sig') %>% ungroup() %>% distinct(ID) # # #write_csv(filter(desc_volcano, ACC %in% sig_ids$ID),'data/desc_volcano3.csv') desc_volcano <- read_csv('data/desc_volcano3.csv') #merge annnotation into volcano data data_volcano <- data_volcano %>% left_join(desc_volcano, by=c('ID'='ACC')) %>% mutate(desc=ifelse(is.na(desc)==T | sig=='non_sig','',desc), group=ifelse(is.na(group)==T | sig=='non_sig','',group)) #levels data_volcano$sig <- factor(data_volcano$sig, levels=c('sig','non_sig')) ## format data for plot #change-log10 pvalue high numbers to a maximum of 7.5 #change symbol of >7.5 to op arrow data_volcano <- data_volcano %>% mutate(max_p_adj=ifelse(-log10(max_p) > 6,1e-6,max_p), pch=ifelse(-log10(max_p) > 6,24,21), ratio_adj=ifelse(ratio > 3.5,3.5,ifelse(ratio < -3.5,-3.5,ratio))) #scale colour based on group data_volcano <- data_volcano %>% mutate(group=ifelse(sig=='non_sig','non_sig',group), alpha=ifelse(group=='non_sig',0.4,0.75)) data_volcano$group <- factor(data_volcano$group , levels=c('non_sig', 'Energy Metabolism', 'Mitochondrial Protein Synthesis', 'Chaperone / Protease', 'Knock Out', 'Ungrouped')) #rename facets data_volcano <-data_volcano %>% ungroup() %>% mutate(fraction=ifelse(fraction=='membrane','Membrane fraction','Soluble fraction')) library(ggrepel) p <- ggplot(data_volcano, aes(x=ratio_adj,y=-log10(max_p_adj),fill=group))+ geom_point(pch=data_volcano$pch,alpha=data_volcano$alpha,size=3)+ geom_text_repel(data=filter(data_volcano,sig=='sig'),aes(label=table_nr),col='black',size=2.5, fontface='bold')+ geom_hline(yintercept = -log10(0.05),size=0.3, alpha=0.5,linetype="dashed",color='#0033ff')+ geom_vline(xintercept = c(-0.4,0.4),size=0.3, alpha=0.5,linetype="dashed",color='#0033ff')+ geom_text(aes(x=3.5,y=-log10(0.05)-0.1,label='P = 0.05'), size = 2.5, colour='#003366')+ geom_text(aes(x=-0.4-0.5,y=5.5,label='Log2FC \u2264 -0.4'), size = 2.5, colour='#003366')+ geom_text(aes(x=0.4+0.5,y=5.5,label='Log2FC \u2265 -0.4'), size = 2.5, colour='#003366')+ facet_wrap(~fraction)+ scale_fill_manual(values=c('#006699','#FF3300','#cc9966','#006600','#660000','#9933ff'))+ theme(legend.position = 'none', axis.title = element_text(face='bold',size = 18), axis.text = element_text(face='bold',size = 16), strip.text = element_text(face='bold',size=18), title = element_text(face='bold',size=18))+ labs(title='', x='log2FC clp1/clp2 VS WT', y=expression(paste("-Lo", g[10]," P",sep=""))) p #save ggsave('Prot_volcano_figure3a.pdf',device = 'pdf',dpi=2160,plot = p,height = 8,width = 13,units = 'in') ################ Figure 3b clp paper (table) ################################## #start with desc volcano fig3b <- desc_volcano %>% left_join(dplyr::select(data_long,2,3,4,6,8), by=c('ACC'='ID')) %>% distinct() %>% dplyr::filter(genotype !='wt') %>% dplyr::rename(AGI=ACC) fig3b <- fig3b[,c(5,4,1,2,3,6,7,8)] fig3b <- fig3b %>% mutate(p_r=paste(p.adj,ratio,sep = '_')) %>% dplyr::select(-p.adj,-ratio) %>% spread(genotype,p_r) %>% mutate(`clp1 ratio`=round(as.numeric(sapply(strsplit(clp1,'_'),'[',2)),digits=2), `clp2 ratio`=round(as.numeric(sapply(strsplit(clp2,'_'),'[',2)),digits=2), `clp1 p.adj`=round(as.numeric(sapply(strsplit(clp1,'_'),'[',1)),digits=2), `clp2 p.adj`=round(as.numeric(sapply(strsplit(clp2,'_'),'[',1)),digits=2)) %>% dplyr::select(-clp1,-clp2) write.csv(fig3b,'data/fig3b.csv') ################ Figure 5a clp paper ######################################### ##data prep # Generate a results table # no pvalue cutoff data_results <- fread('data/fig3a_data.csv') #long format(gather) data_long <- data_results %>% gather(sample,value,3:ncol(.)) %>% mutate(type=sapply(strsplit(sample,'__'),'[',3), type=ifelse(is.na(type)==T,sapply(strsplit(sample,'__'),'[',2),type), sample=sapply(strsplit(sample,'__'),'[',1), fraction=ifelse(sample %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(sample,1,nchar(sample)-1)) %>% dplyr::select(-sample) %>% rowwise() %>% spread(key = type,value = value) %>% mutate(ID=sapply(strsplit(ID,'[.]'),'[',1), name=gsub('Â','',name)) %>% dplyr::filter(str_detect(genotype,'signif')==F) #Gene selection #B8 B8 <- 'AT5G47890' #B14 B14 <- 'AT3G12260' #24KDa kd24 <- 'AT4G02580' #51KDa kd51 <- 'AT5G08530' #75KDa kd75 <- 'AT5G37510' #selction sel <- c(B8,B14,kd24,kd51,kd75) sel <- dplyr::filter(data_long,ID %in% sel) %>% distinct(name) sel$name <- c('B8','B14',rownames(dep)[c(47,58,61)]) #Plot counts #custom selection, Plotcounts() doesn't work on multiple Genes subset <- assay(dep[sel$name]) %>% as.data.frame() %>% rownames_to_column(var='gene') %>% as_tibble() %>% gather(sample,count,2:24) %>% mutate(genotype=ifelse(str_detect(sample,'clp1'),'clp1', ifelse(str_detect(sample,'clp2'),'clp2','WT')), desc=gene, fraction=ifelse(str_detect(sample,'p__')==T,'membrane','soluble'), raw_count=2^count) #stats library(broom) all_ttest <- data.frame() for (prot in unique(subset$gene)){ stat=filter(subset,gene==prot) stat=tidy(pairwise.t.test(stat$raw_count,stat$genotype,p.adjust.method = 'BH')) %>% as.data.frame() %>% mutate(p.value=round(p.value,digits=3), gene=prot) %>% filter(group1=='WT') %>% dplyr::select(-group1) %>% dplyr::rename(genotype=group2) all_ttest=bind_rows(all_ttest,stat) } subset <- left_join(subset,all_ttest) %>% mutate(p.value=ifelse(is.na(p.value),'1',p.value), sig=ifelse(p.value > 0.05,'', ifelse(p.value <= 0.05 & p.value > 0.001,'*', ifelse(p.value <= 0.001,'*\n*','failsave')))) #stat_data stat_data <- subset %>% distinct(gene,genotype,p.value,.keep_all = T) subset$genotype <- factor(subset$genotype, levels = c('WT','clp1','clp2')) subset$desc <- factor(subset$desc, levels = c('B8','B14',unique(subset$gene)[3:5])) stat_data$genotype <- factor(stat_data$genotype, levels = c('WT','clp1','clp2')) stat_data$desc <- factor(stat_data$desc, levels = c('B8','B14',unique(stat_data$desc)[3:5])) stat_data$gene <- factor(stat_data$gene, levels = c('B8','B14',unique(stat_data$gene)[3:5])) #plot g <- ggplot(dplyr::filter(subset), aes(genotype, raw_count/1000000, bg=genotype)) + facet_wrap(~desc,scales = 'free_y',nrow = 1)+ stat_summary(fun.y = median, fun.ymin = median, fun.ymax = median, geom = "bar",col='black', size = 0.15,alpha= 0.6,,width=0.8)+ stat_summary(fun.y = median, fun.ymin = median, fun.ymax = median, geom = "crossbar",col='black', size = 0.3,width=0.8)+ geom_jitter(pch = 21,size=1,color='black',alpha=0.2,width=0.15)+ geom_text(data=stat_data,aes(genotype,c(1.6,6.5,8.5,21.5,28.5,1.7,8,9.5,23,28,1,1,1,1,1),label=sig),size=6, lineheight = 0.25)+ expand_limits(y=0)+ scale_colour_manual(values=c('#339900','#3399cc','#3366cc'))+ scale_fill_manual(values=c('#339900','#3399cc','#3366cc'))+ labs(title='Complex I protein abundance',y='LFQ intensity [M]')+ theme(axis.title.x = element_blank(),legend.position = 'none', axis.text.x = element_text(face=c('plain','italic','italic'),size=8, angle = 90), axis.title.y = element_text(face='bold',size='8'), axis.text.y = element_text(face='bold',size=8), strip.text = element_text(face='bold',size=8), title=element_text(size=10)) g #save ggsave('Prot_CIabundacne_overall_figure4a.pdf',device = 'pdf',dpi=1080,plot = g,height = 6,width = 8,units = 'cm') #overlap shotguna nd chafradic data_results <- data_results %>% mutate(gene=substr(ID,1,9)) chafradic <- fread('data/n_terms.csv') combine <- left_join(chafradic,data_results, by='gene') %>% na.omit() write.csv(combine,'data/combined_shotgun_chafradic.csv') ################ Figure 5 clp paper ######################################### #combine prot volcano data with RNA seq library(data.table) library(tidyverse) ## custom mutant overlap volcano # #only run if pre existing data is not good # #data changed to p=0.05 # dep <- add_rejections(data_diff, alpha = 0.05, lfc = log2(1)) # data_results <- get_results(dep) # data_results %>% filter(significant) %>% nrow() #write table s dep seems to perform differently every time #write_csv(data_results,'data/fig3a_data.csv') #read data rom premade DEP data_results <- fread('data/fig3a_data.csv') #long format(gather) data_long <- data_results %>% gather(sample,value,3:ncol(.)) %>% mutate(type=sapply(strsplit(sample,'__'),'[',3), type=ifelse(is.na(type)==T,sapply(strsplit(sample,'__'),'[',2),type), sample=sapply(strsplit(sample,'__'),'[',1), fraction=ifelse(sample %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(sample,1,nchar(sample)-1)) %>% dplyr::select(-sample) %>% rowwise() %>% dplyr::filter(type != 'significant') %>% spread(key = type,value = value) %>% mutate(ID=sapply(strsplit(ID,'[.]'),'[',1)) #filter for both mutants under 0.1pvalue, and use lowest FC and highest pvalue data_volcano <- data_long %>% dplyr::filter(genotype !='wt') %>% group_by(ID,fraction) %>% mutate(colour_p=ifelse(max(p.adj) <= 0.05,'red','blue')) %>% mutate(min_ratio=min(abs(ratio)), max_p=max(p.adj)) %>% dplyr::filter(abs(ratio)==min_ratio) %>% dplyr::select(-min_ratio) %>% mutate(colour_r=ifelse(ratio <=-0.4 | ratio >= 0.4,'red','blue')) %>% mutate(sig=ifelse(colour_p=='blue'|colour_r=='blue','non_sig','sig')) %>% distinct(ID,fraction, .keep_all = T) # #add good annotation # desc_volcano <- data2 %>% # dplyr::select(Gene.names,`Majority protein IDs`) %>% # dplyr::rename(desc=Gene.names,ACC=`Majority protein IDs`) # #hand curate some annotation # # desc_volcano <- desc_volcano %>% # mutate(desc=ifelse(ACC=='AT5G08690','ATP synth beta2', # ifelse(ACC=='AT5G62270','mucin related AT5G62270', # ifelse(ACC=='AT1G26460','PPR AT1G26460', # ifelse(ACC=='AT3G02650','PPR AT3G02650', # ifelse(ACC=='AT5G64670','PPR AT5G64670',desc)))))) # # desc_volcano <- desc_volcano %>% # mutate(desc=ifelse(ACC=='AT3G62530','ARM repeat', # ifelse(ACC=='AT4G21020','Late embryo abundant', # ifelse(ACC=='AT5G55200','CoChaperone GrpE', # ifelse(ACC=='AT3G19740','p-loop hydrolase', # ifelse(ACC=='AT4G36680','PPR AT4G36680', # ifelse(ACC=='AT1G70190','Ribo L7/L12',desc))))))) # # #write table, hand curate and reimport # #filter desk for significant proteins # #sig_ids <- filter(data_volcano, sig=='sig') %>% ungroup() %>% distinct(ID) # # #write_csv(filter(desc_volcano, ACC %in% sig_ids$ID),'data/desc_volcano3.csv') desc_volcano <- read_csv('data/desc_volcano3.csv') #merge annnotation into volcano data data_volcano <- data_volcano %>% left_join(desc_volcano, by=c('ID'='ACC')) %>% mutate(desc=ifelse(is.na(desc)==T | sig=='non_sig','',desc), group=ifelse(is.na(group)==T | sig=='non_sig','',group)) #levels data_volcano$sig <- factor(data_volcano$sig, levels=c('sig','non_sig')) ## format data for plot #change-log10 pvalue high numbers to a maximum of 7.5 #change symbol of >7.5 to op arrow data_volcano <- data_volcano %>% mutate(max_p_adj=ifelse(-log10(max_p) > 6,1e-6,max_p), pch=ifelse(-log10(max_p) > 6,24,21), ratio_adj=ifelse(ratio > 3.5,3.5,ifelse(ratio < -3.5,-3.5,ratio))) #scale colour based on group data_volcano <- data_volcano %>% mutate(group=ifelse(sig=='non_sig','non_sig',group), alpha=ifelse(group=='non_sig',0.4,0.75)) data_volcano$group <- factor(data_volcano$group , levels=c('non_sig', 'Energy Metabolism', 'Mitochondrial Protein Synthesis', 'Chaperone / Protease', 'Knock Out', 'Ungrouped')) #rename facets data_volcano <-data_volcano %>% ungroup() %>% mutate(fraction=ifelse(fraction=='membrane','Membrane fraction','Soluble fraction')) data_volcano_prot <- data_volcano data_volcano_rna <- fread('data/data_voclano_rnaseq.csv') %>% dplyr::select(rowname,ratio_adj) combined <- data_volcano_prot %>% left_join(data_volcano_rna,by=c('ID'='rowname')) #shrink ratio.y combined <- combined %>% mutate(ratio_adj.y=ifelse(ratio_adj.y >= 1,1, ifelse(ratio_adj.y <= -1,-1,ratio_adj.y))) g <- ggplot(dplyr::filter(combined,sig=='sig'|abs(ratio_adj.x) >= 1 & max_p_adj <= 0.05|abs(ratio_adj.y) >= 0.5 ),aes(ratio_adj.x,ratio_adj.y))+ geom_point()+ geom_text_repel(data=dplyr::filter(combined,sig=='sig'|abs(ratio_adj.x) >= 1 & max_p_adj <= 0.05|abs(ratio_adj.y) >= 0.5 ),aes(label=name),col='black',size=2.5, fontface='bold') ggsave('rna_prot_combine.pdf',device = 'pdf',dpi=1080,plot = g,height = 15,width = 15,units = 'cm') ################ Figure mito encodes expression sublemental clp paper ######################################### ######################################################################################################### ##data prep # # Generate a results table # # no pvalue cutoff # dep <- add_rejections(data_diff, alpha = 1, lfc = log2(1)) # # data_results <- get_results(dep) # data_results <- data_results[,which(str_detect(colnames(data_results),'significant')==F)] data_results <- fread('data/fig3a_data.csv') #long format(gather) data_long <- data_results %>% gather(sample,value,3:ncol(.)) %>% mutate(type=sapply(strsplit(sample,'__'),'[',3), type=ifelse(is.na(type)==T,sapply(strsplit(sample,'__'),'[',2),type), sample=sapply(strsplit(sample,'__'),'[',1), fraction=ifelse(sample %in% c("clp1p","clp2p", "wtp"),'membrane','soluble'), genotype=substr(sample,1,nchar(sample)-1)) %>% dplyr::select(-sample) %>% rowwise() %>% spread(key = type,value = value) %>% mutate(ID=sapply(strsplit(ID,'[.]'),'[',1)) %>% dplyr::filter(str_detect(genotype,'signif')==F) #Gene selection #everything ATM #selction sel <- dplyr::filter(data_long,str_detect(ID,'ATM')==T) %>% distinct(name) #Plot counts #custom selection, Plotcounts() doesn't work on multiple Genes subset <- assay(dep[sel$name]) %>% as.data.frame() %>% rownames_to_column(var='gene') %>% as_tibble() %>% gather(sample,count,2:24) %>% mutate(genotype=ifelse(str_detect(sample,'clp1'),'clp1', ifelse(str_detect(sample,'clp2'),'clp2','WT')), fraction=ifelse(str_detect(sample,'p__')==T,'membrane','soluble'), desc=ifelse(gene=='CLPP2','CLPP2', ifelse(gene=='LON1','LON1', ifelse(gene=='E1 ALPHA','PDC E1 \U221D','failsave'))), raw_count=2^count) #little stars for pvalues :) res <- data_long %>% dplyr::filter(name %in% sel$name, fraction == 'soluble') %>% dplyr::select(name,fraction,genotype,p.adj) %>% mutate(p.adj=ifelse(genotype=='wt',1,p.adj), sig_level=ifelse(p.adj > 0.05,'', ifelse(p.adj <= 0.05 & p.adj > 0.005,'*', ifelse(p.adj <= 0.005,'*\n*','failsave'))), genotype=ifelse(genotype=='wt','WT',genotype), name=ifelse(name=='E1 ALPHA','PDC E1 \U221D',name)) %>% dplyr::rename(desc=name) #add median as ref y axis point y_ref <- subset %>% group_by(genotype,desc) %>% summarise(median=median(raw_count/1000000),max=max(raw_count/1000000)) res <- res %>% left_join(y_ref) #levels subset$genotype <- factor(subset$genotype, levels = c('WT','clp1','clp2')) subset$desc <- factor(subset$desc, levels = c('CLPP2','LON1','PDC E1 \U221D')) res$genotype <- factor(res$genotype, levels = c('WT','clp1','clp2')) res$desc <- factor(res$desc, levels = c('CLPP2','LON1','PDC E1 \U221D')) #plot g <- ggplot(dplyr::filter(subset,fraction=='soluble'), aes(genotype, raw_count/1000000, bg=genotype)) + facet_wrap(~desc,scales = 'free_y')+ stat_summary(fun.y = median, fun.ymin = median, fun.ymax = median, geom = "crossbar",col='black', size = 0.3)+ stat_summary(fun.y = median, fun.ymin = median, fun.ymax = median, geom = "bar",col='black', size = 0.15,alpha= 0.6)+ geom_point(pch = 21,size=2,color='black',alpha=0.5)+ geom_text(data=res,aes(genotype,c(0.65,0.6,rep(1,7)),label=sig_level),size=6, lineheight = 0.25)+ expand_limits(y=0)+ scale_colour_manual(values=c('#339900','#3399cc','#3366cc'))+ scale_fill_manual(values=c('#339900','#3399cc','#3366cc'))+ labs(title='Mitochondrial protein abundance',y='LFQ intensity [M]')+ theme(axis.title.x = element_blank(),legend.position = 'none', axis.text.x = element_text(face=c('plain','italic','italic'),size=8, angle = 30), axis.title.y = element_text(face='bold',size='8'), axis.text.y = element_text(face='bold',size=8), strip.text = element_text(face='bold',size=8), title=element_text(size=10)) #save ggsave('Prot_KO_figure1.pdf',device = 'pdf',dpi=1080,plot = g,height = 6.52,width = 6,units = 'cm')
09b2997b4f59a682b6880c1571c2e289055fe3d0
3cdfdd9a76285fe3604e10e8936011cf0ef00d2b
/research/LDA.R
44b1fb3d875585d73ed53ebae5eb6f2ad746ad61
[]
no_license
nichi97/research
40acd333141c09b719073cc3eb4287faf27a08e7
e92a7a616153fdabc4ee10ec4e2f44791e68e3a5
refs/heads/master
2020-05-07T05:51:06.876840
2019-05-17T17:05:14
2019-05-17T17:05:14
180,289,348
0
0
null
null
null
null
UTF-8
R
false
false
1,295
r
LDA.R
library(tidyverse) library(readtext) library(quanteda) library(topicmodels) # read in the data textlist <- readtext(file = "./New_York_Times_Data") # deal with one sample document first sample <- corpus(textlist[1,2]) # separate each txt file into individual documents sep_doc <- corpus_segment(sample, "____________________________________________________________") # Create document feature matrix doc_features <- dfm(sep_doc, remove=stopwords("english"), stem = T, remove_punct = T) # run LDA to discover the possible topics dtm <- convert(doc_features, to = "topicmodels") lda <- LDA(dtm, k=10) lda_terms <- terms(lda, 10) lda_topics <- topics(lda) # See what is in the data kwic(sep_doc, pattern = "China") library(stringi) library(LDAvis) phi <- posterior(lda)$terms theta <- posterior(lda)$topics vocab <- colnames(phi) doc_length <- ntoken(doc_features) freq_matrix <- data.frame(ST = colnames(dtm), Freq = colSums(as.matrix(dtm))) json_lda <- LDAvis::createJSON(phi = phi, theta = theta, vocab = vocab, doc.length = doc_length, term.frequency = freq_matrix$Freq) serVis(json_lda)
c1dac5ac86569fc1bc7a09ed14957f784f99609d
d75b0a81b020d8397bd6e18e6906b53a7678f873
/man/create_edges.Rd
bb0adb201da83b48754c09cb99babc731dfa5b08
[]
no_license
alishinski/lavaanPlot
eef00b29d2c820b88ce5750e94b6952ef1f779a1
2292161266eb64cf261417124471f3f84f2ce77c
refs/heads/master
2023-02-22T05:48:19.507495
2023-02-17T17:25:09
2023-02-17T17:25:09
93,868,858
38
3
null
2022-04-02T20:41:32
2017-06-09T14:49:28
R
UTF-8
R
false
true
1,239
rd
create_edges.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/lavaanPlot2.R \name{create_edges} \alias{create_edges} \title{Creates edge data frame and adds formatting} \usage{ create_edges( coefs, ndf, edge_options, coef_labels = FALSE, stand = FALSE, stars = NULL, sig = 1 ) } \arguments{ \item{coefs}{a coefficient table from lavaan model created by \code{extract_coefs}} \item{ndf}{A node data frame created by \code{create_nodes}} \item{edge_options}{a named list of graphviz edge attributes, or a data frame of edge options created by \code{formatting}, or a list of such data frames containing 1 set of edge options and one set of custom options} \item{coef_labels}{whether to label edges with coefficient values} \item{stand}{Should the coefficients being used be standardized coefficients} \item{stars}{a character vector indicating which parameters should include significance stars be included for regression paths, latent paths, or covariances. Include which of the 3 you want ("regress", "latent", "covs"), default is none.} \item{sig}{significance level for determining what significant paths are} } \value{ an edge data frame } \description{ Creates edge data frame and adds formatting }
156bae31352a921f989f14319909db1fe6a450fe
9a982397c4b440bfed7f8cc4e4eb87ea6038c57a
/server.R
05f902c587f5821ec8d04fabed4a425a319cd1d5
[]
no_license
kahyeenlai/CorrSave_G3_Bad_Genius
5f5110be8c1dabf28383fe524f05dbbdb5f552c4
66f1015746141b57532d40962b4970b87ea6ceaa
refs/heads/master
2021-09-27T06:38:24.036119
2021-09-10T01:53:45
2021-09-10T01:53:45
188,664,082
0
0
null
null
null
null
UTF-8
R
false
false
28,596
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(keras) library(imager) library(shinyjs) library(ggplot2) library(DT) library(imager) library(dplyr) library(readr) library(EBImage) library(scales) library(glcm) library(wvtool) library(pROC) library(caret) getFeatures <- function (images, im_x = 28, im_y = 28) { # resize image to im_x and im_y dimension images <- lapply(images, imager:::resize, size_x = im_x, size_y = im_y, interpolation_type = 2 ) # initialize features vector features = c(); for (i in 1:length(images)){ # get colour features all channel from every images for (j in 1:3) { channel <- images[[i]][,,,j] m = dim(channel)[1] n = dim(channel)[2] # mean = (sum(channel))/(m*n) mean = mean(channel) # sd = ((sum((channel-mean)**2)/(m*n))**(1/2)) sd = sd(channel) # skewness =((sum((channel-mean)**3)/(m*n))**(1/3)) # https://alstatr.blogspot.com/2013/06/measures-of-skewness-and-kurtosis.html library(moments) f_channel = channel dim(f_channel) = c(m*n, 1) sk = skewness(f_channel) features <- append(features, c (mean,sd,sk)) } # convert to grayscale and take only the 1st two matrix temp = grayscale(images[[i]])[,,1,1] # package used to calculate the texture features # https://cran.r-project.org/web/packages/RTextureMetrics/RTextureMetrics.pdf library(RTextureMetrics) mask <- array(TRUE, dim=dim(temp)) glcms <- EBImage:::.haralickMatrix(mask, temp, nc=255) mat <- EBImage:::.haralickFeatures(mask, temp, nc=255) # entropy = calcENT(glcms[,,1]) # contrast = calcCON(glcms[,,1]) homogeneity = calcHOM(glcms[,,1]) energy = sum(glcms[,,1]^2) features <- append(features, c(mat[,"h.ent"],energy,mat[,"h.con"],homogeneity)) } dim(features) = c(13, length(images)) row.names(features) <- c("r_mean", "r_sd", "r_skewness", "g_mean", "g_sd", "g_skewness", "b_mean", "b_sd", "b_skewness", "entrophy", "energy", "contrast", "homogeneity") colnames(features) < as.character(c(1:length(images))) return (features) } # source("texture features.R") # Define server logic required to draw a histogram shinyServer(function(input, output, session) { opt <- list( lengthChange = TRUE , autoWidth = TRUE, scrollX=TRUE ) use_session_with_seed(1,disable_parallel_cpu = FALSE) variable <- reactiveValues( node = 0, layer = 0, batch_size = 0, epoch = 0, dropout = 0, train_ratio = 0, model = keras_model_sequential(), img_list_c = c(), img_list_nc = c(), img_list = c(), feature_mat = c(), feature_mat_flag = FALSE, label = c(), fit = "", plot_flag = FALSE, k = "", cv_fit = list(), cv_roc_obj = list(), cv_pred_class = list(), cv_pred_prob = list(), cv_roc_plot = list(), cv_flag = FALSE, confusion_matrix_flag = FALSE, performance_report = "", roc_obj = "", img_single = "", scale_attr = c(), image_url_flag = FALSE, image_url = "", img_list_t = "" ) observeEvent(input$fileIn, { inFiles <- input$fileIn variable$img_list_c <- lapply(inFiles$datapath, load.image) variable$img_list_c <- lapply(variable$img_list_c, rm.alpha) }) observeEvent(input$fileIn2, { inFiles <- input$fileIn2 variable$img_list_nc <- lapply(inFiles$datapath, load.image) variable$img_list_nc <- lapply(variable$img_list_nc, rm.alpha) }) observeEvent(input$save_param, { variable$node <- as.integer(input$node) variable$layer <- as.integer(input$layer) variable$batch_size <- as.integer(input$batch_size) variable$epoch <- as.integer(input$epoch) variable$dropout <- as.double(input$dropout) variable$train_ratio <- as.integer(input$train_ratio) variable$model = keras_model_sequential() variable$model %>% layer_dense(input_shape = 13, units = variable$node, activation = "relu") %>% layer_dropout(variable$dropout) for (i in 1:(variable$layer)){ variable$model %>% layer_dense(units = variable$node, activation = "relu") %>% layer_dropout(variable$dropout) } variable$model %>% # output layer layer_dense(units = 1, activation = "sigmoid") # add a loss function and optimizer variable$model %>% compile( loss = "binary_crossentropy", optimizer = "Adam", metrics = "accuracy" ) output$value <- renderPrint({ variable$model }) }) observeEvent(input$calculate_Features, { variable$img_list = c(variable$img_list_c, variable$img_list_nc) # 0 = corroded images # 1 = non-corroded images variable$label = c(rep(0, length(variable$img_list_c)), rep(1, length(variable$img_list_nc))) # implement own function to get image features variable$feature_mat <- "" variable$feature_mat <-getFeatures(variable$img_list) variable$feature_mat <- as.data.frame(variable$feature_mat) variable$feature_mat <- rbind(variable$feature_mat, as.integer(variable$label)) variable$feature_mat <- t.data.frame(variable$feature_mat) rownames(variable$feature_mat) <- c(1:dim(variable$feature_mat)[1]) colnames(variable$feature_mat)[14] <- "label" variable$feature_mat_flag = TRUE }) observeEvent(input$start_training, { set.seed(1) rate <- round(variable$train_ratio/100, digits = 2) n <- nrow(variable$feature_mat) shuffled_df <- variable$feature_mat[sample(n), ] train_indices <- 1:round(rate * n) train <- shuffled_df[train_indices, ] test_indices <- (round(rate * n) + 1):n test <- shuffled_df[test_indices, ] perceptron = variable$node dropout = variable$dropout batch_size = round((variable$batch_size/100) * dim(train)[1]) epoch = variable$epoch test_x <- test[,1:13] test_y <- test[,"label"] # test_x = as.matrix(apply(test_x, 2, function(test_x) (test_x-min(test_x))/(max(test_x) - min(test_x)))) y = train[,"label"] names(y) <- NULL x = train[,1:13] # scale to [0,1] # x = as.matrix(apply(x, 2, function(x) (x-min(x))/(max(x) - min(x)))) maxs <- apply(x, 2, max) mins <- apply(x, 2, min) variable$scale_attr = rbind(mins, maxs) write.csv(variable$scale_attr, file="www/Scale Attribute.csv", row.names = FALSE) variable$scale_attr <- read.csv("www/Scale Attribute.csv") x_train_scaled = scale(x, center = mins, scale = maxs - mins) test_x_scaled = scale(test_x, center = as.numeric(mins), scale = as.numeric(maxs - mins)) progress <- Progress$new(session, min=1, max=10) on.exit(progress$close()) progress$set(message = 'Training in progress', detail = 'This may take a while...', value = 5) # fit model with our training data set, training will be done for 200 times data set fit = variable$model %>% fit( x = x_train_scaled, y = y, shuffle = T, batch_size = batch_size, validation_split = 0.3, epochs = epoch, view_metrics = TRUE, callbacks = callback_csv_logger("www/log.csv", separator = ",", append = FALSE) ) variable$fit <- fit variable$plot_flag <- TRUE # Save the model to be used later name = paste("www/model", Sys.time()) name = gsub(":", ".", name) save_model_hdf5(variable$model, name, overwrite = TRUE, include_optimizer = TRUE) model2 = load_model_hdf5(name, custom_objects = NULL, compile = TRUE) variable$performance_report <- c() pred_class <- predict_classes(object = variable$model, x = as.matrix(test_x_scaled)) %>% as.vector() # Predicted class probability pred_prob <- predict_proba(object = variable$model, x = as.matrix(test_x_scaled)) %>% as.vector() # show confusion matrix # require(caret) # cm <- confusionMatrix(data = as.factor(as.vector(test_y)), as.factor(pred_class), mode = "everything") # plot ROC and calculate AUC par(mfrow = c(1, 1), mar = c(0.1, 0.1, 0.1, 0.1)) variable$roc_obj = roc(as.numeric(test_y), as.numeric(predict_proba(variable$model, test_x_scaled))) # plot.roc(roc_obj) # auc(roc_obj) variable$performance_report <- rbind(test_y,pred_class, pred_prob) variable$confusion_matrix_flag <- TRUE progress$set(message = 'Completed!', detail = 'Test the model with images.', value = 10) }) output$ui.trainPerformance <- renderUI({ if(variable$fit != ""){ tagList( h2("Model Performance for Training and Validation Process"), plotlyOutput('acc_plot'), br(), plotlyOutput('loss_plot'), br(), h3("Validation on Test data"), verbatimTextOutput("perfMetric"), br(), h3("ROC Graph"), plotOutput("rocPlot") ) } }) output$rocPlot <- renderPlot({ if (variable$confusion_matrix_flag == TRUE){ plot.roc(variable$roc_obj, print.auc=TRUE) } else { return () } }) output$perfMetric = renderPrint({ if (variable$confusion_matrix_flag == TRUE){ row.names(variable$performance_report) <- c("Actual Class", "Predicted Class", "Predicted Probability") variable$performance_report } }) output$acc_plot <- renderPlotly({ if(variable$plot_flag == TRUE){ ti = 1:length(variable$fit$metrics$val_loss) mva = lm(variable$fit$metrics$val_acc~ti+I(ti^2)+I(ti^3)) ma = lm(variable$fit$metrics$acc~ti+I(ti^2)+I(ti^3)) line.fmt = list(dash="solid", width = 1.5, color=NULL) plot_ly(data = as.data.frame(variable$fit$metrics), x = 1:length(variable$fit$metrics$val_loss)) %>% add_trace(y = variable$fit$metrics$acc, name = 'Accuracy', mode = 'lines+markers') %>% add_trace(y = variable$fit$metrics$val_acc, name = 'Validation Accuracy', mode = 'lines+markers') %>% add_lines(y = predict(ma), line=line.fmt, name="Accuracy Trend Line") %>% add_lines(y = predict(mva), line=line.fmt, name="Validation Accuracy Trend Line") %>% layout(title = "Accuracy for Train and Validation") } else{ return () } }) output$loss_plot <- renderPlotly({ if(variable$plot_flag == TRUE){ ti = 1:length(variable$fit$metrics$val_loss) mvl = lm(variable$fit$metrics$val_loss~ti+I(ti^2)+I(ti^3)) ml = lm(variable$fit$metrics$loss~ti+I(ti^2)+I(ti^3)) line.fmt = list(dash="solid", width = 1.5, color=NULL) plot_ly(data = as.data.frame(variable$fit$metrics), x = 1:length(variable$fit$metrics$val_loss)) %>% add_trace(y = variable$fit$metrics$loss, name = 'Loss', mode = 'lines+markers')%>% add_trace(y = variable$fit$metrics$val_loss, name = 'Validation Loss', mode = 'lines+markers')%>% add_lines(y = predict(ml), line=line.fmt, name="Loss Trend Line") %>% add_lines(y = predict(mvl), line=line.fmt, name="Validation Loss Trend Line") %>% layout(title = "Losses for Train and Validation") } else{ return () } }) observeEvent(input$loadModel, { inFile <- input$loadModel if (is.null(inFile)) return(NULL) variable$model <- keras_model_sequential() variable$model <- load_model_hdf5(inFile$datapath, custom_objects = NULL, compile = TRUE) output$value <- renderPrint({ variable$model }) }) observeEvent(input$loadScaleAttr, { inFile <- input$loadScaleAttr if (is.null(inFile)) return(NULL) variable$scale_attr <- read.csv(inFile$datapath) }) observeEvent(input$loadImage, { inFile <- input$loadImage if (is.null(inFile)) return(NULL) variable$img_single <- load.image(inFile$datapath) output$imgDetail <- renderPrint({ variable$img_single }) }) observeEvent(input$test_single_image, { img = rm.alpha(variable$img_single) im_x = 28 im_y = 28 # resize image to im_x and im_y dimension r_img = imager:::resize(img, size_x = im_x, size_y = im_y, interpolation_type = 2) # initialize features vector features = c(); # get colour features all channel from every images for (j in 1:3) { channel <- r_img[,,,j] m = dim(channel)[1] n = dim(channel)[2] # mean = (sum(channel))/(m*n) mean = mean(channel) # sd = ((sum((channel-mean)**2)/(m*n))**(1/2)) sd = sd(channel) # skewness =((sum((channel-mean)**3)/(m*n))**(1/3)) # https://alstatr.blogspot.com/2013/06/measures-of-skewness-and-kurtosis.html library(moments) f_channel = channel dim(f_channel) = c(m*n, 1) sk = skewness(f_channel) features <- append(features, c (mean,sd,sk)) } # convert to grayscale and take only the 1st two matrix temp = grayscale(r_img)[,,1,1] # package used to calculate the texture features # https://cran.r-project.org/web/packages/RTextureMetrics/RTextureMetrics.pdf library(RTextureMetrics) mask <- array(TRUE, dim=dim(temp)) glcms <- EBImage:::.haralickMatrix(mask, temp, nc=255) mat <- EBImage:::.haralickFeatures(mask, temp, nc=255) # entropy = calcENT(glcms[,,1]) # contrast = calcCON(glcms[,,1]) homogeneity = calcHOM(glcms[,,1]) energy = sum(glcms[,,1]^2) features <- append(features, c(mat[,"h.ent"],energy,mat[,"h.con"],homogeneity)) dim(features) = c(13, 1) row.names(features) <- c("r_mean", "r_sd", "r_skewness", "g_mean", "g_sd", "g_skewness", "b_mean", "b_sd", "b_skewness", "entrophy", "energy", "contrast", "homogeneity") feature_mat_v <- as.data.frame(features) feature_mat_v <- t.data.frame(feature_mat_v) ### ================= Evaluation =================== n <- nrow(feature_mat_v) test_x_v <- feature_mat_v maxs <- variable$scale_attr[2,] mins <- variable$scale_attr[1,] # test_x_v = as.matrix((test_x_v-min(test_x_v))/(max(test_x_v) - min(test_x_v))) test_x_v_scaled = scale(test_x_v, center = as.numeric(mins), scale = as.numeric(maxs - mins)) rownames(test_x_v_scaled) <- c(1:n) pred_class <- predict_classes(object = variable$model, x = as.matrix(test_x_v_scaled)) %>% as.vector() # Predicted class probability pred_prob <- predict_proba(object = variable$model, x = as.matrix(test_x_v_scaled)) %>% as.vector() output$predResult1 <- renderPrint({ pred_class }) output$predResult2 <- renderPrint({ pred_prob }) }) observeEvent(input$imageIn, { inFiles <- input$imageIn image_name <- input$imageIn$name img_list <- lapply(inFiles$datapath, load.image) img_list <- lapply(img_list, rm.alpha) variable$img_list_t <- cbind(image_name, img_list) }) observeEvent(input$test_multi_image, { # implement own function to get image features feature_mat <-getFeatures(variable$img_list_t[,2]) feature_mat <- as.data.frame(feature_mat) feature_mat <- t.data.frame(feature_mat) rownames(feature_mat) <- c(1:dim(feature_mat)[1]) test_x_t <- feature_mat maxs <- variable$scale_attr[2,] mins <- variable$scale_attr[1,] # test_x_v = as.matrix((test_x_v-min(test_x_v))/(max(test_x_v) - min(test_x_v))) test_x_t_scaled = scale(test_x_t, center = as.numeric(mins), scale = as.numeric(maxs - mins)) pred_class <- predict_classes(object = variable$model, x = as.matrix(test_x_t_scaled)) %>% as.vector() # Predicted class probability pred_prob <- predict_proba(object = variable$model, x = as.matrix(test_x_t_scaled)) %>% as.vector() res_output <- rbind(variable$img_list_t[,1], pred_class, pred_prob) res_output <- as.data.frame(t(res_output)) output$predResult1 <- renderPrint({ res_output }) output$predResult2 <- renderPrint({ }) }) observeEvent(input$load_imageFromUrl, { if (input$imageURL != ""){ download.file(input$imageURL,'www/temp.jpg', mode = 'wb') variable$image_url_flag <- TRUE } else { variable$image_url_flag <- FALSE } }) output$ui.imageFromUrl <- renderUI({ # check whether the dataset is loaded in the application if(variable$image_url_flag == TRUE) { # return radio button UI htmlOutput('image') } else { return () } }) output$image = renderUI({ tags$div( tags$br(), tags$img(src = input$imageURL, width = "100%") ) }) observeEvent(input$test_single_image_from_url, { variable$img_single <- load.image("www/temp.jpg") img = rm.alpha(variable$img_single) im_x = 28 im_y = 28 # resize image to im_x and im_y dimension r_img = imager:::resize(img, size_x = im_x, size_y = im_y, interpolation_type = 2) # initialize features vector features = c(); # get colour features all channel from every images for (j in 1:3) { channel <- r_img[,,,j] m = dim(channel)[1] n = dim(channel)[2] # mean = (sum(channel))/(m*n) mean = mean(channel) # sd = ((sum((channel-mean)**2)/(m*n))**(1/2)) sd = sd(channel) # skewness =((sum((channel-mean)**3)/(m*n))**(1/3)) # https://alstatr.blogspot.com/2013/06/measures-of-skewness-and-kurtosis.html library(moments) f_channel = channel dim(f_channel) = c(m*n, 1) sk = skewness(f_channel) features <- append(features, c (mean,sd,sk)) } # convert to grayscale and take only the 1st two matrix temp = grayscale(r_img)[,,1,1] # package used to calculate the texture features # https://cran.r-project.org/web/packages/RTextureMetrics/RTextureMetrics.pdf library(RTextureMetrics) mask <- array(TRUE, dim=dim(temp)) glcms <- EBImage:::.haralickMatrix(mask, temp, nc=255) mat <- EBImage:::.haralickFeatures(mask, temp, nc=255) # entropy = calcENT(glcms[,,1]) # contrast = calcCON(glcms[,,1]) homogeneity = calcHOM(glcms[,,1]) energy = sum(glcms[,,1]^2) features <- append(features, c(mat[,"h.ent"],energy,mat[,"h.con"],homogeneity)) dim(features) = c(13, 1) row.names(features) <- c("r_mean", "r_sd", "r_skewness", "g_mean", "g_sd", "g_skewness", "b_mean", "b_sd", "b_skewness", "entrophy", "energy", "contrast", "homogeneity") feature_mat_v <- as.data.frame(features) feature_mat_v <- t.data.frame(feature_mat_v) ### ================= Evaluation =================== n <- nrow(feature_mat_v) test_x_v <- feature_mat_v maxs <- variable$scale_attr[2,] mins <- variable$scale_attr[1,] # test_x_v = as.matrix((test_x_v-min(test_x_v))/(max(test_x_v) - min(test_x_v))) test_x_v_scaled = scale(test_x_v, center = as.numeric(mins), scale = as.numeric(maxs - mins)) rownames(test_x_v_scaled) <- c(1:n) pred_class <- predict_classes(object = variable$model, x = as.matrix(test_x_v_scaled)) %>% as.vector() # Predicted class probability pred_prob <- predict_proba(object = variable$model, x = as.matrix(test_x_v_scaled)) %>% as.vector() output$predResult1 <- renderPrint({ pred_class }) output$predResult2 <- renderPrint({ pred_prob }) }) output$summTable <- DT::renderDataTable({ if (variable$feature_mat_flag == TRUE){ name <- c(input$fileIn$name, input$fileIn2$name) path <- c(input$fileIn$datapath, input$fileIn2$datapath) img_path <- c() for (i in 1:length(variable$img_list)){ save.image(variable$img_list[i][[1]], file = paste("www/temp/img",i,".png", sep = "")) img_path <- append(img_path,paste("<img src='",paste("temp/img",i,".png'", sep = "")," height=52></img>", sep='')) } dt <- cbind(name, img_path, variable$feature_mat) datatable(dt, escape = FALSE, option = opt) } }) observeEvent(input$start_CV, { variable$k <- input$k feature_mat2 <- as.data.frame(variable$feature_mat) dropout = variable$dropout folds <- createFolds(y = variable$feature_mat[,"label"], k = variable$k, list = F) feature_mat2$folds <- folds idx <- 1 variable$cv_flag <- FALSE for(f in unique(feature_mat2$folds)){ cat("\n Fold: ", f) ind <- which(feature_mat2$folds == f) train_df <- feature_mat2[-ind,1:13] y_train <- as.matrix(feature_mat2[-ind, "label"]) valid_df <- as.matrix(feature_mat2[ind,1:13]) y_valid <- as.matrix(feature_mat2[ind, "label"]) maxs <- apply(train_df, 2, max) mins <- apply(train_df, 2, min) scale_attr = rbind(mins, maxs) train_df = scale(train_df, center = mins, scale = maxs - mins) valid_df = scale(valid_df, center = mins, scale = maxs - mins) # create sequential model model = keras_model_sequential() # add layers, first layer needs input dimension model %>% # 1- 10th layer layer_dense(input_shape = ncol(train_df), units = variable$node, activation = "relu") %>% layer_dropout(dropout) for (j in 1:variable$layer){ model %>% # 1- 10th layer layer_dense(units = variable$node, activation = "relu") %>% layer_dropout(dropout) } model %>% # output layer layer_dense(units = 1, activation = "sigmoid") # add a loss function and optimizer model %>% compile( loss = "binary_crossentropy", optimizer = "Adam", metrics = "accuracy" ) fit <- model %>% fit( x = as.matrix(train_df), y = y_train, shuffle = T, batch_size = floor(dim(train_df)[1]*variable$batch_size/100), epochs = variable$epoch, validation_split = 0.2 ) l = list("val_loss" = fit$metrics$val_loss, "val_acc" = fit$metrics$val_acc, "loss" = fit$metrics$loss, "acc" = fit$metrics$acc) variable$cv_fit[[idx]] <- l # Predicted class variable$cv_pred_class[[idx]] <- predict_classes(object = model, x = as.matrix(valid_df[,1:13])) %>% as.vector() # Predicted class probability variable$cv_pred_prob[[idx]] <- predict_proba(object = model, x = as.matrix(valid_df[,1:13])) %>% as.vector() print(variable$cv_pred_class[[idx]]) print(variable$cv_pred_prob[[idx]]) print(evaluate(object = model, x = valid_df[,1:13], y = y_valid)) # plot ROC and calculate AUC # par(mfrow = c(1, 1), mar = c(0.1, 0.1, 0.1, 0.1)) variable$cv_roc_obj[[idx]] = roc(as.numeric(y_valid), as.numeric(variable$cv_pred_class[[idx]])) idx <- idx + 1 # y <- rbind(variable$cv_pred_class[[idx]], t(y_valid)) # write.csv(y, paste0("label","_fold_",f,".csv"), row.names = F) # "saves/cv/", } variable$cv_flag <- TRUE }) output$cv_acc_plot <- renderPlotly({ if(variable$cv_flag == TRUE){ p = plot_ly(x = 1:length(variable$cv_fit[[1]]$acc)) for (i in 1:variable$k){ p = p %>% add_trace(y = variable$cv_fit[[i]]$acc, name = paste('Accuracy cv-', i, sep=""), mode = 'lines+markers') } p = p %>% layout(title = "Cross Validation - Accuracy for Training Data") return (p) # ti = 1:length(variable$fit$metrics$val_loss) # mva = lm(variable$fit$metrics$val_acc~ti+I(ti^2)+I(ti^3)) # ma = lm(variable$fit$metrics$acc~ti+I(ti^2)+I(ti^3)) # # line.fmt = list(dash="solid", width = 1.5, color=NULL) # # plot_ly(data = as.data.frame(variable$fit$metrics), x = 1:length(variable$fit$metrics$val_loss)) %>% # add_trace(y = variable$fit$metrics$acc, name = 'Accuracy', mode = 'lines+markers') %>% # add_trace(y = variable$fit$metrics$val_acc, name = 'Validation Accuracy', mode = 'lines+markers') %>% # add_lines(y = predict(ma), line=line.fmt, name="Accuracy Trend Line") %>% # add_lines(y = predict(mva), line=line.fmt, name="Validation Accuracy Trend Line") %>% # layout(title = "Accuracy for Train and Validation") } else{ return () } }) output$cv_val_acc_plot <- renderPlotly({ if(variable$cv_flag == TRUE){ p = plot_ly(x = 1:length(variable$cv_fit[[1]]$acc)) for (i in 1:variable$k){ p = p %>% add_trace(y = variable$cv_fit[[i]]$val_acc, name = paste('Validation Accuracy CV-', i, sep=""), mode = 'lines+markers') } p = p %>% layout(title = "Cross Validation - Accuracy for Validation Data") return (p) } else{ return () } }) output$cv_loss_plot <- renderPlotly({ if(variable$cv_flag == TRUE){ p = plot_ly(x = 1:length(variable$cv_fit[[1]]$acc)) for (i in 1:variable$k){ p = p %>% add_trace(y = variable$cv_fit[[i]]$loss, name = paste('Loss CV-', i, sep=""), mode = 'lines+markers') } p = p %>% layout(title = "Losses in Cross Validation for Train Data") return (p) } else{ return () } }) output$cv_val_loss_plot <- renderPlotly({ if(variable$cv_flag == TRUE){ p = plot_ly(x = 1:length(variable$cv_fit[[1]]$acc)) for (i in 1:variable$k){ p = p %>% add_trace(y = variable$cv_fit[[i]]$val_loss, name = paste('Validation Loss CV-', i, sep=""), mode = 'lines+markers') } p = p %>% layout(title = "Losses in Cross Validation for Validation Data") return (p) } else{ return () } }) output$cv_plot <- renderUI({ tagList( plotlyOutput("cv_acc_plot"), tags$br(), plotlyOutput("cv_val_acc_plot"), tags$br(), plotlyOutput("cv_loss_plot"), tags$br(), plotlyOutput("cv_val_loss_plot"), tags$br(), h3("ROC plot for Cross Validation Traning Process"), plotOutput("rocPlot_cv") ) }) output$rocPlot_cv <- renderPlot({ if (variable$cv_flag == TRUE){ if (variable$k <= 3){ par(mfrow = c(3, 1), mar = c(0.1, 0.1, 0.1, 0.1)) } else if (variable$k <= 6){ par(mfrow = c(3, 2), mar = c(0.1, 0.1, 0.1, 0.1)) } else { par(mfrow = c(3, 3), mar = c(0.1, 0.1, 0.1, 0.1)) } for (i in 1:variable$k){ plot.roc(variable$cv_roc_obj[[i]], print.auc=TRUE, main=paste("ROC curve for CV-", i, sep="")) } } else { return () } }) })
4659bd61b804ef411d6364a598fbd35536e6379c
a4c4893d319c93078075ab7549d23f927cf29ac5
/code/alfresco/alfExtractMain.R
74eb0b8d0d9041f745c9333bc3378507e607e435
[]
no_license
leonawicz/SNAPQAQC
4fecaef9b245e2f8b1c6a9c40d2ed86e6e6d5392
54eb9eca613202ffa166a2f3d417b506c5b78f8a
refs/heads/master
2020-04-12T01:48:01.178693
2017-03-10T19:00:31
2017-03-10T19:00:31
30,124,606
0
0
null
null
null
null
UTF-8
R
false
false
13,541
r
alfExtractMain.R
# @knitr setup # Command line arguments args=(commandArgs(TRUE)) if(!length(args)) q("no") else for(i in 1:length(args)) eval(parse(text=args[[i]])) if(!exists("modelIndex")) stop("Must provide a modelIndex 1 to 15, e.g., modelIndex=1") stopifnot(length(modelIndex)==1) if(!exists("domain")) stop("Must provide domain, e.g., domain='akcan1km' or domain='ak1km'") if(!exists("reps")) stop("Must provide replicates as integer(s) 1:200, e.g., reps=1:25") if(!exists("years")) years <- 2008:2100 # Assume if not specified if(!exists("Rmpi")) Rmpi <- TRUE if(!exists("mpiBy")) mpiBy <- "year" itervar <- if(mpiBy=="rep") reps else if(mpiBy=="year") 1:length(years) else stop("mpiBy must be 'rep' or 'year'.") loopBy <- if(mpiBy=="rep") "year" else "rep" if(!exists("doFire")) doFire <- TRUE if(!exists("doAgeVeg")) doAgeVeg <- TRUE if(exists("repSample") && is.numeric(repSample)){ set.seed(47) reps <- sort(sample(reps, min(repSample, length(reps)))) cat("Sampled replicates:\n", reps, "\n") } if(!exists("useCRU")) useCRU <- FALSE if(!exists("projectName")) projectName <- "Unnamed_Project_Run_Extractions" if(!exists("readMethod")) readMethod <- "loop" library(raster) library(data.table) library(dplyr) # Rmpi setup if(Rmpi){ library(Rmpi) mpi.spawn.Rslaves(needlog = TRUE) mpi.bcast.cmd( id <- mpi.comm.rank() ) mpi.bcast.cmd( np <- mpi.comm.size() ) mpi.bcast.cmd( host <- mpi.get.processor.name() ) } else { library(parallel) n.cores <- 32 } # Load data table of cell indices defining groups of shapefile polygons if(domain=="akcan1km"){ load("/atlas_scratch/mfleonawicz/projects/DataExtraction/workspaces/shapes2cells_akcan1km2km.RData") cells <- filter(cells, Source=="akcan1km") %>% group_by %>% select(-Source) %>% group_by(LocGroup, Location) } else if(domain=="ak1km"){ load("/atlas_scratch/mfleonawicz/projects/DataExtraction/workspaces/shapes2cells_ak1km.RData") cells <- filter(cells, Source=="ak1km") %>% group_by %>% select(-Source) %>% group_by(LocGroup, Location) } if(exists("locgroup")){ locgroup <- gsub("_", " ", locgroup) cat("locgroup = "); cat(locgroup); cat("\n") if(is.character(locgroup)) cells <- filter(cells, LocGroup %in% locgroup) if(is.numeric(locgroup)) cells <- filter(cells, LocGroup %in% unique(cells$LocGroup)[locgroup]) print(unique(cells$LocGroup)) stopifnot(nrow(cells) > 0) } if(domain=="akcan1km"){ veg.labels <- c("Black Spruce", "White Spruce", "Deciduous", "Shrub Tundra", "Graminoid Tundra", "Wetland Tundra", "Barren lichen-moss", "Temperate Rainforest") #dirs <- list.files("/atlas_scratch/apbennett/IEM/FinalCalib", pattern=".*.sres.*.", full=T) if(useCRU) dirs <- list.files("/atlas_scratch/mfleonawicz/alfresco/IEM/outputs/FinalCalib", pattern="CRU", full=T) if(!useCRU) dirs <- list.files("/atlas_scratch/mfleonawicz/alfresco/IEM/outputs/FinalCalib", pattern=".*.sres.*.", full=T) #if(useCRU) dirs <- list.files("/atlas_scratch/apbennett/Calibration/HighCalib/FMO_Calibrated", pattern="CRU", full=T) #if(!useCRU) dirs <- list.files("/atlas_scratch/apbennett/Calibration/HighCalib/FMO_Calibrated", pattern=".*.rcp.*.", full=T) } else if(domain=="ak1km"){ veg.labels <- c("Alpine Tundra", "Black Spruce", "White Spruce", "Deciduous", "Shrub Tundra", "Graminoid Tundra", "Wetland Tundra") if(useCRU) dirs <- list.files("/atlas_scratch/mfleonawicz/alfresco/CMIP5_Statewide/outputs/5m", pattern="CRU", full=T) if(!useCRU) dirs <- list.files("/atlas_scratch/mfleonawicz/alfresco/CMIP5_Statewide/outputs/5m", pattern="^rcp.*.", full=T) } mainDirs <- rep(paste0(dirs,"/Maps")[modelIndex], each=length(itervar)) modname <- unique(basename(dirname(mainDirs))) if(mpiBy=="rep") dir.create(ageDir <- file.path("/atlas_scratch/mfleonawicz/alfresco", projectName, "extractions/veg", modname), recursive=T, showWarnings=F) else ageDir <- NULL #veg.labels <- c("Black Spruce", "White Spruce", "Deciduous", "Shrub Tundra", "Graminoid Tundra", "Wetland Tundra", "Barren lichen-moss", "Temperate Rainforest") scen.levels <- c("SRES B1", "SRES A1B", "SRES A2", "RCP 4.5", "RCP 6.0", "RCP 8.5") mod.scen <- unlist(strsplit(modname, "\\.")) if(domain=="ak1km") mod.scen <- rev(mod.scen) #mod.scen <- unlist(strsplit(modname, "_")) # @knitr functions # Support functions swapModelName <- function(x){ switch(x, cccma_cgcm3_1="CCCMAcgcm31", gfdl_cm2_1="GFDLcm21", miroc3_2_medres="MIROC32m", mpi_echam5="MPIecham5", ukmo_hadcm3="ukmoHADcm3", CCSM4="CCSM4", "GFDL-CM3"="GFDL-CM3", "GISS-E2-R"="GISS-E2-R", "IPSL-CM5A-LR"="IPSL-CM5A-LR", "MRI-CGCM3"="MRI-CGCM3" ) } swapScenarioName <- function(x){ switch(x, sresb1="SRES B1", sresa1b="SRES A1B", sresa2="SRES A2", rcp45="RCP 4.5", rcp60="RCP 6.0", rcp85="RCP 8.5" ) } getPhase <- function(x){ switch(x, sresb1="AR4", sresa1b="AR4", sresa2="AR4", rcp45="AR5", rcp60="AR5", rcp85="AR5" ) } paste("Remaining support objects created. Now pushing objects to slaves.") # @knitr obj2slaves # Export objects to slaves if(Rmpi){ mpi.bcast.Robj2slave(cells) mpi.bcast.Robj2slave(reps) mpi.bcast.Robj2slave(years) mpi.bcast.Robj2slave(mainDirs) mpi.bcast.Robj2slave(modname) mpi.bcast.Robj2slave(ageDir) mpi.bcast.Robj2slave(itervar) mpi.bcast.Robj2slave(loopBy) mpi.bcast.Robj2slave(readMethod) mpi.bcast.Robj2slave(veg.labels) print("mpi.bcast.Robj2slave calls completed.") } # @knitr commands2slaves # Issue commands to slaves if(Rmpi){ mpi.bcast.cmd( mainDir <- mainDirs[id] ) mpi.bcast.cmd( source("/atlas_scratch/mfleonawicz/projects/SNAPQAQC/code/alfresco/alfExtract.R") ) mpi.bcast.cmd( dir.create(tmpDir <- paste0("/atlas_scratch/mfleonawicz/tmp/proc",id), showWarnings=F) ) mpi.bcast.cmd( rasterOptions(chunksize=10e10, maxmemory=10e11, tmpdir=tmpDir) ) print("mpi.bcast.cmd calls completed. Now running mpi.remote.exec...") } else { mainDir <- mainDirs[1] source("/atlas_scratch/mfleonawicz/projects/SNAPQAQC/code/alfresco/alfExtract.R") tmpDir <- paste0("/atlas_scratch/mfleonawicz/tmp/procX") rasterOptions(chunksize=10e10, maxmemory=10e11, tmpdir=tmpDir) } # @knitr fire_stats # Compile fire statistics if(doFire){ print("#### Compiling fire statistics... ####") if(Rmpi){ fsv.dat <- mpi.remote.exec( extract_data(i=itervar[id], type="fsv", loopBy=loopBy, mainDir=mainDir, reps=reps, years=years, cells=select(cells, -Cell_rmNA), readMethod=readMethod, veg.labels=veg.labels) ) fsv.dat <- rbindlist(fsv.dat) } else { len <- length(itervar) if(len <= n.cores){ fsv.dat <- mclapply(itervar, extract_data, type="fsv", loopBy=loopBy, mainDir=mainDir, reps=reps, years=years, cells=select(cells, -Cell_rmNA), readMethod=readMethod, veg.labels=veg.labels, mc.cores=n.cores) fsv.dat <- rbindlist(fsv.dat) } else { serial.iters <- ceiling(len/n.cores) n.cores2 <- which(len/(1:n.cores) < serial.iters)[1] fsv.dat <- vector("list", serial.iters) for(j in 1:serial.iters){ itervar.tmp <- 1:n.cores2 + (j-1)*n.cores2 itervar.tmp <- itervar.tmp[itervar.tmp <= max(itervar)] fsv.tmp <- mclapply(itervar.tmp, extract_data, type="fsv", loopBy=loopBy, mainDir=mainDir, reps=reps, years=years, cells=select(cells, -Cell_rmNA), readMethod=readMethod, veg.labels=veg.labels, mc.cores=n.cores) fsv.dat[[j]] <- rbindlist(fsv.tmp) rm(fsv.tmp) gc() print(paste("Replicate batch", j, "of", serial.iters, "complete.")) } fsv.dat <- rbindlist(fsv.dat) } } fsv.dat.names.ini <- copy(names(fsv.dat)) if(useCRU){ fsv.dat[, Model := "CRU 3.2"] fsv.dat[, Scenario := "Historical"] fsv.dat[, Phase := "Observed"] } else { fsv.dat[, Model := swapModelName(mod.scen[1])] fsv.dat[, Scenario := swapScenarioName(mod.scen[2])] fsv.dat[, Scenario := factor(Scenario, levels=scen.levels)] fsv.dat[, Phase := getPhase(mod.scen[2])] } fsv.dat <- setcolorder(fsv.dat, c("Phase", "Scenario", "Model", fsv.dat.names.ini)) setkey(fsv.dat, Location) print("Fire size by vegetation class completed.") print("Saving fire size by vegetation class data frames by location to .RData file.") locs <- unique(fsv.dat$Location) dir.create(fsvDir <- file.path("/atlas_scratch/mfleonawicz/alfresco", projectName, "extractions/fsv"), recursive=TRUE, showWarnings=FALSE) for(j in 1:length(locs)){ filename.tmp <- if(useCRU) paste0("fsv__", locs[j], "__", "CRU32") else paste0("fsv__", locs[j], "__", modname) d.fsv <- fsv.dat[locs[j]] save(d.fsv, file=paste0(fsvDir, "/", filename.tmp, ".RData")) print(paste(filename.tmp, "object", j, "of", length(locs), "saved.")) } print(tables()) rm(fsv.dat, d.fsv) gc() } # @knitr age_veg_stats # Compile vegetation class and age statistics if(doAgeVeg){ print("#### Compiling vegetation class and age statistics... ####") if(Rmpi){ va.dat <- mpi.remote.exec( extract_data(i=itervar[id], type="av", loopBy=loopBy, mainDir=mainDir, ageDir=ageDir, reps=reps, years=years, cells=select(cells, -Cell), readMethod=readMethod, veg.labels=veg.labels) ) d.area <- rbindlist(lapply(va.dat, function(x) x$d.area)) if(mpiBy=="year") d.age <- rbindlist(lapply(va.dat, function(x) x$d.age)) } else { len <- length(itervar) if(len <= n.cores){ va.dat <- mclapply(itervar, extract_data, type="av", loopBy=loopBy, mainDir=mainDir, ageDir=ageDir, reps=reps, years=years, cells=select(cells, -Cell), readMethod=readMethod, veg.labels=veg.labels, mc.cores=n.cores) d.area <- rbindlist(lapply(va.dat, function(x) x$d.area)) if(mpiBy=="year") d.age <- rbindlist(lapply(va.dat, function(x) x$d.age)) } else { serial.iters <- ceiling(len/n.cores) n.cores2 <- which(len/(1:n.cores) < serial.iters)[1] d.age <- d.area <- vector("list", serial.iters) for(j in 1:serial.iters){ itervar.tmp <- 1:n.cores2 + (j-1)*n.cores2 itervar.tmp <- itervar.tmp[itervar.tmp <= max(itervar)] va.dat <- mclapply(itervar.tmp, extract_data, type="av", loopBy=loopBy, mainDir=mainDir, ageDir=ageDir, reps=reps, years=years, cells=select(cells, -Cell), readMethod=readMethod, veg.labels=veg.labels, mc.cores=n.cores) d.area[[j]] <- rbindlist(lapply(va.dat, function(x) x$d.area)) if(mpiBy=="year") d.age[[j]] <- rbindlist(lapply(va.dat, function(x) x$d.age)) rm(va.dat) gc() print(paste("Replicate batch", j, "of", serial.iters, "complete.")) } d.area <- rbindlist(d.area) if(mpiBy=="year") d.age <- rbindlist(d.age) } } d.area.names.ini <- copy(names(d.area)) if(useCRU){ d.area[, Model := "CRU 3.2"] d.area[, Scenario := "Historical"] d.area[, Phase := "Observed"] } else { d.area[, Model := swapModelName(mod.scen[1])] d.area[, Scenario := swapScenarioName(mod.scen[2])] d.area[, Scenario := factor(Scenario, levels=scen.levels)] d.area[, Phase := getPhase(mod.scen[2])] } d.area <- setcolorder(d.area, c("Phase", "Scenario", "Model", d.area.names.ini)) setkey(d.area, Location) print("Vegetation area completed.") print("Saving vegetation area data tables by location to .RData files.") locs <- unique(d.area$Location) dir.create(vegDir <- file.path("/atlas_scratch/mfleonawicz/alfresco", projectName, "extractions/veg"), recursive=TRUE, showWarnings=FALSE) for(j in 1:length(locs)){ filename.tmp <- if(useCRU) paste0("veg__", locs[j], "__", "CRU32") else paste0("veg__", locs[j], "__", modname) d.vegarea <- d.area[locs[j]] save(d.vegarea, file=paste0(vegDir, "/", filename.tmp, ".RData")) print(paste(filename.tmp, "object", j, "of", length(locs), "saved.")) } print(tables()) rm(d.area, d.vegarea) gc() if(mpiBy=="year"){ d.age.names.ini <- copy(names(d.age)) if(useCRU){ d.age[, Model := "CRU 3.2"] d.age[, Scenario := "Historical"] d.age[, Phase := "Observed"] } else { d.age[, Model := swapModelName(mod.scen[1])] d.age[, Scenario := swapScenarioName(mod.scen[2])] d.age[, Scenario := factor(Scenario, levels=scen.levels)] d.age[, Phase := getPhase(mod.scen[2])] } d.age <- setcolorder(d.age, c("Phase", "Scenario", "Model", d.age.names.ini)) setkey(d.age, Location) print("Vegetation area by age completed.") print("Saving vegetation area by age data tables by location to .RData files.") locs <- unique(d.age$Location) dir.create(ageDir <- file.path("/atlas_scratch/mfleonawicz/alfresco", projectName, "extractions/age"), showWarnings=F) for(j in 1:length(locs)){ filename.tmp <- if(useCRU) paste0("age__", locs[j], "__", "CRU32") else paste0("age__", locs[j], "__", modname) d.vegage <- d.age[locs[j]] save(d.vegage, file=paste0(ageDir, "/", filename.tmp, ".RData")) print(paste(filename.tmp, "object", j, "of", length(locs), "saved.")) } print(tables()) rm(d.age, d.vegage) gc() } } # All done if(Rmpi){ mpi.close.Rslaves(dellog = FALSE) mpi.exit() }
ea320c9817c0f64f3c1e2e5873dfce36159fea75
f2e5a6f59add8d8f542986368f04cd2618f73cfb
/man/print.svR_games.Rd
3bdd244dd9ecd27cf7c2e4a9b39bcdafdffb45ce
[]
no_license
durtal/servevolleyR
c106a04ac5ef84b5ba32a772816aa2d5fc0ea6cb
7df9e63fe41394d772b3bb23aeb29aff1c237227
refs/heads/master
2021-01-17T11:14:31.885626
2015-09-03T13:22:55
2015-09-03T13:22:55
38,617,027
7
2
null
null
null
null
UTF-8
R
false
false
311
rd
print.svR_games.Rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/simGame.R \name{print.svR_games} \alias{print.svR_games} \title{print method for detailed return of \link{simGames}} \usage{ \method{print}{svR_games}(x) } \description{ print method for detailed return of \link{simGames} }
7049324d0e5f7c1ae8b997891d0c27520413c18c
e2e1a80e7d9b39886d47d144f7d573a6d3e87668
/man/inferSSNetwork.Rd
f1f3b881a913967ad7a68b9b0fe43c31b25ba094
[ "MIT" ]
permissive
tianyu-lu/dynUGENE
087fdc2070cedaf101720b269536170f6c8a9810
120f6b829b4683222d569aeb8002aa28b1a2498c
refs/heads/master
2023-02-13T08:41:25.755706
2021-01-05T23:31:00
2021-01-05T23:31:00
306,977,481
1
0
null
null
null
null
UTF-8
R
false
true
2,703
rd
inferSSNetwork.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/inferSSNetwork.R \name{inferSSNetwork} \alias{inferSSNetwork} \title{Infers a Gene Regulatory Network from Steady-State Data} \usage{ inferSSNetwork( data, mask = NULL, ntree = 10L, mtry = NULL, alpha = NULL, seed = 777, showPlot = FALSE ) } \arguments{ \item{data}{A data.frame of gene expression values, should be numerics. Each row is a different measurement at steady state. Each column corresponds to one gene.} \item{mask}{A matrix which only includes the values 1 or NA. Must be of size numgenes*numgenes. If entry \eqn{(i.j) = 1}, then \eqn{i} can be used in predicting the value of \eqn{j}. Otherwise, the connection is snipped and such a dependency is not allowed when training the random forests.} \item{ntree}{A positive integer indicating the number of trees in each random forest. Equivalent to the ntree argument in the randomForest package. Defaults to 10L.} \item{mtry}{A positive integer indicating the number of randomly sampled candidates to use at each split of each random forest. Equivalent to the mtry argument in the randomForest package. Defaults to p/3, where p is the number of genes. This option is disabled when a mask is provided and the default value is used.} \item{alpha}{If not provided, assumed to be 1 for all genes. If provided, can be a vector of the degradation rates of each gene, or a single number (same rate for all genes).} \item{seed}{Random seed for reproducibility. Defaults to 777.} \item{showPlot}{Plots the weights matrix as a heatmap. Defaults to FALSE. #' @return Returns an object of class "ugene" with the following items: \itemize{ \item network - A matrix storing the importance weights w_ij of each pair of genes. \item alpha - A vector of the gene product degradation rates, possibly inferred from data. \item model - A list of "randomForest" objects where model[i] is the trained randomForest able to predict changes in concentrations of gene i given the current concentrations of all genes. }} } \description{ Given a dataframe genes as columns and different measurements as rows, returns the adjacency matrix of the inferred network, the estimated decay rates of each species, and the dynamics of the network learned by \eqn{p} random forests. } \examples{ \dontrun{ data <- grndata::syntren300.data ugene <- inferSSNetwork(data, showPlot = TRUE) } } \references{ Geurts, P. (2018). dynGENIE3: dynamical GENIE3 for the inference of gene networks from time series expression data. \emph{Scientific reports}, 8(1), 1-12. A. Liaw and M. Wiener (2002). Classification and Regression by randomForest. R News 2(3), 18--22. }
e1fba596094578290c0483e2bc85a9c4cb76bac1
88dbe91218a7592f1927fde83a254808c9570f76
/homework one.R
34fd484bd56abe459c0f4a104920583d59c6048e
[]
no_license
YUYUNPONG/tryone
ce7a70f9834b99cfd2f6c09875224caec68d2163
eb20a0add63bd050d70463c35d8ea6000965b63a
refs/heads/master
2020-04-28T01:04:19.251080
2019-04-17T12:21:42
2019-04-17T12:21:42
174,840,640
0
0
null
null
null
null
UTF-8
R
false
false
4,385
r
homework one.R
###資料分析 ## 第一步:讀入資料 Sys.setlocale(category ='LC_ALL') library(tm) library(readr) jan<- read_csv("201801_data.csv",locale = locale(encoding = "UTF8")) feb<- read_csv("201802_data.csv",locale = locale(encoding = "UTF8")) mar<- read_csv("201803_data.csv",locale = locale(encoding = "UTF8")) apr<- read_csv("201804_data.csv",locale = locale(encoding = "UTF8")) may<- read_csv("201805_data.csv",locale = locale(encoding = "UTF8")) jun<- read_csv("201806_data.csv",locale = locale(encoding = "UTF8")) jul<- read_csv("201807_data.csv",locale = locale(encoding = "UTF8")) aug<- read_csv("201808_data.csv",locale = locale(encoding = "UTF8")) sep<- read_csv("201809_data.csv",locale = locale(encoding = "UTF8")) oct<- read_csv("201810_data.csv",locale = locale(encoding = "UTF8")) nov<- read_csv("201811_data.csv",locale = locale(encoding = "UTF8")) dec<- read_csv("201812_data.csv",locale = locale(encoding = "UTF8")) jan19<- read_csv("201901_data.csv",locale = locale(encoding = "UTF8")) View(jan) ##取出JAN中的資料看第一條的字串 jan$Message[1] nchar(jan$Message[1]) ##取出JAN中的資料Message 每筆總共數,計算字串長度 nchar(jan$Message) ##取出JAN中的Page_Name資,指定查詢 grep("韓國瑜",jan$Page_Name)#36 韓 grep("陳其邁",jan$Page_Name)# 33 陳 grep("柯文哲",jan$Page_Name) ## 第一篇說柯,第432再說柯 regexpr("韓國瑜", jan$Message) ##合併資料 alldata=rbind(jan, feb, mar, apr, may,jun, jul, aug, sep, oct, nov, dec, jan19) save(alldata, file="alldata.rda") ##save new data ##設定日期時間格式 alldata$Date=as.POSIXct(alldata$Date,format="%Y/%m/%d %H:%M:%S")## format 定義 ##資料整理 ##挑選候選人fb資料1#grepl模糊比對,明子有韓的 kh <-filter(alldata,grepl("韓國瑜", alldata$Page_Name)==TRUE&grepl("高雄選韓國瑜News",alldata$Page_Name)==FALSE&grepl("韓國瑜粉絲團", alldata$Page_Name)==FALSE&grepl("韓國瑜新聞網", alldata$Page_Name)==FALSE&grepl("韓國瑜民間粉絲團", alldata$Page_Name)==FALSE&grepl("高雄在地韓國瑜News", alldata$Page_Name)==FALSE&grepl("侯友宜 盧秀燕 韓國瑜 北中南連線", alldata$Page_Name)==FALSE) gc <-filter(alldata,grepl("陳其邁", alldata$Page_Name)==TRUE&grepl("陳其邁的潛水日記",alldata$Page_Name)==FALSE) ##挑選候選人fb資料2 kh1 <- alldata %>% filter(Page_Name == "韓國瑜") %>% select(Page_Name, Page_ID, Date, All_Reaction_Count, LIKE_COUNT, Comment_Count, Share_Count, Message, Type) ## 沒有挑選全部 gc1 <- alldata %>% filter(Page_Name == "陳其邁 Chen Chi-Mai") %>% select(Page_Name, Page_ID, Date, All_Reaction_Count, LIKE_COUNT, Comment_Count, Share_Count, Message, Type) ## 沒有挑選全部 ## 分月份?? 1 group_byzp 分群的意思 khMonth <-kh%>%group_by(month=format(Date,"%Y%m"))%>%count()%>%mutate(type="khan") khMonth <-kh%>%group_by(type=Type)%>%count() gcMonth <-gc%>%group_by(month=format(Date,"%Y%m"))%>%count()%>%mutate(type="gchen") month_rank=rbind(khMonth, gcMonth)%>%arrange((month)) month_rank22=rbind(khMonth, gcMonth) ## 分月份?? 2 khMonth1 <-kh%>%group_by(month=format(Date,"%m"))%>%count()%>%mutate(type="Han1") gcMonth1 <-gc%>%group_by(month=format(Date,"%m"))%>%count()%>%mutate(type="Ke1") month_rank2=rbind(khMonth1, gcMonth1) month_rank1=rbind(khMonth1, gcMonth1)%>%arrange((month)) ##畫圖套件 library(ggplot2) ###BAR# 兩位比較 ggplot(month_rank,aes(x=month,y=n,fill=type))+ geom_bar(stat="identity",position = "dodge") ggplot(month_rank22,aes(x=month,y=n,fill=type))+ geom_bar(stat="identity",position = "dodge") # ggplot(month_rank,aes(x=month,y=n,fill=type))+ geom_bar(stat="identity") # LINE ggplot(month_rank,aes(x=month,y=n,group=type,color=type))+geom_line() # BOXPLOT ggplot(month_rank,aes(x=month,y=n))+geom_boxplot() # POINT #head取資料的前幾位,在沒有排去前 ggplot(kh,aes(x=Share_Count,y=All_Reaction_Count))+ geom_point() ggplot(head(gc,657),aes(x=Share_Count,y=All_Reaction_Count))+ geom_point() ################### library(ggpubr) kh$mes_nchar=nchar(kh$Message) gc$mes_nchar=nchar(gc$Message) ggscatter(gc,x="All_Reaction_Count",y="LIKE_COUNT", add = "reg.line", conf.int = TRUE, cor.coef = TRUE, cor.method = "pearson") ggqqplot(gc$All_Reaction_Count) #常態分佈 ggqqplot(gc$LIKE_COUNT) #常態分佈
c7024e6da24a23f09ee54bf22cee1aeeed5c7aa9
49d20609fe6b5866d46460a59e3f78903a5cb3ff
/Week-5/資料清理與合併.R
8365334bea9159c60a0dd6ec82394de15228356e
[]
no_license
PeterChiu1202/Politics-and-information-2019
8e2fcc23a5e77e768ad6302306afb8625330604a
2c1a700b017b511cf8bd218df6e4f5d852105ff3
refs/heads/master
2020-04-26T16:53:32.709753
2019-04-21T14:54:20
2019-04-21T14:54:20
173,695,267
0
0
null
null
null
null
UTF-8
R
false
false
1,120
r
資料清理與合併.R
# Data Cleaning and Combine library(readr) Jan.18 <- read_csv("201801_data.csv") Feb.18 <- read_csv("201802_data.csv") Mar.18 <- read_csv("201803_data.csv") Apr.18 <- read_csv("201804_data.csv") May.18 <- read_csv("201805_data.csv") Jun.18 <- read_csv("201806_data.csv") Jul.18 <- read_csv("201807_data.csv") Aug.18 <- read_csv("201808_data.csv") Sep.18 <- read_csv("201809_data.csv") Oct.18 <- read_csv("201810_data.csv") Nov.18 <- read_csv("201811_data.csv") Dec.18 <- read_csv("201812_data.csv") Jan.19 <- read_csv("201901_data.csv") alldata=rbind(Jan.18, Feb.18, Mar.18, Apr.18, May.18, Jun.18, Jul.18, Aug.18, Sep.18, Oct.18, Nov.18, Dec.18, Jan.19) save(alldata, file="AllData.rda") Han <- alldata %>% filter(Page_Name == "韓國瑜") %>% select(Page_Name, Page_ID, Date, All_Reaction_Count, LIKE_COUNT, Comment_Count, Share_Count, Message, Type) Ke <- alldata %>% filter(Page_Name == "柯文哲") %>% select(Page_Name, Page_ID, Date, All_Reaction_Count, LIKE_COUNT, Comment_Count, Share_Count, Message, Type) save(Han, file="HanKY.rda") save(Ke, file="KeWC.rda")
72b2d2e5293c259fa6898921718ef5952bee87bf
8d547a59eeaaeeb6e0c7df8ab98cc1bce8f81c4a
/Drake_code.R
e096361ea59a0536ee28e82fa3318beb83c66eb1
[]
no_license
hanndrake/Hello-world
60b2afe2f81eee1a0f2847ce8750c9cfefa16f11
157a771887af7842e40ad76ed3e2f309e6b2ee9a
refs/heads/master
2020-07-30T20:09:23.085368
2019-09-23T12:27:14
2019-09-23T12:27:14
210,344,330
0
0
null
2019-09-23T12:27:15
2019-09-23T12:01:30
R
UTF-8
R
false
false
417
r
Drake_code.R
lyrics = "You used to call me on my, you used to, you used to You used to call me on my cell phone Late night when you need my love Call me on my cell phone Late night when you need my love" chorus = "I know when that hotline bling That can only mean one thing I know when that hotline bling That can only mean one thing" print(c(lyrics,chorus)) #prints the first lyrics of Drake's 2015 hit single "Hotline Bling"
f788995eb0a200eaf66599dee71c418b4b1d1380
c7c304bc767395e7f0eac6b3c9459bcca6f1575a
/ExampleDREAMBayesianTools.R
3533ed13a91cdfb7cf59ff43b0d55fbacace7b01
[ "MIT" ]
permissive
jds485/R-BayesianToolsExample
040a33dcc2aeefee9abc184fa985d717290d73e7
2a1ce8dd46e1bc42d58239e8c15bd3e55f5b705d
refs/heads/master
2022-11-25T12:26:32.634750
2020-07-22T14:32:49
2020-07-22T14:32:49
281,698,169
0
0
null
null
null
null
UTF-8
R
false
false
5,344
r
ExampleDREAMBayesianTools.R
#Script to lean some of the functionality of the BayesianTools R package #Includes serial and parallel examples. #External parallelization not demonstrated here. #There are many additional plots and diagnostics available in the coda and bayesplot packages. Users encouraged to try them. #Example from: https://cran.r-project.org/web/packages/BayesianTools/vignettes/BayesianTools.html#example #Load libraries---- library(BayesianTools) library(parallel) library(bayesplot) library(coda) #Setup problem: Quadratic Equation---- set.seed(2759) sampleSize = 30 x <- (-(sampleSize-1)/2):((sampleSize-1)/2) y <- 1 * x + 1*x^2 + rnorm(n=sampleSize,mean=0,sd=10) plot(x,y, main="Test Data") #Likelihood definition---- likelihood1 <- function(param){ #Intercept, linear, quadratic terms pred = param[1] + param[2]*x + param[3] * x^2 #Standard deviation parameter singlelikelihoods = dnorm(y, mean = pred, sd = 1/(param[4]^2), log = T) return(sum(singlelikelihoods)) } #Setup problem and define the uniform prior---- setUp1 <- createBayesianSetup(likelihood1, lower = c(-5,-5,-5,0.01), upper = c(5,5,5,30)) #MCMC setup for DREAMzs algorithm - Serial Run---- #Iterations per chain = (iterations - burnin/thin). 1400 with 5 chains #Number of chains specified by startValue = 5 (5 random draws from prior) settings = list(iterations = 10000, gamma= NULL, eps = 0, e = 0.05, parallel = NULL, Z = NULL, ZupdateFrequency = 10, pSnooker = 0.1, DEpairs = 3, nCR = 3, pCRupdate = TRUE, updateInterval = 10, #burnin must be greater than adaptation. burnin = 3000, adaptation = 2000, thin = 1, message = FALSE, startValue = 5) out1 <- runMCMC(bayesianSetup = setUp1, sampler = "DREAMzs", settings = settings) # Summary information and plots---- summary(out1) #Traceplot tracePlot(out1, smooth=FALSE) #Marginal prior and posterior marginalPlot(x = out1, prior = TRUE) #Scatterplot matrix of parameters correlationPlot(out1) #Potential scale reduction factor gelmanDiagnostics(out1, plot=T) #Density overlay mcmc_dens_overlay(out1$chain, color_chains = TRUE) #Serial run with half the iterations---- settings_5000 = list(iterations = 5000, gamma= NULL, eps = 0, e = 0.05, parallel = NULL, Z = NULL, ZupdateFrequency = 10, pSnooker = 0.1, DEpairs = 3, nCR = 3, pCRupdate = TRUE, updateInterval = 10, #burnin must be greater than adaptation. burnin = 3000, adaptation = 2000, thin = 1, message = FALSE, startValue = 5) out1_5000 <- runMCMC(bayesianSetup = setUp1, sampler = "DREAMzs", settings = settings_5000) # Summary information and plots---- summary(out1_5000) #Traceplot tracePlot(out1_5000, smooth=FALSE) #Marginal prior and posterior marginalPlot(x = out1_5000, prior = TRUE) #Scatterplot matrix of parameters correlationPlot(out1_5000) #Potential scale reduction factor gelmanDiagnostics(out1_5000, plot=T) #Density overlay mcmc_dens_overlay(out1$chain, color_chains = TRUE) #Serial run with double the iterations---- settings_20000 = list(iterations = 20000, gamma= NULL, eps = 0, e = 0.05, parallel = NULL, Z = NULL, ZupdateFrequency = 10, pSnooker = 0.1, DEpairs = 3, nCR = 3, pCRupdate = TRUE, updateInterval = 10, #burnin must be greater than adaptation. burnin = 3000, adaptation = 2000, thin = 1, message = FALSE, startValue = 5) out1_20000 <- runMCMC(bayesianSetup = setUp1, sampler = "DREAMzs", settings = settings_20000) # Summary information and plots---- summary(out1_20000) #Traceplot tracePlot(out1_20000, smooth=FALSE) #Marginal prior and posterior marginalPlot(x = out1_20000, prior = TRUE) #Scatterplot matrix of parameters correlationPlot(out1_20000) #Potential scale reduction factor gelmanDiagnostics(out1_20000, plot=T) #Density overlay mcmc_dens_overlay(out1$chain, color_chains = TRUE) #Parallel run---- #For parallel test on 5 cores setUp1_par <- createBayesianSetup(likelihood1, lower = c(-5,-5,-5,0.01), upper = c(5,5,5,30), parallel = 5, parallelOptions = list(packages=list('BayesianTools'), variables=list('x','y'), dlls=NULL)) #Note: setting the seed equal to the seed for serial does not result in identical runs. There must be a parallel random seed option that's different than serial. settings_par = list(iterations = 10000, gamma= NULL, eps = 0, e = 0.05, parallel = NULL, Z = NULL, ZupdateFrequency = 10, pSnooker = 0.1, DEpairs = 3, nCR = 3, pCRupdate = TRUE, updateInterval = 10, #burnin must be greater than adaptation. burnin = 3000, adaptation = 2000, thin = 1, message = FALSE, startValue = 5) out1_par <- runMCMC(bayesianSetup = setUp1_par, sampler = "DREAMzs", settings = settings_par) # Summary information and plots---- #Note that summary requires that the parallel cores are still open summary(out1_par) #Traceplot tracePlot(out1_par, smooth=FALSE) #Marginal prior and posterior marginalPlot(x = out1_par, prior = TRUE) #Scatterplot matrix of parameters correlationPlot(out1_par) #Potential scale reduction factor gelmanDiagnostics(out1_par, plot=T) stopParallel(setUp1_par)
bcdac0903bfca2de163c6776f7e1f7e2c5545983
9505d8ab047a5d6e35e10745d99ee1c268e2be4a
/theme-clean.R
8434f2345ba4e5428e24626abdc2394299c3ad63
[]
no_license
mloop/r-scripts
9a9326f802f8e4ce1d3ae2c76a18674d79199ba8
da01ff94360c9fdff1395c08b2e3e0694b490875
refs/heads/master
2021-01-10T06:45:08.457307
2016-04-01T17:04:41
2016-04-01T17:04:41
52,898,889
0
0
null
null
null
null
UTF-8
R
false
false
649
r
theme-clean.R
# a clean theme, which came from http://stackoverflow.com/questions/16631568/ggplot2-mapping-county-boundries-in-one-color-and-state-boundries-in-another-on theme_clean <- function(base_size = 12) { require(grid) theme_grey(base_size) %+replace% theme( axis.title = element_blank(), axis.text = element_blank(), panel.background = element_blank(), panel.grid = element_blank(), axis.ticks.length = unit(0,"cm"), axis.ticks.margin = unit(0,"cm"), panel.margin = unit(0,"lines"), plot.margin = unit(c(0,0,0,0),"lines"), complete = TRUE ) }
2baac199e54f5d63595db294339716b91e493f5a
b5274edf8f2b3e9f995290b84745860355981184
/plot2.R
8dcd37667607c21ad3161bbe8e36501cf3dde899
[]
no_license
vaibhav6215/ExData_Plotting1
3e4e8529a24e0fe004106c761bb147c467c5752e
652b8038168af0646921dc4ce3ca8ff05158ef00
refs/heads/master
2021-01-24T21:12:01.195214
2014-09-06T18:01:40
2014-09-06T18:01:40
null
0
0
null
null
null
null
UTF-8
R
false
false
371
r
plot2.R
a<-fread("household_power_consumption.txt") dat<-a[which(a$Date=="1/2/2007" | a$Date=="2/2/2007"),] dat$Date<-as.Date(dat$Date,format="%d/%m/%Y") dat$Time<-paste(dat$Date,dat$Time) par(mfrow=c(1,1)) with(dat,plot(strptime(Time,"%Y-%m-%d %H:%M:%S"),Global_active_power,type="l",ylab="Global active Power (Kilowatts)",xlab="")) dev.copy(png, file = "plot2.png") dev.off()
6a8d24ff11e5ef30f86342981b7e419156109585
45b25bd747002ea494942c9ba660a67f1fcd4fd6
/R-plots/jellyfish-plots.R
d02193452ec547de1f3045958a4b16ee879a915a
[]
no_license
mikeyweigand/Bordetella_species
6b913ee58c5820b33fac1b3929621f2ee180be9e
ea2344518cabc83ff31473b179acbe830c28b2e5
refs/heads/master
2020-06-24T16:44:06.803606
2020-02-06T18:19:41
2020-02-06T18:19:41
199,019,990
0
0
null
null
null
null
UTF-8
R
false
false
6,326
r
jellyfish-plots.R
# This script takes the outputs from jellyfish and draws line plots of kmer copy number abundance. Intended to be run interactively in Rstudio. setwd("~/Documents/Bordetella_species/results/jellyfish/") library(ggplot2) library(scales) library(reshape) ### B. bronch ### # hist.Bb = read.table("./20180222/hist/Bb-15mer.hist", header=T, sep="\t") # hist.Bb2 <- cbind(hist.Bb, rowMeans(hist.Bb[-1])) # colnames(hist.Bb2)[dim(hist.Bb2)[2]] = "Mean" # hist.Bb2.melted <- melt(hist.Bb2, id = "Tag") # head(hist.Bb2.melted) # (ggplot( data = hist.Bb2.melted, aes(x=Tag, y=value, color = variable)) # + geom_point(size=0.5) # + geom_line() # + coord_cartesian(ylim=c(0,1000),xlim=c(0,80)) # ) ### B. pertussis ### # hist.Bp = read.table("./20180222/hist/Bp-15mer.hist", header=T, sep="\t") # hist.Bp2 <- cbind(hist.Bp, rowMeans(hist.Bp[-1])) # colnames(hist.Bp2)[dim(hist.Bp2)[2]] = "Mean" # hist.Bp2.melted <- melt(hist.Bp2, id = "Tag") # # (ggplot( data = hist.Bp2.melted, aes(x=Tag, y=value, color = variable)) # + geom_point(size=0.5) # + geom_line() # + coord_cartesian(ylim=c(0,750),xlim=c(110,140)) # ) # (ggplot( hist.Bp2, aes(x=Tag, y=Bp_H559.15mer)) # + geom_line() # + geom_point(size = 0.5) # + scale_y_continuous(label=comma,name = "Average Number of 15-mers") # + scale_x_continuous(name = "Frequency") # + coord_cartesian(ylim=c(0,1000),xlim=c(100,150)) # ) ### B. parapertussis ### # hist.Bpp = read.table("./20180222/hist/Bpp-15mer.hist", header=T, sep="\t") # hist.Bpp2 <- cbind(hist.Bpp, rowMeans(hist.Bpp[-1])) # colnames(hist.Bpp2)[dim(hist.Bpp2)[2]] = "Mean" # hist.Bpp2.melted <- melt(hist.Bpp2, id = "Tag") # # (ggplot( data = hist.Bpp2.melted, aes(x=Tag, y=value, color = variable)) # + geom_point(size=0.5) # + geom_line() # + coord_cartesian(ylim=c(0,1500),xlim=c(0,80)) # ) ### B. holmesii ### # hist.Bho = read.table("./20180222/hist/Bho-15mer.hist", header=T, sep="\t") # hist.Bho2 <- cbind(hist.Bho, rowMeans(hist.Bho[-1])) # colnames(hist.Bho2)[dim(hist.Bho2)[2]] = "Mean" # hist.Bho2.melted <- melt(hist.Bho2, id = "Tag") # # (ggplot( data = hist.Bho2.melted, aes(x=Tag, y=value, color = variable)) # + geom_point(size=0.5) # + geom_line() # + coord_cartesian(ylim=c(0,1500),xlim=c(0,50)) # ) ### B. hinzii ### # hist.Bhi = read.table("./20180222/hist/Bhi-15mer.hist", header=T, sep="\t") # hist.Bhi2 <- cbind(hist.Bhi, rowMeans(hist.Bhi[-1])) # colnames(hist.Bhi2)[dim(hist.Bhi2)[2]] = "Mean" # hist.Bhi2.melted <- melt(hist.Bhi2, id = "Tag") # # (ggplot( data = hist.Bhi2.melted, aes(x=Tag, y=value, color = variable)) # + geom_point(size=0.5) # + geom_line() # + coord_cartesian(ylim=c(0,1000),xlim=c(0,30)) # ) ### B. avium ### # hist.Ba = read.table("./20180222/hist/Ba-15mer.hist", header=T, sep="\t") # hist.Ba2 <- cbind(hist.Ba, rowMeans(hist.Ba[-1])) # colnames(hist.Ba2)[dim(hist.Ba2)[2]] = "Mean" # hist.Ba2.melted <- melt(hist.Ba2, id = "Tag") # # (ggplot( data = hist.Ba2.melted, aes(x=Tag, y=value, color = variable)) # + geom_point(size=0.5) # + geom_line() # + coord_cartesian(ylim=c(0,700),xlim=c(0,60)) # ) ### B. trematum ### # hist.Bt = read.table("./20180222/hist/Bt-15mer.hist", header=T, sep="\t") # hist.Bt2 <- cbind(hist.Bt, rowMeans(hist.Bt[-1])) # colnames(hist.Bt2)[dim(hist.Bt2)[2]] = "Mean" # hist.Bt2.melted <- melt(hist.Bt2, id = "Tag") # # (ggplot( data = hist.Bt2.melted, aes(x=Tag, y=value, color = variable)) # + geom_point(size=0.5) # + geom_line() # + coord_cartesian(ylim=c(0,100),xlim=c(0,200)) # ) ### B. sp ### # hist.Bsp = read.table("./20180222/hist/Bsp-15mer.hist", header=T, sep="\t") # hist.Bsp2 <- cbind(hist.Bsp, rowMeans(hist.Bsp[-1])) # colnames(hist.Bsp2)[dim(hist.Bsp2)[2]] = "Mean" # hist.Bsp2.melted <- melt(hist.Bsp2, id = "Tag") # # (ggplot( data = hist.Bsp2.melted, aes(x=Tag, y=value, color = variable)) # + geom_point(size=0.5) # + geom_line() # + coord_cartesian(ylim=c(0,1000),xlim=c(0,60)) # ) # # (ggplot( hist.Bhi2, aes(x=Tag, y=Bhi_H720.15mer)) # + geom_line() # + geom_point(size = 0.5) # + scale_y_continuous(label=comma,name = "Average Number of 15-mers") # + scale_x_continuous(name = "Frequency") # + coord_cartesian(ylim=c(0,1500),xlim=c(0,50)) # ) # # (ggplot( hist.Breps, aes(x=Tag, y=Bpetrii_DSM12804.15mer)) # + geom_line() # + geom_point(size = 0.5) # + scale_y_continuous(label=comma,name = "Average Number of 15-mers") # + scale_x_continuous(name = "Frequency") # + coord_cartesian(ylim=c(0,1500),xlim=c(0,50)) # ) ### Representative subset ### #hist.Breps = read.table("./20180222/hist/Reps-15mer.hist", header=T, sep="\t") hist.Breps = read.table("./20180222/hist/Reps-15mer.20181129.hist", header=T, sep="\t") hist.Breps.melted <- melt(hist.Breps, id = "Tag") head(hist.Breps.melted) (ggplot( data = subset(hist.Breps.melted, Tag > 1 ), aes(x=Tag, y=value, color = variable)) + geom_line() + coord_cartesian(ylim=c(0,1550),xlim=c(0,27)) + theme_classic(base_size = 14) + scale_x_continuous(expand = c(0,0)) + scale_y_continuous(expand = c(0,0)) + theme( legend.position = c(0.5,0.5), legend.background=element_rect(fill="white", size=0.5, color="black"), legend.text=element_text(size=6), legend.title=element_text(size=6), legend.direction = 'horizontal', axis.text = element_text(color='black') ) + labs(x="Copy number", y="15-mer count" ) ) #ggsave("./20180222/99.figures/20181129-Reps-15mer.pdf", device = 'pdf', width = 6, height = 3, units = 'in', useDingbats=F) hist.bp.bho = subset(hist.Breps.melted, subset = variable %in% c('Bho_F615.15mer','Bp_H627.15mer')) head(hist.bp.bho) (ggplot( data = subset(hist.bp.bho, Tag > 1 ), aes(x=Tag, y=value, color = variable)) + geom_line() + coord_cartesian(ylim=c(0,1550),xlim=c(0,155)) + theme_classic(base_size = 14) + scale_x_continuous(expand = c(0,0)) + scale_y_continuous(expand = c(0,0)) + theme( legend.position = c(0.75,0.6), legend.background=element_rect(fill="white", size=0.5, color="black"), legend.text=element_text(size=7), axis.text = element_text(color='black') ) + labs(x="Copy number", y="15-mer count" ) ) #ggsave("./20180222/99.figures/20180803-Reps-15mer-Bp-Bho.pdf", device = 'pdf', width = 3, height = 3, units = 'in', useDingbats=F)
10128292d5db61f15cf4b3caa9c20aeab085e9c4
bb166b1903b12a423fe17ffa27772ca465f8f313
/R/play_stats_per_game.R
6933278e59122422ecce49a5661355c3c4de5514
[]
no_license
cran/AdvancedBasketballStats
73aa903ab2959113cd0e08ff52a1d30b28705cd4
5fc71920bddf1e099488645ae07dd74b7351540c
refs/heads/master
2023-04-11T01:24:09.173088
2021-04-06T11:10:07
2021-04-06T11:10:07
339,602,070
0
0
null
null
null
null
UTF-8
R
false
false
1,521
r
play_stats_per_game.R
#' @title Play stats per game #' @description The function allows the calculation of play statistics per game. #' @param df1 Should be a Data Frame that represents the play's statistics. The parameter has to be in the format provided by the play_data_adjustment() function. #' @details The calculation is made with the number of games played by the player. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with play statistics per game #' @examples #' #' df1 <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71), #' "PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1), #' "FGA Percentage" = c(0.552,1),"3P" = c(6,1),"3PA" = c(18,1), #' "3P Percentage" = c(0.333,1),"2P" = c(149,0),"2PA" = c(263,0), #' "2P Percentage" = c(0.567,0),"FT" = c(39,1), "FTA" = c(53,1), #' "FT Percentage" = c(0.736,1), "ANDONE" = c(12,1), "AST" = c(0,1), #' "TOV" = c(27,1)) #' #' play_stats_per_game(df1) #' #' @export #' play_stats_per_game <- function(df1){ df1 <- df1[-nrow(df1),] for(i in 3:ncol(df1)){ if(i==6 || i==9 || i==12 || i==15){ df1[i] <- round(df1[i],3) } else{ df1[i] <- round(df1[i] / df1[2],2) } } names(df1) <- c("Name","GP","PTS","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%","And One","AST","TOV") df1[is.na(df1)] <- 0 return(df1) }
02963a0fa377ccd071ecb46715284bc374946a8e
5d4429dc4708aa5e9e1d24a7e7740243ae0d4a47
/R/dtedit.R
85a111a74a4344573718ec006d5902050e49b082
[]
no_license
DavidPatShuiFong/DTedit
6c449449afba79c1d465825e361730e7357f3e11
082616e09aeb0d043e793c0d17a02532e1bac120
refs/heads/master
2022-11-16T02:22:46.032038
2021-10-23T11:56:42
2021-10-23T11:56:42
168,662,418
20
19
null
2021-01-24T07:31:58
2019-02-01T07:57:21
R
UTF-8
R
false
false
60,950
r
dtedit.R
#' Create a DataTable with Add, Edit and Delete buttons. #' #' dtedit - editable DataTable #' #' \code{dtedit} is used in conjunction with \code{uiOutput} to create editable datatables. #' \code{dtedit} is used in a shiny application's server definition, \code{uiOutput} is used #' in the UI (user interface) definition. #' #' @param input Shiny input object passed from the server. #' @param output Shiny output object passed from the server. #' @param name (\code{name} is available in \code{dtedit} only). The \code{name} of the #' outputted editable datatable. The \code{name} passed to \code{dtedit} is the same #' as the name passed to \code{uiOutput}. Put \code{uiOutput(name)} where you want the #' editable datatable in the \code{ui.R}. When using more than one \code{dtedit} within a Shiny #' application the name must be unique. (\code{name} is converted #' to the \code{session} argument of dteditmod.) #' @param ... \code{dtedit} passes options to \code{dteditmod}, #' re-labelling \code{name} to \code{session}. #' Extra options not defined by \code{dteditmod} are passed to \code{DT::renderDataTable}. #' #' @family Datatable Edit functions #' @seealso #' #' \itemize{ #' \item \code{example("dtedit")} a simple example. #' \item \code{dtedit_demo()} demonstration of dtedit. #' \item \code{dtedit_reactive_demo()} reactive dataframe #' \item \code{dtedit_selectInputReactive_demo()} reactive selectInput #' } #' #' @example inst/examples/example.R #' #' @export dtedit <- function(input, output, name, thedata, ...) { dteditmod(input, output, session = name, thedata = thedata, ...) } #' Create a DataTable with Add, Edit and Delete buttons. #' #' dteditmod - editable DataTable, adapted for use in modules #' #' \code{dteditmod} is used in conjunction with \code{callModule} and #' \code{dteditmodUI} to create editable datatables in a module environment. #' \code{dteditmod} is called through \code{callModule} in the 'server' section of #' the shiny application. #' \code{dteditmodUI} is called in the 'UI' (user-interface) section of the shiny app. #' #' This object will maintain data state. However, in order for data to persist #' between Shiny instances, data needs to be saved to an external format (e.g. #' database or R data file). The callback functions provide a mechanism for this #' function to interact with a permanent data storage scheme. The callback #' functions are called when the user adds, updates, or deletes a row from the #' data table. The callback must accept two parameters: \code{data} and \code{row}. #' For inserting and updating, the \code{data} object is the current state of #' data table including any additions or updates. The \code{row} parameter indicates #' which row from \code{data} was modified (or added). For deletions, however, #' the \code{data} represents the data table just before deleting the specified #' row. That is, if \code{callback.delete} returns a \code{data.frame}, that will #' be the new data table; otherwise this function will remove row \code{row} from #' \code{data} and that will become the current data table. #' #' While `olddata` will contain values as contained in the original `data.frame`, #' the values returned in `data` are limited to values that can be returned by the #' `shiny` widgets underlying the `input.types`. For example, the `textInput` can #' return an empty string, but cannot return `NA`. #' #' The callback functions may throw errors (see e.g. \code{stop}) if there are #' problems with data. That is, if data validation checks indicate data problems #' before inserting or updating a row the function may throw an error. Note that #' the error message will be presented to the user so providing messages #' meaningful to the user is recommended. Moreover, if an error is thrown, the #' modal dialog is not dismissed and the user can further edit the data and #' retry the insertion or update. #' #' Callback functions may return a \code{data.frame}. When a \code{data.frame} is #' returned that will become the current state of the data table. If anything #' else is returned then the internal \code{data.frame} will be used. #' #' @md #' #' @return Returns reactiveValues #' * `theData` - the current state of `DTedit`'s copy of the data #' * `view.cols` #' * `edit.cols` #' * `edit.count` - number of edits to data done within `DTedit` (does not #' include changes to `DTedit`'s copy of the data secondary to changes #' of a reactive `thedata`) #' * `rows_selected` - the row number selected. initially set to `NULL` #' #' @param input Shiny input object passed from the server. #' @param output Shiny output object passed from the server. #' @param session Shiny session object (an environment) passed from the server. #' Alternatively, the 'name' (character) of the outputted editable datatable. #' @param thedata a data frame to view and edit. can be a reactive #' @param view.cols character vector with the column names to show in the DataTable. #' This can be a subset of the full \code{data.frame}. #' @param edit.cols character vector with the column names the user can edit/add. #' This can be a subset of the full \code{data.frame}. #' @param edit.label.cols character vector with the labels to use on the edit #' and add dialogs. The length and order of \code{code.cols.labels} must #' correspond to \code{edit.cols}. #' @param delete.info.cols character vector with the column names specifying #' which values are presented on the delete dialog. #' This can be a subset of the full \code{data.frame}. Defaults to \code{view.cols}. #' If \code{NULL}, no data values are shown on the delete dialog. #' @param delete.info.label.cols character vector with the labels to use on the delete #' dialog. The length and order of \code{delete.info.label.cols} must #' correspond to \code{delete.info.cols}. #' @param input.types a character vector where the name corresponds to a column #' in \code{edit.cols} and the value is the input type. Possible values #' are: #' #' * `dateInput` - input changed by `date.width` #' * `datetimeInput` - input changed by `datetime.width`. needs #' `useairDatepicker` set to `TRUE` and requires package `shinyWidgets`. #' * `selectInput` - choices determined by `input.choices`, #' or the levels of the data column #' variable (if the column variable is of class `factor`), #' or the already present values in the data column. #' * `selectizeInput` - use selectize version of `selectInput`. Options #' defined by `selectize.options`. #' * `selectInputMultiple` - choices determined by #' `input.choices` or the already present values in the data #' column. #' * `selectizeInputMultiple` - use selectize version of `selectInputMultiple`. #' Options defined by `selectize.options` #' * `selectInputReactive` - choices determined by a reactive #' variable, as defined by `input.choices` and #' `input.choices.reactive`. #' * `selectizeInputReactive` - selectize version of `selectInputReactive`. #' Options defined by `selectize.options` #' * `selectInputMultipleReactive` - choices determined by a #' reactive variable, as defined by `input.choices` and #' `input.choices.reactive` #' * `selectizeInputMultipleReactive` - selectize version of `selectInputReactive`. #' Options defined by `selectize.options` #' * `numericInput` - input changed by `numeric.width` #' * `textInput` - input changed by `text.width` #' * `textAreaInput` - input changed by `textarea.width` and `textarea.height` #' * `passwordInput` #' * `fileInput` - type of acceptable file types is defined by #' `input.choices`. Maximum file length is modifed by #' `max.fileInputLength` #' * `checkboxInput`- input changed by `checkbox.width` #' #' One case where this parameter is desirable is when a text #' area is required instead of a simple text input. #' #' @param input.choices a list of character vectors. The names of each element #' in the list must correspond to a column name in the data. The value, #' a character vector, are the options presented to the user for data entry, #' in the case of input type \code{selectInput}). #' #' In the case of input type `selectInputReactive` #' or `selectInputMultipleReactive`, the value is the name #' of the reactive in 'input.choices.reactive' #' #' In the case of input type `fileInput` this is the #' 'accept' argument, which specifies the type of file which #' is acceptable. Can be a case insensitive file extension #' (e.g. '.csv' or '.rds') or a MIME type (e.g. 'text/plain' or #' 'application/pdf'). #' @param input.choices.reactive a named list of reactives, referenced in #' `input.choices` to use for input type \code{selectInputReactive} or #' \code{selectInputMultipleReactive}. The reactive itself is a character #' vector. #' @param selectize.options options for `selectizeInput`. By default, the options #' defined apply to all selectize inputs. However, selectize.options is a named #' list of lists, where each list is named after an editable selectize-style #' column, then the named lists are individualized options lists for each #' selectize-style column. #' @param inputEvent a named list of functions. The names of each element in #' the list must correspond to an editable column name in the data. The #' function is called when the associated input widget event is observed #' during editing/adding a data row. Can be used, for example, #' with `shinyFeedback`. The functions need to accept two parameters, #' the inputID of the input widget, and the value of that widget. #' @param action.buttons a named list of action button columns. #' Each column description is a list of \code{columnLabel}, \code{buttonLabel}, #' \code{buttonPrefix}, \code{afterColumn}. #' * \code{columnLabel} label used for the column. #' * \code{buttonLabel} label used for each button #' * \code{buttonPrefix} used as the prefix for action button IDs. #' The suffix will be a number from '1' to the number of rows. #' Prefix and suffix will be separated with an underscore '_'. #' * \code{afterColumn} if provided, the action button column is #' placed after this named column. #' @param selectize Whether to use `selectize.js` or not for `selectInputMultiple` #' or `selectInputMultipleReactive`. See \code{shiny::\link{selectInput}} for #' more information. #' @param defaultPageLength number of rows to show in the data table by default. #' @param modal.size the size of the modal dialog. See \code{\link{modalDialog}}. #' @param text.width width of text inputs. #' @param textarea.width the width of text area inputs. #' @param textarea.height the height of text area inputs. #' @param date.width the width of data inputs #' @param datetime.width the width of datetime inputs #' @param numeric.width the width of numeric inputs. #' @param select.width the width of drop down inputs. #' @param checkbox.width the width of checkbox inputs. #' @param max.fileInputLength the maximum length (in bytes) of \code{fileInput}. #' Shiny itself has a default limit of 5 megabytes per file. #' The limit can be modified by using shiny.maxRequestSize option. #' @param title.delete the title of the dialog box for deleting a row. #' @param title.edit the title of the dialog box for editing a row. #' @param title.add the title of the dialog box for inserting a new row. #' @param label.delete the label of the delete button. #' @param label.edit the label of the edit button. #' @param label.add the label of the add button. #' @param label.copy the label of the copy button. #' @param label.save the label of the save button. #' @param label.cancel the label of the cancel button. #' @param icon.delete the icon for the delete button, e.g. \code{icon("trash")}. #' Defaults to \code{NULL}. #' @param icon.edit the icon for the edit button, e.g. \code{icon("edit")}. #' Defaults to \code{NULL}. #' @param icon.add the icon for the add button, e.g. \code{icon("plus")}. #' Defaults to \code{NULL}. #' @param icon.copy the icon for the copy button, e.g. \code{icon("copy")}. #' Defaults to \code{NULL}. #' @param text.delete.modal the text shown in the delete modal dialog. #' @param show.delete whether to show/enable the delete button. #' @param show.update whether to show/enable the update button. #' @param show.insert whether to show/enable the insert button. #' @param show.copy whether to show/enable the copy button. #' @param callback.delete a function called when the user deletes a row. #' This function should return an updated data.frame. #' @param callback.update a function called when the user updates a row. #' This function should return an updated data.frame. #' @param callback.insert a function called when the user inserts a new row. #' This function should return an updated data.frame. #' @param callback.actionButton a function called when the user clicks an action button. #' called with arguments `data`, `row` and `buttonID`. #' This function can return an updated data.frame, #' alternatively return NULL if data is not to be changed. #' @param click.time.threshold This is to prevent duplicate entries usually by #' double clicking the save or update buttons. If the user clicks the save #' button again within this amount of time (in seconds), the subsequent click #' will be ignored (using `shiny::throttle`). Set to zero to disable this #' feature. #' @param useairDatepicker use `shinyWidgets` package `airDatepickerInput` #' @param datatable.options options passed to \code{DT::renderDataTable}. #' See \url{https://rstudio.github.io/DT/options.html} for more information. #' @param datatable.rownames show rownames as part of the datatable? `TRUE` or `FALSE`. #' Note that if datatable.call includes `DT::format*` calls, #' then `datatable.rownames` must equal `TRUE` #' @param datatable.call pre-processing call when calling `DT::renderDataTable`. #' Can be defined, for example, to include `DT::format*` calls. #' `dtedit` will pass several arguments to the `datatable.call` function. #' * `data` a dataframe. may have been processed to add `actionButtons` #' * `options` - `datatable.options` #' * `rownames` - `datatable.rownames` #' * `escape` - escape all columns except those with action buttons. #' * `selection` - `single` #' @param ... arguments not recognized by DTedit are passed to \code{DT::renderDataTable} #' By default, `datatable.call` uses `DT::dataframe`, so this limits the options that #' can be passed through this method. #' #' @seealso #' #' \itemize{ #' \item \code{\link{dteditmodUI}} : the companion user-interface function for \code{dteditmod}.\cr #' \item \code{example("dteditmodUI")} a simple module example with reactive dataframe #' \item \code{dteditmod_demo()} a more complex module example. Database interaction #' and interactions between the data of multiple datatables. #' \item \code{dteditmod_fileInput_demo()} a modular example including binary file input and action buttons. #' } #' #' @rdname dtedit #' #' @example inst/examples/example_mod.R #' #' @export dteditmod <- function(input, output, session, thedata, view.cols = names( shiny::isolate( if (shiny::is.reactive(thedata)) { thedata() } else { thedata } ) ), edit.cols = names( shiny::isolate( if (shiny::is.reactive(thedata)) { thedata() } else { thedata } ) ), edit.label.cols = edit.cols, delete.info.cols = view.cols, delete.info.label.cols = delete.info.cols, input.types, input.choices = NULL, input.choices.reactive = NULL, selectize.options = NULL, inputEvent = NULL, action.buttons = NULL, selectize = TRUE, modal.size = "m", text.width = "100%", textarea.width = "570px", textarea.height = "200px", date.width = "100px", datetime.width = "200px", numeric.width = "100px", select.width = "100%", checkbox.width = "100%", defaultPageLength = 10, max.fileInputLength = 100000000, title.delete = "Delete", title.edit = "Edit", title.add = "New", label.delete = "Delete", label.edit = "Edit", label.add = "New", label.copy = "Copy", label.save = "Save", label.cancel = "Cancel", icon.delete = NULL, icon.edit = NULL, icon.add = NULL, icon.copy = NULL, text.delete.modal = "Are you sure you want to delete this record?", show.delete = TRUE, show.update = TRUE, show.insert = TRUE, show.copy = TRUE, callback.delete = function(data, row) { }, callback.update = function(data, olddata, row) { }, callback.insert = function(data, row) { }, callback.actionButton = function(data, row, buttonID) { }, click.time.threshold = 0.5, # in seconds useairDatepicker = FALSE, datatable.options = list(pageLength = defaultPageLength), datatable.rownames = FALSE, datatable.call = function(...) {DT::datatable(...)}, ...) { if (!missing(session) && is.environment(session)) { # the function has been called as a module ns <- session$ns name <- "editdt" moduleMode <- TRUE # in 'module' mode } else if (is.character(session)) { # the function has not been called as a module # and 'session' is a character string, # then 'session' is the 'name' of the output name <- session ns <- function(x) return(x) # 'ns' becomes a 'change nothing' function moduleMode <- FALSE # not in 'module' mode } thedataCopy <- if (shiny::is.reactive(shiny::isolate(thedata))) { shiny::isolate(thedata()) } else { thedata } # if a reactive has been passed, obtain the value # Some basic parameter checking if (!is.data.frame(thedataCopy) || ncol(thedataCopy) < 1) { stop("Must provide a data frame with at least one column.") } else if (length(edit.cols) != length(edit.label.cols)) { stop("edit.cols and edit.label.cols must be the same length.") } else if (length(delete.info.cols) != length(delete.info.label.cols)) { stop("delete.info.cols and delete.info.label.cols must be the same length.") } else if (!all(view.cols %in% names(thedataCopy))) { stop("Not all view.cols are in the data.") } else if (!all(edit.cols %in% names(thedataCopy))) { stop("Not all edit.cols are in the data.") } else if (!all(delete.info.cols %in% names(thedataCopy))) { stop("Not all delete.info.cols are in the data.") } DataTableName <- paste0(name, "dt") result <- shiny::reactiveValues() result$thedata <- thedataCopy result$view.cols <- view.cols result$edit.cols <- edit.cols result$edit.count <- 0 # number of edits (Add/Delete/Edit/Copy) through dtedit result$rows_selected <- NULL # no row selected initially dt.proxy <- DT::dataTableProxy(DataTableName) selectInputMultiple <- function(...) { shiny::selectInput(multiple = TRUE, selectize = selectize, ...) } selectizeInputMultiple <- function(...) { shiny::selectizeInput(multiple = TRUE, ...) } valid.input.types <- c( "dateInput", "datetimeInput", "selectInput", "selectizeInput", "numericInput", "textInput", "textAreaInput", "passwordInput", "selectInputMultiple", "selectizeInputMultiple", "selectInputReactive", "selectizeInputReactive", "selectInputMultipleReactive","selectizeInputMultipleReactive", "fileInput", "checkboxInput" ) # data.frames are coerced to unnamed vectors when selecting a single column using thedataCopy[, edit.cols] # therefore, use the subset-function to avoid errors: inputTypes <- sapply(subset(thedataCopy, select=edit.cols), FUN = function(x) { switch(class(x)[[1]], list = "selectInputMultiple", character = "textInput", Date = "dateInput", POSIXct = "datetimeInput", factor = "selectInput", integer = "numericInput", numeric = "numericInput", blob = "fileInput", logical = "checkboxInput" ) }) if ("datetimeInput" %in% inputTypes && !useairDatepicker) { # standard dateInput does not have a time picker stop ( "'datetimeInput', or POSIXct types, are not available if 'useairDatepicker' is set to false." ) } if (!missing(input.types)) { if (!all(names(input.types) %in% edit.cols)) { stop( "input.types column not a valid editing column: ", paste0(names(input.types)[!names(input.types) %in% edit.cols]) ) } if (!all(input.types %in% valid.input.types)) { stop(paste0( "input.types must only contain values of: ", paste0(valid.input.types, collapse = ", ") )) } inputTypes[names(input.types)] <- input.types } # Convert any list columns to characters before displaying for (i in seq_len(ncol(thedataCopy))) { if (nrow(thedataCopy) == 0) { thedataCopy[, i] <- character() } else if (is.list(thedataCopy[, i])) { thedataCopy[, i] <- sapply(thedataCopy[, i], FUN = function(x) { paste0(x, collapse = ", ") }) } } addActionButtons <- function(data, action.buttons) { # data : dataframe # action.buttons : named list of lists # each list contains # $columnLabel - the name of the created column # $buttonLabel - the label to use for each button # $buttonPrefix - the prefix of the button ID # the suffix is a number # $afterColumn - (optional) # the name of the column after which created column is placed # returns list # $dataframe # $button.colNames - the column names of the action buttons # create a vector of shiny inputs # of length 'len' # input IDs have prefix 'id', a numeric suffix from '1' to 'len' # separated by an underscore '_' shinyInput <- function(FUN, len, id, ...) { inputs <- character(len) for (i in seq_len(len)) { inputs[i] <- as.character(FUN(paste0(id, "_", i), ...)) } return(inputs) } # https://stackoverflow.com/questions/45739303/ # r-shiny-handle-action-buttons-in-data-table # https://stackoverflow.com/questions/57969103/ # how-to-use-shiny-action-button-in-datatable-through-shiny-module # https://community.rstudio.com/t/ # how-to-use-shiny-action-button-in-datatable-through-shiny-module/39998 # if used in a module environment, usage looks like : # Actions = shinyInput( # actionButton, 5, # 'button', # label = "Fire", # onclick = paste0('Shiny.setInputValue(\"' , # ns("select_button"), # '\", this.id, {priority: \"event\"})') # ) view.cols.andButtons <- names(data) # used to store the order of columns # by default, view columns 'and buttons' are the same as view.cols button.colNames <- NULL # later will store vector of button column names if (!is.null(action.buttons)) { for (i in action.buttons) { button.colNames <- append(button.colNames, i$columnLabel) data[, i$columnLabel] <- shinyInput( shiny::actionButton, nrow(data), i$buttonPrefix, label = i$buttonLabel, onclick = paste0( 'Shiny.setInputValue(\"', ns("select_button"), '\", this.id, {priority: \"event\"})' ) ) if (is.null(i$afterColumn)) { # this button column has no defined position, # so place at end of view column vector view.cols.andButtons <- append( view.cols.andButtons, i$columnLabel ) } else { # this button column has a defined position view.cols.andButtons <- append( view.cols.andButtons, i$columnLabel, after = which(view.cols.andButtons == i$afterColumn) ) } } } data <- data[, view.cols.andButtons, drop = FALSE] # re-order columns as necessary # drop = FALSE necessary to stop converting single column # data-frame to a vector return(list(data = data, button.colNames = button.colNames)) } thedataWithButtons <- addActionButtons( thedataCopy[, view.cols, drop = FALSE], action.buttons ) # was "thedata[,view.cols]", but requires drop=FALSE # to prevent return of vector (instead of dataframe) # if only one column in view.cols output[[DataTableName]] <- DT::renderDataTable({ datatable.call( data = thedataWithButtons$data, options = datatable.options, rownames = datatable.rownames, escape = which( !names(thedataWithButtons$data) %in% thedataWithButtons$button.colNames ), # 'escaped' columns are those without HTML buttons etc. # escape the 'data' columns # but do not escape the columns which # have been created by addActionButtons() selection = "single" ) }, server = TRUE, ... ) outputOptions(output, DataTableName, suspendWhenHidden = FALSE) # without turning off suspendWhenHidden, changes are # not rendered if containing tab is not visible # if a row is selected in the dataframe named in 'DataTableName' # then set result$rows_selected to that row # this will be returned to the caller shiny::observeEvent( input[[paste0(DataTableName, "_rows_selected")]], { result$rows_selected <- input[[paste0(DataTableName, "_rows_selected")]] }) getFields <- function(typeName, values) { # creates input fields when adding or editing a row # 'typeName' is either '_add_' or '_edit_' # 'values' are current values of the row # (if already existing, or being copied) # if adding a 'new' row, then 'values' will be 'missing' # # returns a list of shiny inputs, 'fields' if (grepl("selectize", inputTypes) && !is.null(selectize.options)) { # if *any* of the selectize input-type variants in the inputTypes # and selectize.options is actually defined # # then are the selectize.options applied to *all* the selectize input # types, or are they individually defined? selectize_individual <- TRUE # by default, assume individually defined edit.cols.selectize <- edit.cols[grepl("selectize", inputTypes)] # the editable columns which are 'selectize' variants for (i in names(selectize.options)) { if (i == "" || !(i %in% edit.cols)) { # to be individually defined each item in selectize.options must be # 1. named 2. same name as in the editable columns selectize_individual <- FALSE } else if (!is.list(selectize.options[[i]])) { # to be individually defined each item in selectize.options must be # *also* be a list selectize_individual <- FALSE } } } else { selectize_individual <- FALSE } fields <- list() for (i in seq_along(edit.cols)) { if (inputTypes[i] == "dateInput") { value <- ifelse(missing(values), as.character(Sys.Date()), as.character(values[, edit.cols[i]]) ) if (!useairDatepicker) { fields[[i]] <- shiny::dateInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], value = value, width = date.width ) } else { fields[[i]] <- shinyWidgets::airDatepickerInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], value = value, timepicker = FALSE, addon = "none", width = date.width ) } } else if (inputTypes[i] == "datetimeInput") { # note that this uses shinyWidgets::airDatepickerInput value <- ifelse(missing(values), as.character(Sys.time()), as.character(values[, edit.cols[i]]) ) fields[[i]] <- shinyWidgets::airDatepickerInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], value = value, timepicker = TRUE, addon = "none", width = datetime.width ) } else if (inputTypes[i] == "selectInputMultiple" || inputTypes[i] == "selectizeInputMultiple") { value <- ifelse(missing(values), "", values[, edit.cols[i]]) if (is.list(value)) { value <- value[[1]] } choices <- "" if (!is.null(input.choices) && edit.cols[i] %in% names(input.choices)) { choices <- input.choices[[edit.cols[i]]] } else if (nrow(result$thedata) > 0) { choices <- unique(unlist(result$thedata[, edit.cols[i]])) # no choices explicitly defined # # use choices defined in other rows, if available # this is a bad choice. even if a column starts # with just 'Yes/No', it is quite possible that with # further table editing valid choices will become # unavailable if, after editing, no rows have that valid choice warning(paste0( "No choices explicitly defined for ", edit.cols[i], ". Specify them using the input.choices parameter" )) } if (length(choices) == 1 && choices[[1]] == "") { warning(paste0( "No choices available for ", edit.cols[i], ". Specify them using the input.choices parameter" )) } if (inputTypes[i] == "selectInputMultiple") { fields[[i]] <- selectInputMultiple( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], choices = choices, selected = value, width = select.width ) } else if (inputTypes[i] == "selectizeInputMultiple") { if (selectize_individual) { selectize.option <- selectize.options[[edit.cols[[i]]]] # selectize.options are individually defined for # each 'selectizeInput' } else { selectize.option <- selectize.options # only one (unnamed) options list for selectizeInput } fields[[i]] <- selectizeInputMultiple( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], choices = choices, selected = value, width = select.width, options = selectize.option ) } } else if (inputTypes[i] == "selectInput" || inputTypes[i] == "selectizeInput") { value <- ifelse( missing(values), "", as.character(values[, edit.cols[i]]) ) if (is.list(value)) { value <- value[[1]] } choices <- "" if (!is.null(input.choices) && edit.cols[i] %in% names(input.choices)) { choices <- input.choices[[edit.cols[i]]] } else if (is.factor(result$thedata[, edit.cols[i]])) { choices <- levels(result$thedata[, edit.cols[i]]) } else if (nrow(result$thedata) > 0) { choices <- unique(unlist(result$thedata[, edit.cols[i]])) # no choices explicitly defined # # use choices defined in other rows, if available # this is a bad choice. even if a column starts # with just 'Yes/No', it is quite possible that with # further table editing valid choices will become # unavailable if, after editing, no rows have that valid choice warning(paste0( "No choices explicitly defined for ", edit.cols[i], ". Specify them using the input.choices parameter" )) } if (length(choices) == 1 && choices[[1]] == "") { warning(paste0( "No choices available for ", edit.cols[i], ". Specify them using the input.choices parameter" )) } if (inputTypes[i] == "selectInput") { fields[[i]] <- shiny::selectInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], choices = choices, selected = value, width = select.width ) } else if (inputTypes[i] == "selectizeInput") { if (selectize_individual) { selectize.option <- selectize.options[[edit.cols[[i]]]] # selectize.options are individually defined for # each 'selectizeInput' } else { selectize.option <- selectize.options # only one (unnamed) options list for selectizeInput } fields[[i]] <- shiny::selectizeInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], choices = choices, selected = value, width = select.width, options = selectize.option ) } } else if (inputTypes[i] == "selectInputMultipleReactive" || inputTypes[i] == "selectizeInputMultipleReactive") { value <- ifelse(missing(values), "", values[, edit.cols[i]]) if (is.list(value)) { value <- value[[1]] } choices <- NULL if (!is.null(input.choices.reactive)) { if (edit.cols[i] %in% names(input.choices)) { choices <- input.choices.reactive[[input.choices[[edit.cols[i]]]]]() # it is the responsiblity of the # calling functions/reactive variable handlers # that the list of choices includes all CURRENT choices # that have already been chosen in the data. } } if (is.null(choices)) { warning(paste0( "No choices available for ", edit.cols[i], ". ", "Specify them using the input.choices and ", "input.choices.reactive parameter" )) } if (inputTypes[i] == "selectInputMultipleReactive") { fields[[i]] <- selectInputMultiple( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], choices = choices, selected = value, width = select.width ) } else if (inputTypes[i] == "selectizeInputMultipleReactive") { if (selectize_individual) { selectize.option <- selectize.options[[edit.cols[[i]]]] # selectize.options are individually defined for # each 'selectizeInput' } else { selectize.option <- selectize.options # only one (unnamed) options list for selectizeInput } fields[[i]] <- selectizeInputMultiple( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], choices = choices, selected = value, width = select.width, options = selectize.option ) } } else if (inputTypes[i] == "selectInputReactive" || inputTypes[i] == "selectizeInputReactive") { value <- ifelse( missing(values), "", as.character(values[, edit.cols[i]]) ) choices <- NULL if (!is.null(input.choices.reactive)) { if (edit.cols[i] %in% names(input.choices)) { choices <- input.choices.reactive[[input.choices[[edit.cols[i]]]]]() # it is the responsiblity of # the calling functions/reactive variable handlers # that the list of choices includes all CURRENT choices # that have already been chosen in the data. } } if (is.null(choices)) { warning(paste0( "No choices available for ", edit.cols[i], ". ", "Specify them using the input.choices and ", "input.choices.reactive parameter" )) } if (inputTypes[i] == "selectInputReactive") { fields[[i]] <- shiny::selectInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], choices = choices, selected = value, width = select.width ) } else if (inputTypes[i] == "selectizeInputReactive") { if (selectize_individual) { selectize.option <- selectize.options[[edit.cols[[i]]]] # selectize.options are individually defined for # each 'selectizeInput' } else { selectize.option <- selectize.options # only one (unnamed) options list for selectizeInput } fields[[i]] <- shiny::selectizeInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], choices = choices, selected = value, width = select.width, options = selectize.option ) } } else if (inputTypes[i] == "numericInput") { value <- ifelse(missing(values), 0, values[, edit.cols[i]]) fields[[i]] <- shiny::numericInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], value = value, width = numeric.width ) } else if (inputTypes[i] == "textAreaInput") { value <- ifelse(missing(values), "", values[, edit.cols[i]]) fields[[i]] <- shiny::textAreaInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], value = value, width = textarea.width, height = textarea.height ) } else if (inputTypes[i] == "textInput") { value <- ifelse(missing(values), "", values[, edit.cols[i]]) fields[[i]] <- shiny::textInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], value = value, width = text.width ) } else if (inputTypes[i] == "passwordInput") { value <- ifelse(missing(values), "", values[, edit.cols[i]]) fields[[i]] <- shiny::passwordInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], value = value, width = text.width ) } else if (inputTypes[i] == "fileInput") { # current value(if not 'missing') is actually irrelevant! # will always present a file selector fields[[i]] <- shiny::fileInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], accept = input.choices[[edit.cols[i]]] # acceptable file input choices # e.g. case insensitive file extension '.csv' # MIME types "text/plain" ) } else if (inputTypes[i] == "checkboxInput") { value <- ifelse(missing(values), FALSE, values[, edit.cols[i]]) value <- ifelse(is.na(value), FALSE, value) fields[[i]] <- shiny::checkboxInput( ns(paste0(name, typeName, edit.cols[i])), label = edit.label.cols[i], value = value, width = checkbox.width ) } else { stop("Invalid input type!") } } return(fields) } output[[paste0(name, "_message")]] <- shiny::renderUI("") updateData <- function(proxy, data, ...) { # updates data displayed in DT datatable # # will reference 'global' action.buttons variable # when callling function 'addActionButtons' # Convert any list columns to characters before displaying for (i in seq_len(ncol(data))) { if (is.list(data[, i])) { data[, i] <- as.character(sapply(data[, i], FUN = function(x) { paste0(x, collapse = ", ") })) # convert to as.character, because if data[,i] is empty, # sapply can return an empty list # cannot assign empty list() to data[,i], because that # causes data[,i] column to be deleted! } } DT::replaceData(proxy, addActionButtons(data, action.buttons)$data, ...) result$rows_selected <- NULL # no row selected after each edit } ##### inputEvent observeEvent helper #################################### inputEvent_object <- R6::R6Class("inputEvent_object", list( handles = NULL, # list of observeEvents initialize = function(input_infix) { # parameters : input_infix e.g. "_add", or "_edit" # creates observeEvents watching the edit/add input widgets # e.g. to use package 'shinyFeedback' # for edit.cols with functions defined in parameter 'inputEvent' # # stores the observeEvents in self$handler # (so they can be later destroyed) # self$handles <- lapply( X = edit.cols[ grepl( paste(paste0('^', names(inputEvent), '$'), collapse = "|"), # enforce exact pattern matching with '^' and '$' # otherwise can match subsets, including NULL (!!!) edit.cols )], # choose only edit.cols which are defined in 'inputEvent' FUN = function(x) { input_name <- paste0(name, input_infix, "_", x) observeEvent(input[[input_name]], { inputEvent[[x]](input_name, input[[input_name]]) # sends two parameters - the inputID and the input value # # unfortunately, could not easily just send the inputID alone # for the inputEvent function to refer to the value by input[[input_name]] # # input[[input_name]] for the defined inputEvent function *does* work # in the simple case # # however, if dtedit is called in dteditmod (module) mode, # the function's enclosing environment (where it was defined) # might need to *additionally* prefix the input_name with the # dtedit module ID # # calling session$ns(input_name) from within dteditmod results in adding the # dteditmod module ID and, IF the calling function is *also* a # module, adding the module ID of the calling function ('fully # specified' name). Unfortunately, if the calling function is # a module then the fully specified name is not easily used from # within the inputEvent function! # e.g. I could only access with ... unlist(input)$impl$get(x) !!! }) } ) }, finalize = function() { # remove the observeEvents, if they exist # otherwise, when the modal dialog closes, observeEvents will accumulate if (!is.null(self$handles)) { lapply( X = self$handles, FUN = function(x) { x$destroy() } ) self$handles <- NULL } } )) inputEvent_handles <- NULL # will be used by the functions which call inputEvent_handler ##### Insert functions ##################################################### observeEvent(input[[paste0(name, "_add")]], { # if the 'Add' button is clicked then # the 'addModal' popup is generated, with 'missing' values if (!is.null(row)) { shiny::showModal(addModal()) inputEvent_handles <<- inputEvent_object$new("_add") } }) addModal <- function(row, values) { # 'addModal' popup is generated when # the '_add' button event is observed (with missing 'values') # the '_copy' button event is observed (with prefilled 'values') # # other than being closed/cancelled # the 'addModal' popup can create an '_insert' event output[[paste0(name, "_message")]] <- shiny::renderUI("") fields <- getFields("_add_", values) shiny::modalDialog( title = title.add, shiny::div( shiny::htmlOutput( ns(paste0(name, "_message")) ), style = "color:red" ), fields, footer = shiny::column( shiny::actionButton(ns(paste0(name, "_insert_cancel")), label.cancel), shiny::actionButton(ns(paste0(name, "_insert")), label.save), width = 12 ), size = modal.size ) } observeEvent(input[[paste0(name, "_insert_cancel")]], { # the '_cancel' event is observed from the 'addModal' popup inputEvent_handles$finalize() # remove the observeEvents shiny::removeModal() # close the modal without saving }) insert_event <- shiny::reactive({input[[paste0(name, "_insert")]]}) insert_event_t <- shiny::throttle(insert_event, click.time.threshold * 1000) # '_insert' event generated from the 'addModal' popup # 'throttled' version of insert button observeEvent(insert_event_t(), { newdata <- as.data.frame(result$thedata) # coerce to dataframe # class(newdata[,i])[[1]] does not work if newdata is a tibble row <- nrow(newdata) + 1 # the new row number new_row <- list() # to contain a 'blank' new row # the following loop can be tested on the following dataframes # data.frame(a = character(), b = numeric(), # x = as.Date(numeric(), origin = "1970-01-01"), y = raw()) # data.frame(a = "a", b = 7, # x = as.Date(NA, origin = "1970-01-01"), y = raw(1)) # 'raw(1)' can be changed to as.blob(raw(0)) # but as.blob can't be used to create a NULL blob object! for (i in seq_len(ncol(newdata))) { new_row[[i]] <- switch( class(newdata[, i])[[1]], "factor" = as.factor(NA), "Date" = as.Date(NA, origin = "1970-01-01"), "raw" = list(blob::as.blob(raw(1))), "blob" = list(blob::as.blob(raw(1))), "character" = as.character(NA), "numeric" = as.numeric(NA), "POSIXct" = as.POSIXct(NA), "AsIs" = as.list(NA), # for lists "logical" = as.logical(NA), methods::as(NA, class(newdata[, i])[[1]])) } newdata[row, ] <- data.frame(new_row, stringsAsFactors = FALSE) # create a new empty row, compatible with blob columns # the new row is ready for filling for (i in edit.cols) { if (inputTypes[i] %in% c("selectInputMultiple", "selectizeInputMultiple", "selectInputMultipleReactive", "selectizeInputMultipleReactive")) { newdata[[i]][row] <- list(input[[paste0(name, "_add_", i)]]) } else if (inputTypes[i] == "fileInput") { # file read into binary blob datapath <- input[[paste0(name, "_add_", i)]]$datapath if (!is.null(datapath)) { newdata[[i]][row] <- blob::blob( readBin( datapath, what = "raw", n = max.fileInputLength ) ) } } else { newdata[row, i] <- input[[paste0(name, "_add_", i)]] } } tryCatch({ callback.data <- callback.insert(data = newdata, row = row) if (!is.null(callback.data) && is.data.frame(callback.data)) { result$thedata <- callback.data } else { result$thedata <- newdata } updateData(dt.proxy, result$thedata[, view.cols, drop = FALSE], # was "result$thedata[,view.cols]", # but that returns vector if view.cols is a single column rownames = datatable.rownames ) result$edit.count <- result$edit.count + 1 inputEvent_handles$finalize() # remove the observeEvents shiny::removeModal() return(TRUE) }, error = function(e) { output[[paste0(name, "_message")]] <<- shiny::renderUI(shiny::HTML(geterrmessage())) return(FALSE) }) }) ##### Copy functions ####################################################### observeEvent(input[[paste0(name, "_copy")]], { # if '_copy' event is observed, call the 'addModal' popup # with pre-filled values # (the same 'addModal' popup is used with missing values for '_insert') row <- input[[paste0(name, "dt_rows_selected")]] if (!is.null(row)) { if (row > 0) { shiny::showModal(addModal(values = result$thedata[row, , drop = FALSE])) inputEvent_handles <<- inputEvent_object$new("_add") # shares the same input names as '_add' } } }) ##### Update functions ##################################################### observeEvent(input[[paste0(name, "_edit")]], { # if '_edit' event is observed, call the 'editModal' popup row <- input[[paste0(name, "dt_rows_selected")]] if (!is.null(row) && row > 0) { shiny::showModal(editModal(row)) inputEvent_handles <<- inputEvent_object$new("_edit") } }) editModal <- function(row) { # 'editModal' popup created when '_edit' event is observed # # other than being closed/cancelled, the 'editModal' popup # can also be closed when the '_update' event is observed output[[paste0(name, "_message")]] <- renderUI("") fields <- getFields("_edit_", values = result$thedata[row, , drop = FALSE]) shiny::modalDialog( title = title.edit, shiny::fluidPage( shiny::div( if (datatable.rownames) # rownames are being displayed shiny::h4(rownames(thedata)[row]) ), shiny::div( shiny::htmlOutput( ns(paste0(name, "_message"))), style = "color:red"), fields ), footer = column( shiny::actionButton(ns(paste0(name, "_update_cancel")), label.cancel), shiny::actionButton(ns(paste0(name, "_update")), label.save), width = 12 ), size = modal.size ) } observeEvent(input[[paste0(name, "_update_cancel")]], { # the '_cancel' event is observed from the 'editModal' popup inputEvent_handles$finalize() # remove the observeEvents shiny::removeModal() # close the modal without saving }) update_event <- shiny::reactive({input[[paste0(name, "_update")]]}) update_event_t <- shiny::throttle(update_event, click.time.threshold * 1000) # the '_update' event is observed from the 'editModal' popup # throttled version of 'update' button observeEvent(update_event_t(), { row <- input[[paste0(name, "dt_rows_selected")]] if (!is.null(row) && row > 0) { newdata <- result$thedata for (i in edit.cols) { if (inputTypes[i] %in% c("selectInputMultiple", "selectizeInputMultiple", "selectInputMultipleReactive", "selectizeInputMultipleReactive")) { newdata[[i]][row] <- list(input[[paste0(name, "_edit_", i)]]) } else if (inputTypes[i] == "fileInput") { datapath <- input[[paste0(name, "_edit_", i)]]$datapath if (!is.null(datapath) && file.exists(datapath)) { # only if file actually uploaded, otherwise we won't update newdata[[i]][row] <- blob::blob( readBin( # file read into binary raw (blob) column datapath, what = "raw", n = max.fileInputLength ) ) } } else if (inputTypes[i] %in% c("dateInput", "datetimeInput")) { if (length(input[[paste0(name, "_edit_", i)]]) == 0) { newdata[row, i] <- as.Date(NA) # 'dateInput' returns length 0 if empty, but date of length 0 # fails to 'replace' the current contents of newdata[row, i]! # address issue #21 } else { newdata[row, i] <- input[[paste0(name, "_edit_", i)]] } } else { newdata[row, i] <- input[[paste0(name, "_edit_", i)]] } } tryCatch({ callback.data <- callback.update( data = newdata, olddata = result$thedata, row = row ) if (!is.null(callback.data) && is.data.frame(callback.data)) { result$thedata <- callback.data } else { result$thedata <- newdata } updateData(dt.proxy, result$thedata[, view.cols, drop = FALSE], # was "result$thedata[,view.cols]", # but that returns vector (not dataframe) if # view.cols is only a single column rownames = datatable.rownames ) result$edit.count <- result$edit.count + 1 inputEvent_handles$finalize() # remove the observeEvents shiny::removeModal() return(TRUE) }, error = function(e) { output[[paste0(name, "_message")]] <<- shiny::renderUI(shiny::HTML(geterrmessage())) return(FALSE) }) } return(FALSE) }) ##### Delete functions ##################################################### observeEvent(input[[paste0(name, "_remove")]], { # if the '_remove' event is observed, the 'deleteModal' popup is opened row <- input[[paste0(name, "dt_rows_selected")]] if (!is.null(row)) { if (row > 0) { shiny::showModal(deleteModal(row)) } } }) deleteModal <- function(row) { # if the '_remove' event is observed, the 'deleteModal' popup is opened # # other than being closed/cancelled, the 'deleteModal' popup # can also be closed if the '_delete' event is observed fields <- list() for (i in seq_along(delete.info.cols)) { fields[[i]] <- div(paste0(delete.info.label.cols[i], " = ", result$thedata[row, delete.info.cols[i]])) } output[[paste0(name, "_message")]] <- shiny::renderUI("") shiny::modalDialog( title = title.delete, shiny::fluidPage( shiny::div( if (datatable.rownames) # rownames are being displayed shiny::h4(rownames(thedata)[row]) ), shiny::div( shiny::htmlOutput( ns(paste0(name, "_message"))), style = "color:red" ), shiny::p(text.delete.modal), fields ), footer = shiny::column(modalButton(label.cancel), shiny::actionButton( ns(paste0(name, "_delete")), label.delete ), width = 12 ), size = modal.size ) } observeEvent(input[[paste0(name, "_delete")]], { # the '_delete' event is observed from the 'deleteModal' popup row <- input[[paste0(name, "dt_rows_selected")]] if (!is.null(row) && row > 0) { tryCatch({ callback.data <- callback.delete(data = result$thedata, row = row) if (!is.null(callback.data) && is.data.frame(callback.data)) { result$thedata <- callback.data } else { result$thedata <- result$thedata[-row, , drop = FALSE] # 'drop=FALSE' prevents the dataframe being reduced to a vector # especially if only a single column } updateData(dt.proxy, result$thedata[, view.cols, drop = FALSE], # was "result$thedata[,view.cols]", # but that only returns a vector (instead of dataframe) # if view.cols is single column rownames = datatable.rownames ) result$edit.count <- result$edit.count + 1 shiny::removeModal() return(TRUE) }, error = function(e) { output[[paste0(name, "_message")]] <<- shiny::renderUI(shiny::HTML(geterrmessage())) return(FALSE) } ) } return(FALSE) }) ##### Action button callbacks ################################################ observeEvent(input$select_button, { # triggered by an 'action' button being clicked # row <- input[[paste0(name, "dt_rows_selected")]] # unfortunately, the 'row' selected this way seems to be unreliable # determine the row number from the button selected # the buttons have been 'numbered' in the suffix x <- strsplit(input$select_button, "_")[[1]] selectedRow <- as.numeric(x[length(x)]) newdata <- result$thedata tryCatch({ callback.data <- callback.actionButton( data = result$thedata, row = selectedRow, buttonID = input$select_button ) if (!is.null(callback.data) && is.data.frame(callback.data)) { result$thedata <- callback.data } else { result$thedata <- newdata # 'drop=FALSE' prevents the dataframe being reduced to a vector # especially if only a single column } updateData(dt.proxy, result$thedata[, view.cols, drop = FALSE], # was "result$thedata[,view.cols]", # but that only returns a vector (instead of dataframe) # if view.cols is single column rownames = datatable.rownames ) result$edit.count <- result$edit.count + 1 shiny::removeModal() return(TRUE) }, error = function(e) { output[[paste0(name, "_message")]] <<- shiny::renderUI(shiny::HTML(geterrmessage())) return(FALSE) } ) }) ##### React to changes in 'thedata' if that variable is a reactive ###### if (shiny::is.reactive(thedata)) { observeEvent(thedata(), { result$thedata <- as.data.frame(shiny::isolate(thedata())) updateData(dt.proxy, result$thedata[, view.cols, drop = FALSE], # was "result$thedata[,view.cols]", # but that returns vector (not dataframe) # if view.cols is only a single column rownames = datatable.rownames ) }) } ##### Build the UI for the DataTable and buttons ########################### output[[name]] <- shiny::renderUI({ shiny::div( if (show.insert) { shiny::actionButton( ns(paste0(name, "_add")), label.add, icon = icon.add ) }, if (show.update) { shiny::actionButton( ns(paste0(name, "_edit")), label.edit, icon = icon.edit ) }, if (show.delete) { shiny::actionButton( ns(paste0(name, "_remove")), label.delete, icon = icon.delete ) }, if (show.copy) { shiny::actionButton( ns(paste0(name, "_copy")), label.copy, icon = icon.copy ) }, shiny::br(), shiny::br(), DT::dataTableOutput(ns(DataTableName)) ) }) outputOptions(output, name, suspendWhenHidden = FALSE) # if suspendWhenHidden is true, then # the table is not rendered if the tab is hidden return(result) # $edit.count only incremented by changes made through dtedit GUI # does not include edits created through response # to changes in reactiveval 'thedata' # this might help determine the source of changes in result$thedata } #' Create a DataTable with Add, Edit and Delete buttons. #' #' dteditmodUI - user-interface function for module use #' #' Use in conjunction with \code{callModule} and \code{dtedit} to create #' editable datatables. \code{dteditUI} is used in the 'user interface' #' component of the shiny app. #' #' @param id the namespace of the module #' @family Datatable Edit functions #' @seealso \code{\link{dteditmod}} : the companion server-component function.\cr #' #' \itemize{ #' \item \code{example("dteditmodUI")} a simple example #' with a reactive dataframe #' \item \code{dteditmod_demo()} a more complex example. #' Includes database interaction and interactions between #' the data of multiple datatables. #' } #' @example inst/examples/reactivedataframe_modular/app.R #' @export dteditmodUI <- function(id) { ns <- shiny::NS(id) shiny::tagList( shiny::uiOutput(ns("editdt")) ) }
b1725b99b76f0583925c0e659f6f7a619dae7f3a
665b11fb5c51f7ccf2d6b4f18616f13a82a79446
/p2.R
77b1f1949e3ef096379ada6cb3a61fe3fd3446b3
[]
no_license
manishwaran/location-based-prediction-analysis-on-fb-data-for-commercial-products
e43c971cab2427063fad9850e13e3d434261695d
82a3074dacf400fdee350848755f3e3381c17c42
refs/heads/master
2020-04-12T10:19:29.142450
2016-06-04T09:42:56
2016-06-04T09:42:56
null
0
0
null
null
null
null
UTF-8
R
false
false
924
r
p2.R
get.count_data <- function(my_set_net,my_set_week,week) { count<-0 for(i in 1:nrow(my_set_net)) { if(isTRUE(my_set_net[i,1]!="NA")) { if(isTRUE(my_set_week[i,1]==week)){ count<-count+1} } } return(count) } reform_data_predict <- function(data_set,new_set,week,max_week) { for( i in 1:max_week) { tem<-as.data.frame(matrix(ncol = length(network_types)+1,nrow = 1)) name_data<-c("Week",network_types) names(tem)<-name_data tem['Week']<-i for(j in network_types) { tem[j]<-get.count_data(data_set[j],data_set['Week'],i) } new_set<-insertRow2(new_set,tem,nrow(new_set)+1) } return(new_set) } new_set <- as.data.frame(matrix(ncol = length(network_types)+1,nrow = 1)) name_data<-c("Week",network_types) names(new_set)<-name_data new_set<-reform_data_predict(fb_data,new_set,1,22) new_set<-new_set[-1,] new_set new_set<-ts(new_set) plot(new_set[,-1]) url<-readline("Enter the Network : ") predict_arima(new_set[,url],4)
62f97fd70ce95c84e9ef0fbdb212b1194125e274
4f584789b99a33d806da0b7c5b63da3b608f7b48
/scripts/site_wise_mnase_signal.R
c86fca24b0ac8350bc3d30af73e43cd09a26f0c8
[]
no_license
satyanarayan-rao/protein_binding_at_enhancers
f10580e76adcc057bf21614c0f9a3c96a8b3f0d5
74a6a33efb7acff073b0dcec96c917a4cd019219
refs/heads/master
2022-11-30T13:56:41.520639
2020-08-11T21:17:19
2020-08-11T21:17:19
286,848,856
2
0
null
null
null
null
UTF-8
R
false
false
6,400
r
site_wise_mnase_signal.R
library(stringr) library(ggplot2) library(ggthemes) library(zoo) # chr2L@11806479@11806979@chr2L:11806729-11806729^20 args = commandArgs(trailingOnly = T) # args[1]: mnase csv gz file # args[2]: site of interest # args[3]: site wise eom plot # args[4]: site wise erom rmean plot # args[5]: site wise max peak location (have to find two peaks) # args[6]: rolling mean window size input_dt = read.table(args[1], stringsAsFactors = F, sep = "", header = F) site_of_interest = str_replace(args[2], "\\^", "\\\\^") rolling_window_size = as.integer (args[6]) # get the specific site site_dt = as.data.frame(t(input_dt[grepl(site_of_interest, input_dt$V1),, drop = F]), stringsAsFactors = F) # remove the first row site_dt = site_dt[2:dim(site_dt)[1], , drop = F] names(site_dt) = "site_of_interest" site_dt[site_of_interest] = as.numeric(site_dt[, "site_of_interest"]) site_dt["x_tics"] = seq(dim(site_dt)[1]) site_dt$x_tics = site_dt$x_tics - as.integer(dim(site_dt)[1]/2) site_dt$rmean = rollmean(site_dt[site_of_interest], k = rolling_window_size, fill = NA) # find the max (indices of right and left flank) and the second max ### to_find_max = site_dt[, "site_of_interest"] total_rows = dim(site_dt)[1] first_max_loc = which.max(to_find_max) first_max_val = to_find_max[first_max_loc] first_max_right_flank = NULL for (i in seq(first_max_loc + 1, total_rows)){ if (to_find_max[i] != first_max_val){ first_max_right_flank = i - 1 break }else{ next } } first_max_left_flank = NULL for (i in seq(first_max_loc - 1 , 1)){ if (to_find_max[i] != first_max_val){ first_max_left_flank = i + 1 break }else{ next } } # copy to_find_max to another vector and replace first_max val to -1 and then find max print (c (first_max_left_flank, first_max_right_flank)) to_find_second_max = to_find_max to_find_second_max[first_max_left_flank: first_max_right_flank] = -1 second_max_loc = which.max (to_find_second_max) second_max_val = to_find_second_max[second_max_loc] print (c(second_max_val, second_max_loc) ) second_max_right_flank = NULL for (i in seq(second_max_loc + 1, total_rows)){ print(to_find_second_max[i]) if (to_find_second_max[i] != second_max_val){ second_max_right_flank = i - 1 break }else{ next } } print ('here') second_max_left_flank = NULL for (i in seq(second_max_loc - 1 , 1)){ if (to_find_second_max[i] != second_max_val){ second_max_left_flank = i + 1 break }else{ next } } first_max_left_loc_eom = site_dt[first_max_left_flank, "x_tics"] first_max_right_loc_eom = site_dt[first_max_right_flank, "x_tics"] second_max_left_loc_eom = site_dt[second_max_left_flank, "x_tics"] second_max_right_loc_eom = site_dt[second_max_right_flank, "x_tics"] ### # find the max (indices of right and left flank) and the second max: for rolling mean ### to_find_max = site_dt[, "rmean"] total_rows = dim(site_dt)[1] first_max_loc = which.max(to_find_max) first_max_val = to_find_max[first_max_loc] first_max_right_flank = NULL for (i in seq(first_max_loc + 1, total_rows)){ if (to_find_max[i] != first_max_val){ first_max_right_flank = i - 1 break }else{ next } } first_max_left_flank = NULL for (i in seq(first_max_loc - 1 , 1)){ if (to_find_max[i] != first_max_val){ first_max_left_flank = i + 1 break }else{ next } } # copy to_find_max to another vector and replace first_max val to -1 and then find max to_find_second_max = to_find_max to_find_second_max[first_max_left_flank: first_max_right_flank] = -1 second_max_loc = which.max (to_find_second_max) second_max_val = to_find_second_max[second_max_loc] second_max_right_flank = NULL for (i in seq(second_max_loc + 1, total_rows)){ if (to_find_second_max[i] != second_max_val){ second_max_right_flank = i - 1 break }else{ next } } second_max_left_flank = NULL for (i in seq(second_max_loc - 1 , 1)){ if (to_find_second_max[i] != second_max_val){ second_max_left_flank = i + 1 break }else{ next } } first_max_left_loc_rmean = site_dt[first_max_left_flank, "x_tics"] first_max_right_loc_rmean = site_dt[first_max_right_flank, "x_tics"] second_max_left_loc_rmean = site_dt[second_max_left_flank, "x_tics"] second_max_right_loc_rmean = site_dt[second_max_right_flank, "x_tics"] ### pdf(args[3], width = 6, height = 6) kk = ggplot (data = site_dt, aes(x = x_tics, y = site_of_interest)) + geom_line() + ggtitle(site_of_interest) + theme_few() + geom_rangeframe() + theme(plot.title = element_text(hjust = 0.5)) + xlab("Distance from peak center [bp]") + ylab ("MNase (e.o.m)") + geom_vline(xintercept = c(first_max_left_loc_eom, first_max_right_loc_eom, second_max_left_loc_eom, second_max_right_loc_eom), linetype = 2) print(kk) dev.off() pdf(args[4], width = 6, height = 6) kk = ggplot (data = site_dt, aes(x = x_tics, y = rmean)) + geom_line() + ggtitle(site_of_interest) + theme_few() + geom_rangeframe() + theme(plot.title = element_text(hjust = 0.5)) + xlab("Distance from peak center [bp]") + ylab ("MNase (e.o.m-rolling mean)") + geom_vline(xintercept = c(first_max_left_loc_rmean, first_max_right_loc_rmean, second_max_left_loc_rmean, second_max_right_loc_rmean), linetype = 2) print(kk) dev.off() # save max locations in file and also minimum difference between peaks flanks # create a data frame of locations and differences location_df = data.frame(row.names = c("eom", "roll_mean"), first_max_left_loc = c(first_max_left_loc_eom, first_max_left_loc_rmean), first_max_right_loc = c(first_max_right_loc_eom, first_max_right_loc_rmean), second_max_left_loc = c(second_max_left_loc_eom, second_max_left_loc_rmean), second_max_right_loc = c(second_max_right_loc_eom, second_max_right_loc_rmean)) write.table(location_df, file = args[5], row.names = T, col.names = T, quote = F)
a9ab962b82422b991c2b82d3595ad4419314f82a
8b5adabd11f4e662dbad9731e21528c277dd80f1
/man/as.definitions.modelname.Rd
dcd0e75b277348482a64aedd3ec0d9ad93d3e117
[]
no_license
bergsmat/partab
68e6ecab610d45f59541e7000bc1ad2f023af0a6
aacbfc64017d4ff9df2963de267b4add453a23cb
refs/heads/master
2021-01-13T12:17:17.140660
2017-02-18T14:49:09
2017-02-18T14:49:09
78,268,135
0
0
null
null
null
null
UTF-8
R
false
true
1,896
rd
as.definitions.modelname.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/definitions.R \name{as.definitions.modelname} \alias{as.definitions.modelname} \alias{definitions} \title{Create Item Definitions from Model Name} \usage{ \method{as.definitions}{modelname}(x, verbose = FALSE, opt = getOption("project"), project = if (is.null(opt)) getwd() else opt, rundir = file.path(project, x), ctlfile = file.path(rundir, paste0(x, ".ctl")), metafile = file.path(rundir, paste0(x, ".def")), fields = c("symbol", "label", "unit"), read = length(metafile) == 1, write = FALSE, ...) } \arguments{ \item{x}{a model name (numeric or character)} \item{verbose}{set FALSE to suppress messages} \item{opt}{alternative argument for setting project} \item{project}{parent directory of model directories} \item{rundir}{specific model directory} \item{ctlfile}{path to control stream (pass length-zero argument to ignore)} \item{metafile}{path to definitions file (pass length-zero argument to ignore)} \item{fields}{metadata fields to read from control stream if no metafile} \item{read}{whether to read the definitions file} \item{write}{whether to write the definitions file} \item{...}{passed to other functions} } \value{ object of class definitions, or path to metafile if write = TRUE. } \description{ Creates item definitions from a model name. Scavenges definitions optionally from the control stream and optionally from the definitions file. Optionally writes the result to the definitions file. Always returns a data.frame with at least the column 'item' but possibly no rows. } \examples{ library(magrittr) options(project = system.file('project/model',package='partab')) 1001 \%>\% as.definitions } \seealso{ \code{\link{as.xml_document.modelname}} \code{\link{as.bootstrap.modelname}} \code{\link{as.nmctl.modelname}} \code{\link{write.csv}} \code{\link{read.csv}} }
0874d7f49ec7dd16637415d7b79e5814365c8cb9
6b081fff9d4ca5958c93d494e70115c7071dadef
/Assignment4.1.r
c5b8f30b9b5615ebee9bc90fab767035b8133916
[]
no_license
clintaveben/Assignmnet-4.1
13d1915c5ba8fcec2088c89b0152766c0d669e99
591b13f5416c0c358fb68382c17b721d4cf1de38
refs/heads/master
2020-04-04T19:52:28.555827
2018-11-05T13:40:40
2018-11-05T13:40:40
156,223,895
0
0
null
null
null
null
UTF-8
R
false
false
1,105
r
Assignment4.1.r
# This is given df1 = data.frame(CustId = c(1:6), Product = c(rep("TV", 3), rep("Radio", 3))) df2 = data.frame(CustId = c(2, 4, 6), State = c(rep("Texas", 2), rep("NYC", 1))) df1 #left table df2 #right table ## Return only the rows in which the left table have match. df<-merge(x=df1,y=df2,by="CustId") df ### . Returns all rows from both tables, join records from the left which have matching keys in the right table Ans : df<-merge(x=df1,y=df2,by="CustId",all=TRUE) df ###. Return all rows from the right table, and any rows with matching keys from the left table. df<-merge(x=df1,y=df2,by="CustId",all=FALSE) df #### Q 2. Perform the below operations on above given data frames and tables: # . Return a long format of the datasets without matching key. df<-merge(x=df1,y=df2,by="CustId",all=TRUE) df_2<- df[c(1,3,5),] df_2 #Keep only observations in df1 that match in df2. df<-merge(x=df1,y=df2,by="CustId",all=FALSE) df # . Drop all observations in df1 that match in df2. df<-merge(x=df1,y=df2,by="CustId",all=TRUE) df_2<- df[c(1,3,5),] df_2
1758730a9ea93877d96b74005ba7bc7d28a44420
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/micompr/examples/summary.micomp.Rd.R
6276e518c6291afed9aafff7ac8cbcf2fdddaf24
[]
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
485
r
summary.micomp.Rd.R
library(micompr) ### Name: summary.micomp ### Title: Summary method for multiple comparisons of outputs ### Aliases: summary.micomp ### ** Examples # A micomp object from package datasets (i.e. grpoutputs objects) directly ## No test: summary(micomp(5, 0.85, list(list(name = "CompEq", grpout = pphpc_ok), list(name = "CompNoShuf", grpout = pphpc_noshuff), list(name = "CompDiff", grpout = pphpc_diff)))) ## End(No test)
988894576991150107a00759f3c18e76398f1135
6587d3d6a95e795d58413a82f28fcfc14fb3cfb4
/server.R
7c3f1deed00b9e5ad19f1381738db774d65e4519
[]
no_license
Sandy4321/feature_selection_app
01035c0781cf97a1a785d9c6faccaca0e2eef306
73fa137691bc2194ab12427cede12959a289ec3d
refs/heads/master
2021-01-22T10:25:08.331453
2015-06-20T19:11:50
2015-06-20T19:11:50
null
0
0
null
null
null
null
UTF-8
R
false
false
5,374
r
server.R
# Handle computations for feature selection demo app. library(shiny) require(caret, quietly=TRUE) require(kernlab, quietly=TRUE) require(ElemStatLearn, quietly=TRUE) # This package is *not* needed, but when this app is run on shinyapps.io, # I get an error saying it *is* needed. The SVM used here is svmPoly, # which the kernlab docs say explicitly is an *alternative* to svm from # e1071. require(e1071, quietly=TRUE) # We're using the South Africa heart disease data from the ElemStatLearn # package. This is chosen because it is small (hence doesn't have long # training times nor large memory use) and because the features are very # familar to most people. (With one exception...no, I don't know the # difference between obesity and adiposity either. Have not been able to # obtain a copy of the original paper to check how they are using the two # terms.) Drawback to this dataset is that the feature selection does not # make a huge difference to the accuracy. Would be nice to find a dataset # where there are big gains to be had with the right selection of features. # # Training will be done on the entire dataset, since it is so small, and # accuracy will be estimated by cross-validation rather than saving out a # validation set. This does yield a higher accuracy than (say) reserving # 30% for validation, but that may be due to the small amount of data -- # there really may be an improvement from training on that remaining 30% # as well, rather than a degradation due to overfitting. data(SAheart) SAheart$chd <- factor(SAheart$chd, levels=c(0,1), labels=c("FALSE","TRUE")) train.ctrl <- trainControl(method="cv", number=5, returnData=FALSE) column.labels <- c( "chd" = "Heart disease", "adiposity" = "Adiposity", "age" = "Age", "alcohol" = "Alcohol use", "famhist" = "Family history", "ldl" = "LDL cholesterol", "obesity" = "Obesity", "sbp" = "Systolic blood pressure", "tobacco" = "Tobacco use", "typea" = "Type A behavior" ) run.train <- function(users.features) { if (!is.null(users.features) & length(users.features) > 0) { # Construct the formula. users.formula.text <- paste("chd ~ ", paste(users.features, collapse="+")) users.formula <- as.formula(users.formula.text) # Train the classifier. Use a support vector machine with polynomial # kernel. This consistently does better than a random forest on this # dataset. Yes, really, try it. set.seed(54321) sa.model <- train(users.formula, method="svmPoly", data=SAheart, trControl=train.ctrl) sa.trainperf <- getTrainPerf(sa.model) as.character(round(sa.trainperf$TrainAccuracy, digits=4)) # sprintf("Accuracy: %s, Formula: %s", # as.character(round(sa.trainperf$TrainAccuracy, digits=4)), # users.formula.text # ) } else { NULL } } shinyServer(function(input, output) { output$featurePlot <- renderPlot({ input$plotButton isolate({ # Don't complain to the user for minor things. If they have # checked any feature, we can show an appropriate plot. If the # outcome is checked, show that with the first checked feature. # Otherwise, show the first two checked features. if (length(input$features) >= 1) { xcol <- NULL ycol <- NULL if (input$outcome | length(input$features) == 1) { # Here, the user wants to compare against outcome. x.name <- "chd" y.name <- input$features[1] } else { x.name <- input$features[1] y.name <- input$features[2] } par(mar=c(4,4,1,1)) x.column <- SAheart[, x.name] y.column <- SAheart[, y.name] plot(x.column, y.column, xlab=column.labels[x.name], ylab=column.labels[y.name], col="red") # If either column is a binary factor, convert it to 0 and 1. # For factors with other than 2 levels, omit the correlation. cvt.factor <- function(col) { if (is.factor(col)) { level.names <- levels(col) if (length(level.names) == 2) { # Convert the first level to FALSE, second to TRUE. col == level.names[2] } else { NULL } } else { col } } x.column <- cvt.factor(x.column) y.column <- cvt.factor(y.column) if (!is.null(x.column) & !is.null(y.column)) { c <- round(cor(x.column, y.column), digits=3) usr <- par("usr") xmid <- (usr[1] + usr[2]) / 2 ytop <- usr[4] - 2 text(xmid, ytop, sprintf("Correlation = %.3f", c)) } } }) }) output$accuracy <- renderText({ input$trainButton isolate(run.train(input$features)) }) })
99156cef997d8434204737eb6085432eddc8636c
7f968fdd74ebf15e9280485290fe2bb9348e9b75
/Project1/plot1.R
97e3ded11081cc8b8426d921480290d5d4413e74
[]
no_license
jozelazarevski/ExData_Plotting1
bf5b05dbad7ecf89aba5b0fbfecbf95c60649296
0f599f85cb71cae392eaf981d39845b28929ac63
refs/heads/master
2020-12-03T08:12:31.235022
2014-11-09T22:52:56
2014-11-09T22:52:56
null
0
0
null
null
null
null
UTF-8
R
false
false
355
r
plot1.R
data<-read.table("household_power_consumption.txt",sep=";",header=TRUE) data1<-subset(data,Date=="1/2/2007" | Date=="2/2/2007" ) data1_num<-as.numeric(as.character(data1$Global_active_power)) hist(data1_num, col = "red", main = paste("Global Active Power"),xlab = "Global Active Power (kilowatts)") dev.copy(png, file = "plot1.png", width = 480) dev.off()
ecc3d59a053c6aeb213f921c61a4874e6002cb52
f860a2ddbebe96ad25f2347823d1ad31a5ae949e
/R/prep/plotting.R
0da9d82fdbbe80f683120a7bc3ae3428981ddac9
[ "MIT" ]
permissive
mespe/STS198
edd0e966a329b8701048e2c8371a57b0a261f2fa
4dd8184e67689ff9d0af3dab1813973e46f59df3
refs/heads/master
2021-01-22T18:51:06.426391
2017-09-15T23:10:34
2017-09-15T23:10:34
85,125,705
0
0
null
null
null
null
UTF-8
R
false
false
1,598
r
plotting.R
# Learning ggplot2 library(ggplot2) load("../data/health_costs.rda") sac = subset(health, Provider.City == "SACRAMENTO") ggplot(sac, aes(x = Total.Discharges, y = Average.Total.Payments)) + geom_point() ggplot(sac, aes(x = Total.Discharges, y = Average.Total.Payments, shape = Provider.Name, color = Provider.Name)) + geom_point() ggplot(sac, aes(x = Average.Medicare.Payments, y = Average.Total.Payments, color = Provider.Name)) + geom_point(aes(size = Total.Discharges)) ggplot(sac, aes(x = Total.Discharges, y = Average.Total.Payments, shape = Provider.Name, color = Provider.Name)) + geom_point() ggplot(sac, aes(x = Provider.Name, y = Average.Total.Payments, shape = Provider.Name, color = Provider.Name)) + geom_violin() ggplot(sac, aes(x = Provider.Name, y = Total.Discharges, shape = Provider.Name, color = Provider.Name)) + geom_violin() ggplot(sac, aes(x = Average.Covered.Charges, y = Average.Total.Payments, shape = Provider.Name, color = Provider.Name)) + geom_point() + geom_smooth() ggplot(sac, aes(x = Average.Total.Payments, fill = Provider.Name)) + geom_density(alpha = 0.2) ggplot(sac, aes(x = Average.Total.Payments)) + geom_histogram() + theme_bw() + xlab("Average Total Payments (USD)") + ylab("Count") #### class #### idx = grep("HEART", health$DRG.Definition) heart = health[idx,] ggplot(heart, aes(x = Average.Total.Payments, fill = Provider.City == "SACRAMENTO")) + geom_density(alpha = 0.2)
95fe08968a303b3a10665a7c5fc4cba487e0ba0a
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/GiniWegNeg/examples/Gini_CTR_BS.Rd.R
d02fa3bba9bc02eb38897cb05edcf1cf473af2a2
[]
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
851
r
Gini_CTR_BS.Rd.R
library(GiniWegNeg) ### Name: Gini_CTR_BS ### Title: The Gini coefficient adjusted for negative attributes (Chen, ### Tsaur and Rhai, 1982, Berebbi and Silber, 1985) ### Aliases: Gini_CTR_BS ### ** Examples # generate the vector of attributes with even negative elements y<-c(-7,-15,11,-10,2,4,40) # generate the vector of weights w<-c(2.5,1.1,3.6,4.4,0.8,2.7,1.9) # compute the Gini coefficient adjusted for negative values Gini_CTR_BS(y,w) data(BI2012) # define the vector of weights w<-BI2012$weight # select the vector of incomes (e.g., the incomes from transfers YTA) y<-BI2012$YTA # compute the Gini coefficient adjusted for negative values Gini_CTR_BS(y,w) # select the vector of incomes (e.g., the incomes from financial capital gain YCF) y<-BI2012$YCF # compute the Gini coefficient adjusted for negative values Gini_CTR_BS(y,w)
bf73b3b519b20c00912d2a12f416bd0dd5ae3f3b
81af737c7f206593c900d3973d8d175dc50ac8af
/man/itemdiagram.Rd
9731db2731c9f2178a6e45a43aedd70f896e26b7
[ "MIT" ]
permissive
CambridgeAssessmentResearch/POSAC
df607fd2f1cc6cd0d86a24212f28f471cdb89fb2
6aaeecfc76e643bde973c613bcdef14588e0431a
refs/heads/master
2021-10-23T16:02:08.065883
2019-03-18T15:29:14
2019-03-18T15:29:14
109,018,236
0
0
MIT
2018-07-10T15:15:46
2017-10-31T15:50:29
R
UTF-8
R
false
true
1,400
rd
itemdiagram.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/itemdiagram.R \name{itemdiagram} \alias{itemdiagram} \title{Function to plot X and Y output from POSAC with colours for different values of given variables} \usage{ itemdiagram(posacout, vars) } \arguments{ \item{posacout}{Output from function POSAC (or POSACupdate).} \item{vars}{Indices of items from pattern matrix. Including too many items at once may possibly produce an error. Also note that if multiple items are specified, the positioning of points will be the same in each plot generated - only the colouring and labelling will change.} } \description{ This function produces plots of the values of the two variables (X and Y) produced by the analysis (e.g. the POSAC function) against one another. Colour is added to the chart to represent the values of a particular individual variable within the data set. These plots may help to identify whether a given indidvidual variable is particularly important in the definition of either X or Y. Note that if multiple plots are produced (for multiple items) the positions of points will be identical in every plot. Only the colouring and labelling of points will vary. } \examples{ posac2=POSAC(CRASdata[,1:5],CRASdata[,6]) itemdiagram(posac2,1) itemdiagram(posac2,2) itemdiagram(posac2,1:3) itemdiagram(posac2,1:5) } \keyword{Scalogram}
1549ad6c3963e855008a274fda55d8f3b9961bf8
245fe92d0c2995e7a7a031ae7945d9b0164e4936
/PA1_template.R
cbfc30413510466ada395d549c86894a3c2dd75d
[]
no_license
topramen/RepData_PeerAssessment1
d8a41c2864d0b011044fa02188009632f580dafa
265bd09a7929be0cc4d207204674302640cbf687
refs/heads/master
2021-01-16T21:44:29.940672
2015-01-17T21:35:57
2015-01-17T21:35:57
29,200,910
0
0
null
2015-01-13T17:04:17
2015-01-13T17:04:17
null
UTF-8
R
false
false
2,834
r
PA1_template.R
if (!require(lubridate)) { install.packages("lubridate") library(lubridate) } if (!require(plyr)) { install.packages("plyr") library(plyr) } if (!require(ggplot2)) { install.packages("ggplot2") library(ggplot2) } if (!require(xts)){ install.packages("xts") library(xts) } if (!require(reshape2)){ install.packages("reshape2") library(reshape2) } steps <- read.csv("activity.csv", stringsAsFactors=F) names(steps) summary(steps) steps$date <- ymd(steps$date) steps.complete <- steps[complete.cases(steps),] steps.daily.complete <- aggregate(steps ~ date, steps.complete, sum) str(steps.daily.complete) #histogram of daily steps hist(steps.daily.complete$steps) #mean and median of daily steps mean.sdc <- mean(steps.daily.complete$steps) median.sdc <- median(steps.daily.complete$steps) #average day avg.day <- aggregate(steps ~ interval, steps.complete, mean) #row.names(avg.day) <- hm(ymd_hm(paste("20150101", formatC(avg.day$interval, width = 4, format = "d", flag = "0"))) row.names(avg.day) <- ymd_hm(paste("20150101", formatC(avg.day$interval, width = 4, format = "d", flag = "0"))) max.steps.interval <- avg.day[which.max(avg.day$steps), "interval"] #For imputing missing values in steps, lookup the steps for that interval from avg.day steps <- merge (steps, avg.day, by="interval") #remove the interval column so that this dataframe can be used as a zoo object avg.day <- subset (avg.day, select = -c(interval)) #Time Series Plot of average day plot.zoo(as.xts(avg.day), ylab="Steps", xlab="Hour of the day") #Handling NA values na.rows <- is.na(steps$steps.x) #How many NAs are there sum(na.rows) #impute the na values in a new data set #steps$steps.x[na.rows] <- steps$steps.y[na.rows] steps2 <- transform(steps, steps = ifelse(na.rows, steps$steps.y, steps$steps.x)) #histogram with the imputed data steps2 <- subset (steps2, select = -c(steps.x, steps.y)) steps2.daily <- aggregate(steps ~ date, steps2, sum) #histogram of imputed daily steps hist(steps2.daily$steps) #mean and median of imputed daily steps mean.step2.daily <- mean(steps2.daily$steps) median.steps2.daily <- median(steps2.daily$steps) #add weekday/weekend identifier to imputed DF steps2 steps2$day <- weekdays(steps2$date) # Does the day begin with an 's'? steps2$isWeekend <- grepl("^S", steps2$day) steps2$dayType <- factor(steps2$isWeekend, levels = c(F, T), labels = c("Weekday", "Weekend")) head(steps2) avg.day.imputed <- aggregate(steps ~ interval + dayType, steps2, mean) avg.day.imputed <- dcast(avg.day.imputed, interval ~ dayType) row.names(avg.day.imputed) <- ymd_hm(paste("20150101", formatC(avg.day.imputed$interval, width = 4, format = "d", flag = "0"))) avg.day.imputed <- subset (avg.day.imputed, select = -c(interval)) plot.zoo(as.xts(avg.day.imputed), xlab="Interval", main="Number of Steps")
fe0175593a2f76ed3f7704f7002256a1a664cf9f
c0354f6714026298a8b145f895bbe6870805a261
/run_analysis.R
6f27166ac39b9ea565d2a4abd5ca4a5e02d8042e
[]
no_license
DP-atnt/Getting_and_cleaning_data
8d52aa9ef630ea2b302f594ffa1dffce44aeb9a2
07507b857fa689f5cea729d8d687dd17927bf230
refs/heads/master
2021-01-10T17:57:45.126586
2016-02-13T20:25:12
2016-02-13T20:25:12
51,634,843
0
0
null
null
null
null
UTF-8
R
false
false
2,676
r
run_analysis.R
```{r} # I will use dplyer, so the library is assumed installed and is loaded library(dplyr) #the following chunk of code downloads the original data set if(!file.exists("./Project")){dir.create("./Project")} fileUrl <-"https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" download.file(fileUrl,destfile="./Project/getdata-projectfiles-UCI HAR Dataset.zip") unzip("./Project/getdata-projectfiles-UCI HAR Dataset.zip",exdir = "./Project") #the next step is to read the files into R.loading the train data X.train <-read.table("./Project/UCI HAR Dataset/train/X_train.txt") y.train <-read.table("./Project/UCI HAR Dataset/train/y_train.txt") subject.train <-read.table("./Project/UCI HAR Dataset/train/subject_train.txt") #loading the test data X.test <-read.table("./Project/UCI HAR Dataset/test/X_test.txt") y.test <-read.table("./Project/UCI HAR Dataset/test/y_test.txt") subject.test <-read.table("./Project/UCI HAR Dataset/test/subject_test.txt") #loading activity and variable names variables<-read.table("./Project/UCI HAR Dataset/features.txt") activities<-read.table("./Project/UCI HAR Dataset/activity_labels.txt") #joining the train and test data and then the whole set train_df<-cbind(subject.train, y.train, X.train) test_df<-cbind(subject.test, y.test, X.test) whole_set_df<-rbind(train_df,test_df) #setting the right names for the variables. colnames(whole_set_df)<-c("subject","activity",as.character(variables$V2)) #extracting ID, activity, mean and std columns and these to create the data frame with relevant variables only means <- grep("[Mm]ean",names(whole_set_df),value = FALSE) stds<-grep("[Ss]td",names(whole_set_df)) colms<-sort(c(1,2,means,stds)) filt_set_df<-whole_set_df[, colms] #replacing activity names in dataset names(activities)<-c("ID","activity") clean<-merge(activities,filt_set_df,by.x = "ID",by.y = "activity") clean<-clean[,-1] #changing to descriptive names names(clean)<-gsub("f[B]*","frequencyB",names(clean)) names(clean)<-gsub("^t[B]","timeB",names(clean)) names(clean)<-gsub("^t[G]","timeG",names(clean)) names(clean)<-gsub("-","",names(clean)) names(clean)<-gsub("[()]","",names(clean)) names(clean)<-gsub(",","",names(clean)) names(clean)<-gsub("Acc","Acceleration",names(clean)) #at this point is safe to clean all unused variables rm(y.train,y.test,X.test,X.train,whole_set_df,variables,train_df,test_df, subject.test,subject.train,stds,means,filt_set_df,fileUrl,colms,activities) #create summary of data and save to disk action<-group_by(clean,activity,subject) final_data<-summarize_each(action,funs(mean)) write.table(final_data,"./Project/final_data.txt",row.name=FALSE) ```
e165a187bce5ae27fa2e6fb490d2092bcce4697e
b9d215db9994c580ec44e13fe649474eb4ad4971
/R/FootprintFilter.R
a5308d2a92a5b4a396ba4767e5b85576c5fc10cf
[]
no_license
noahmclean1/TReNA
f1a1e809bd7c416ea4fb4a5b2695983d574a6e32
b93e1d5bf824822b4c92ba7f555072facc76fd9a
refs/heads/master
2020-04-05T12:10:25.599926
2017-08-16T19:09:17
2017-08-16T19:09:17
95,243,670
0
0
null
2017-07-28T23:45:29
2017-06-23T17:55:55
Jupyter Notebook
UTF-8
R
false
false
6,329
r
FootprintFilter.R
#' @title Create a FootprintFilter object #' #' @description #' A FootprintFilter object allows for filtering based on gene footprinting databases. Using its #' associated \code{getCandidates} method and URIs for both a genome database and project database, #' a FootprintFilter object can be used to filter a list of possible transcription factors to those #' that match footprint motifs for a supplied target gene. #' #' @include CandidateFilter.R #' @import methods #' #' @name FootprintFilter-class #' @rdname FootprintFilter-class #' @aliases FootprintFilter #---------------------------------------------------------------------------------------------------- .FootprintFilter <- setClass("FootprintFilter", contains = "CandidateFilter", slots=list(genomeDB="character", footprintDB="character", regions="character", footprintFinder="FootprintFinder") ) #---------------------------------------------------------------------------------------------------- printf <- function(...) print(noquote(sprintf(...))) #---------------------------------------------------------------------------------------------------- #' @rdname FootprintFilter-class #' #' #' @param quiet A logical denoting whether or not the filter should print output #' #' @seealso \code{\link{getCandidates-FootprintFilter}}, \code{\link{getFilterAssayData}} #' #' @export #' #' @return An object of the FootprintFilter class #' #' @family Filtering Objects #' #' @examples #' load(system.file(package="TReNA", "extdata/ampAD.154genes.mef2cTFs.278samples.RData")) #' footprint.filter <- FootprintFilter() FootprintFilter <- function(genomeDB, footprintDB, geneCenteredSpec=list(), regionsSpec=list(), quiet=TRUE) { fpFinder <- FootprintFinder(genomeDB, footprintDB, quiet=quiet) regions <- c(); # one or more chromLoc strings: "chr5:88903257-88905257" if(length(geneCenteredSpec) == 3){ new.region <- with (geneCenteredSpec, getGenePromoterRegion(fpFinder, targetGene, tssUpstream, tssDownstream)) new.region.chromLocString <- with(new.region, sprintf("%s:%d-%d", chr, start, end)) regions <- c(regions, new.region.chromLocString) } if(length(regionsSpec) > 0) regions <- c(regions, regionsSpec) .FootprintFilter(CandidateFilter(quiet = quiet), genomeDB=genomeDB, footprintDB=footprintDB, regions=regions, footprintFinder=fpFinder) } # FootprintFilter, the constructor #---------------------------------------------------------------------------------------------------- #' Get candidate genes using the variance filter #' #' @aliases getCandidates-FootprintFilter #' #' @param obj An object of class FootprintFilter #' @param extraArgs A named list containing 5 fields: #' \itemize{ #' \item{"target.gene" A designated target gene that should be part of the mtx.assay data} #' \item{"genome.db.uri" A connection to a genome database containing footprint information} #' \item{"project.db.uri" A connection to a project database containing footprint information} #' \item{"size.upstream" An integer denoting the distance upstream of the target gene to look for footprints} #' \item{"size.downstream" An integer denoting the distance downstream of the target gene to look for footprints} #' } #' #' @seealso \code{\link{FootprintFilter}} #' #' @family getCandidate Methods #' #' @return A vector containing all genes with variances less than the target gene #' #' @examples #' #' # Use footprint filter with the included SQLite database for MEF2C to filter candidates #' # in the included Alzheimer's dataset #' load(system.file(package="TReNA", "extdata/ampAD.154genes.mef2cTFs.278samples.RData")) #' footprint.filter <- FootprintFilter(mtx.assay = mtx.sub) #' #' target.gene <- "MEF2C" #' db.address <- system.file(package="TReNA", "extdata") #' genome.db.uri <- paste("sqlite:/",db.address,"genome.sub.db", sep = "/") #' project.db.uri <- paste("sqlite:/",db.address,"project.sub.db", sep = "/") #' #' tfs <- getCandidates(footprint.filter, extraArgs = list("target.gene" = target.gene, #' "genome.db.uri" = genome.db.uri, "project.db.uri" = project.db.uri, #' "size.upstream" = 1000, "size.downstream" = 1000)) setMethod("getCandidates", "FootprintFilter", function(obj){ # Create a FootprintFinder object and find the footprints fp <- FootprintFinder(obj@genomeDB, obj@footprintDB, quiet=TRUE) tbl.out <- data.frame() for(region in obj@regions){ chromLoc <- .parseChromLocString(region) if(!obj@quiet) printf(" FootprintFilter::getCandidates, getFootprintsInRegion %s", region) tbl.fp <- try(with(chromLoc, getFootprintsInRegion(fp, chrom, start, end))) if(!(class(tbl.fp) == "try-error")){ tbl.out <- rbind(tbl.out, mapMotifsToTFsMergeIntoTable(fp, tbl.fp)) } else{ warning("FootprintFinder error with region %s", region) closeDatabaseConnections(fp) return(NULL) } } # for region closeDatabaseConnections(fp) # Intersect the footprints with the rows in the matrix candidate.tfs <- NA_character_ if(nrow(tbl.out) > 0) candidate.tfs <- sort(unique(unlist(strsplit(tbl.out$tf, ";")))) return(list("tfs" = candidate.tfs, "tbl" = tbl.out)) }) # getCandidates #---------------------------------------------------------------------------------------------------- .parseChromLocString <- function(chromLocString) { tokens.0 <- strsplit(chromLocString, ":", fixed=TRUE)[[1]] stopifnot(length(tokens.0) == 2) chrom <- tokens.0[1] if(!grepl("chr", chrom)) chrom <- sprintf("chr%s", chrom) tokens.1 <- strsplit(tokens.0[2], "-")[[1]] stopifnot(length(tokens.1) == 2) start <- as.integer(tokens.1[1]) end <- as.integer(tokens.1[2]) return(list(chrom=chrom, start=start, end=end)) } # parseChromLocString #------------------------------------------------------------------------------------------------------------------------
c7b786c0b2982a6cbc07926fd9ea9fe0ea80a2bc
103cefcd0a90175d953b11b1a13a6c76adb28aef
/analyses/bb_analysis/models_stan_pepspp.R
954897387801d4210d72a476488f8a2df0b1d148
[]
no_license
lizzieinvancouver/ospree
8ab1732e1245762194db383cdea79be331bbe310
9622af29475e7bfaa1b5f6697dcd86e0153a0a30
refs/heads/master
2023-08-20T09:09:19.079970
2023-08-17T10:33:50
2023-08-17T10:33:50
44,701,634
4
1
null
null
null
null
UTF-8
R
false
false
4,164
r
models_stan_pepspp.R
##################################################### ## Taken from models_stan.R in early December 2018 ## ##################################################### ## With a few tweaks the PEP 725 code should still run ## ## Right now, each chunk is set up to run separately (model, then plotting) ## ######################### ## For PEP 725 species ## ######################### if(use.pep){ getspp <- subset(bb.stan, select=c("complex", "complex.wname")) allspp <- getspp[!duplicated(getspp), ] allspp <- allspp[order(allspp$complex),] pepspp <- c("Acer_pseudoplatanus", "Aesculus_hippocastanum", "Betula_pendula", "Corylus_avellana", "Fagus_sylvatica", "Larix_decidua", "Picea_abies", "Populus_tremula", "Prunus_padus","Quercus_robur", "Syringa_vulgaris") # gymnastics to renumber species somespp <- allspp[which(allspp$complex.wname %in% pepspp),] somespp$complex <- NULL somespp$complex <- seq(1:nrow(somespp)) bb.stan <- bb.stan[which(bb.stan$complex.wname %in% pepspp),] bb.stan$complex <- NULL dim(bb.stan) bb.stan <- merge(bb.stan, somespp, by="complex.wname") dim(bb.stan) datalist.bb <- with(bb.stan, list(y = resp, chill = chill, force = force, photo = photo, sp = complex, N = nrow(bb.stan), n_sp = length(unique(bb.stan$complex)) ) ) } ################################## ## PLOTTING For PEP 725 species ## ################################## # As of 11 July 2019 this runs if you first run models_stan.R through # to after this: source("source/bbstanleadin.R") ## # This code could easily be added to another file for the budburst ms if needed! ## if(use.pep){ getspp <- subset(bb.stan, select=c("complex", "complex.wname")) allspp <- getspp[!duplicated(getspp), ] allspp <- allspp[order(allspp$complex),] pepspp <- c("Acer_pseudoplatanus", "Aesculus_hippocastanum", "Betula_pendula", "Corylus_avellana", "Fagus_sylvatica", "Larix_decidua", "Picea_abies", "Populus_tremula", "Prunus_padus","Quercus_robur", "Syringa_vulgaris") # gymnastics to renumber species somespp <- allspp[which(allspp$complex.wname %in% pepspp),] somespp$complex <- NULL somespp$complex <- seq(1:nrow(somespp)) bb.stan <- bb.stan[which(bb.stan$complex.wname %in% pepspp),] bb.stan$complex <- NULL dim(bb.stan) bb.stan <- merge(bb.stan, somespp, by="complex.wname") dim(bb.stan) bb.stan$quickgdd <- bb.stan$force*bb.stan$resp bb.stan$utah <- bb.stan$chill*240 bb.stan$latbi <- paste(bb.stan$genus, bb.stan$species) ## GDD by chill unit plots, a few options pdf(file.path("figures/gddbyutah_pepspp.pdf"), width = 7, height = 5) ggplot(bb.stan, aes(utah, quickgdd, color=latbi)) + geom_point() + xlim(-10, 3300) + ylim(-55, 4500) + labs(x="Chilling (Utah units)", y="Growing degree days (GDD)", colour="Species") + geom_segment(y=-50, x=6.7*240, yend=-50, xend=12.5*240, col="black") + theme_classic() + theme(legend.text = element_text(face = "italic")) dev.off() ggplot(bb.stan, aes(chill, quickgdd, color=complex.wname)) + geom_point() + xlim(-1, 15) + # geom_segment(y=-15, x=4.95, yend=-15, xend=14.70, col="black") + # these numbers come from comparetopepsims.R: range(bp$chillutah)/240 geom_segment(y=-15, x=6.7, yend=-15, xend=12.5, col="black") + # these numbers come from comparetopepsims.R: quantile(bp$chillutah, c(0.1, 0.9))/240 (accurate as of 11 Jul 2019) theme_classic() ggplot(bb.stan, aes(chill, quickgdd, color=complex.wname)) + geom_point() + facet_wrap(~complex.wname, ncol=3) ggplot(subset(bb.stan, complex.wname=="Betula_pendula"), aes(chill, quickgdd, color=complex.wname)) + geom_point() + xlim(-1, 15) + geom_segment(y=-15, x=4.95, yend=-15, xend=14.70, col="black") + # these numbers come from comparetopepsims.R: range(bp$chillutah)/240 theme_classic() ## Model plot! load("stan/output/M1_daysBBnointer_2levelpepspp.Rda") m1.bb <- m2l.ni pdf(file.path(figpath, "M1nointer_wpepspp.pdf"), width = 7, height = 6) source("source/bb_muplot.R") dev.off() }
a192d72b3110a60b9318709093f758f7ee661d7c
16b2f87a1dddd5444ec822932c929bca44fd6e25
/code/chapter02.R
9ea96f69651bb7584e084c589a6ebf9add14dfc4
[]
no_license
vahidpartovinia/r2018
94d2299bb42763e5927492e79b887b06df668425
bb545af903fad986d2c819cced3872759e297b23
refs/heads/master
2020-03-21T14:41:49.856133
2018-07-04T15:52:43
2018-07-04T15:52:43
138,671,007
0
0
null
null
null
null
UTF-8
R
false
false
3,496
r
chapter02.R
remove(list=ls()) zipdata <- as.matrix(read.table("~/Desktop/zip.train")) dim(zipdata) #zipdata[1,1:16] #(matrix((zipdata[1,2:257]),nrow=16, ncol=16)) par(mar=c(0,0,0,0)) image((matrix((zipdata[1,2:257]),nrow=16, ncol=16))) image((matrix((zipdata[1,2:257]),nrow=16, ncol=16))[,16:1],col = gray((0:255)/255)) Seems we have the negative image. image((matrix(( - zipdata[1,2:257]), nrow=16, ncol=16))[,16:1], col = gray((0:255)/255), axes=FALSE) zipdata3 <- zipdata[zipdata[,1]==3,] zipdata8 <- zipdata[zipdata[,1]==8,] nrow(zipdata3) set.seed(10) random3 <- sample(1:nrow(zipdata3),size=10) zipdata3stack <- matrix(zipdata3[random3[1],2:257], 16, 16)[,16:1] dim(zipdata3stack) for (i in 2:length(random3)) { zipdata3stack <- cbind(zipdata3stack, matrix(zipdata3[random3[i],2:257], 16, 16)[,16:1]) } image(zipdata3stack) par(mar=c(0,10,0,10)) image(-zipdata3stack, col= gray((0:255)/255),axes=FALSE) set.seed(10) random8 <- sample(1:nrow(zipdata8),size=10) zipdata8stack <- matrix(zipdata8[random3[1],2:257], 16, 16)[,16:1] dim(zipdata8stack) for (i in 2:length(random8)) { zipdata8stack <- rbind(zipdata8stack, matrix(zipdata8[random8[i],2:257], 16, 16)[,16:1]) } par(mar=c(5,0,5,0)) image(-zipdata8stack, col= gray((0:255)/255),axes=FALSE) X <- as.data.frame(zipdata[,2:257]) y <- zipdata[,1] X_pca<- princomp(X,2) X_pred <- predict(X_pca) plot(X_pca) index <- (y==1) | (y==0) plot( X_pred[index,1], X_pred[index,2]) plot( X_pred[y==1,1], X_pred[y==1,2], pch="1",col="red",xlim=c(-20,10), ylim=c(-15,10)) points( X_pred[y==0,1], X_pred[y==0,2], pch="0", col="blue") index <- (y==3) | (y==8) plot( X_pred[y==3,1], X_pred[y==3,2], pch="3",col=adjustcolor("red", alpha=0.2),xlim=c(-20,10), ylim=c(-15,10)) points( X_pred[y==8,1], X_pred[y==8,2], pch="8", col=adjustcolor("blue", alpha=0.2)) require(MASS) xy <- as.data.frame(zipdata) colnames(xy) <- c("digit",paste("pixel_",1:256,sep="")) xy$digit <- as.factor(xy$digit) xy_lda <- lda(digit~.,data=xy) xy_pred <- predict(xy_lda)$x index <- (y==1) | (y==0) plot( xy_pred[index,1], xy_pred[index,2]) plot( xy_pred[y==1,1], xy_pred[y==1,2], pch="1",col="red",xlim=c(-10,10), ylim=c(-5,5)) points( xy_pred[y==0,1], xy_pred[y==0,2], pch="0", col="blue") library(scatterplot3d) s<-scatterplot3d( xy_pred[y==1,1], xy_pred[y==1,2], xy_pred[y==1,3],color="red", pch="1",xlim=c(-10,10), ylim=c(-10,10), zlim=c(-10,10)) s$points3d( xy_pred[y==0,1], xy_pred[y==0,2], xy_pred[y==0,3],col="blue", pch="0") #install.packages("mylibrary") require(e1071) plot(xy_pred[,1],xy_pred[,2],pch=paste(round(y)),col=adjustcolor((round(y+1)), alpha=0.2)) plot(xy_pred[y==9,1],xy_pred[y==9,2],pch="9",col=2,xlim=c(-10,10),ylim=c(-10,10)) points(xy_pred[y==4,1],xy_pred[y==4,2],pch="4",col=1) zip_pc <- rbind(xy_pred[y==9,1:2],xy_pred[y==4,1:2]) dim(zip_pc) zip_pc <- cbind(rep(c(9,4),c(sum(y==9),sum(y==4))), zip_pc) zip_pc <- as.data.frame(zip_pc) colnames(zip_pc) <- c("digit", "pc1", "pc2") zip_pc$digit <- as.factor(zip_pc$digit) svm.model <- svm (digit~., data=zip_pc, kernel="linear") n=50 zip_pc_test <- expand.grid(seq(-10,10,length=n),seq(-10,10,length=n)) colnames(zip_pc_test) <- c("pc1","pc2") svm.pred <- predict(svm.model, zip_pc_test) plot(zip_pc_test[,1],zip_pc_test[,2], col=svm.pred,pch=paste(svm.pred)) svm.model <- svm (digit~., data=zip_pc, kernel="radial") svm.pred <- predict(svm.model, zip_pc_test) plot(zip_pc_test[,1],zip_pc_test[,2], col=svm.pred,pch=paste(svm.pred))
14541051259e4c073a8a003806927db5a94cd29b
6e88b915929d4d667afc5ac3436c875f521ff61b
/ProblemSets/PS4/PS4a_Hopewell.R
865136afc4a4992a3a26bb6de59074001d4102c0
[ "MIT" ]
permissive
AudreyHopewell/DScourseS20
ce37aa0653bbc8579d75f79d80ef08a32f9ed885
36f210d6ea43d254b497deb7b204acce694cc3ba
refs/heads/master
2020-12-13T11:37:22.037791
2020-04-30T18:11:19
2020-04-30T18:11:19
234,405,586
0
0
MIT
2020-01-16T20:33:04
2020-01-16T20:28:03
null
UTF-8
R
false
false
369
r
PS4a_Hopewell.R
# importing nfl player stats system("wget -O nfl.json 'https://api.fantasy.nfl.com/v1/players /stats?statType=seasonStats&season=2010&week=1&format=json'") # printing the file system("cat nfl.json") # converting from JSON to dataframe library(jsonlite) mydf <- fromJSON('nfl.json') # examining the dataframe class(mydf) class(mydf$players) head(mydf$players)
3967fbcbef6ad87546b3f56ccbaa465454ae5e57
dffc300d3a66dede5afbf72e3eb1ba714976aea1
/src/Plot2_Revised.R
0e42434b576ab589d41f4dc92750ac4b0e01e1bd
[]
no_license
Hanna520/CS510_Qualifying_Exam
ff5eb2620c36c8a784a0f07aa9814f89b9f0870c
4cf8aa3c42dbe9b73699b8ca05ce3da36cdf2d1c
refs/heads/main
2023-02-23T09:40:39.555732
2021-01-31T04:58:07
2021-01-31T04:58:07
334,486,595
0
0
null
null
null
null
UTF-8
R
false
false
3,700
r
Plot2_Revised.R
# About this script: # This R script plots velocity vectors on the background of individual images from particle image velocimetry. The vectors fade from red to black based on the maximum velocity of the video clip (red) to zero (black). x and y are position data and u is the x-component of velocity and v is the y-component of velocity. # Load Required Packages library(grid) require(tiff) library(foreach) library(doParallel) library(pryr) library(raster) # Clear Workspace rm(list=ls()) # Move to working directory # setwd("/Users/Spectre/Dropbox/microPIV/prelimdata/subset1") scale <- 0.02 # Scale of the length of vector arrows angle <- 25 # Angle between the arrow head and body length <- 0.03 # Length of the arrow head sides start <- 41 # Start number of image sequence end <- 90 # End number of image sequence imageseq<-seq(start,end) # Constructs vector with image sequence for later reference # Construct a function for creating the color map for vectors myColorRamp <- function(colors, values) { v <- (values - min(values))/diff(range(values)) x <- colorRamp(colors)(v) rgb(x[,1], x[,2], x[,3], maxColorValue = 255) } # This section reads in files for pair 31, which had the highest magnitudes of any other pair, used to scale color on all pairs u31.1 <- read.csv("cs510-qe-january2021-Hanna520/practical/u31.csv",header=FALSE) u31 <- as.matrix(u31.1) v31.1 <- read.csv("cs510-qe-january2021-Hanna520/practical/v31.csv",header=FALSE) v31 <- as.matrix(v31.1) it31.1 <- sqrt(u31^2+v31^2) it31 <- replace(it31.1, is.na(it31.1), 0) cols31 <- myColorRamp(c("black", "red"), it31) #Constructs color map rm(u31.1, v31.1, u31, v31, it31) # The following code plots image and PIV data for all 50 data sets # Since the plot of each dataset is independent, we can use parallelization to optimize the speed filepath <- "cs510-qe-january2021-Hanna520/practical/" x_files <- list() y_files <- list() u_files <- list() v_files <- list() images <- list() w_values <- list() foreach(i = 1:50) %dopar%{ # Constructs image file name nametiff <- ifelse(imageseq[i]<100, paste0(filepath,"tunicate_PIV_07_14_C001H001S0001_images0000", imageseq[i],".tif"), paste0(filepath,"tunicate_PIV_07_14_C001H001S0001_images000", imageseq[i],".tif")) # Loads individual files xfile <- read.csv(paste0(filepath, "x", i, ".csv"),header=FALSE) x_files[[i]] <- as.matrix(xfile) yfile <- read.csv(paste0(filepath, "y", i, ".csv"),header=FALSE) y_files[[i]] <- as.matrix(yfile) ufile <- read.csv(paste0(filepath, "u", i, ".csv"),header=FALSE) u_files[[i]] <- as.matrix(ufile) vfile <- read.csv(paste0(filepath, "v", i, ".csv"),header=FALSE) v_files[[i]] <- as.matrix(vfile) images[[i]] <- readTIFF(nametiff) # Calculates velocity magnitudes w_values[[i]] <- sqrt(u_files[[i]]^2+v_files[[i]]^2) # Plots and save Image and PIV data new_tiff <- str_remove(nametiff, filepath) tiff(file=paste0("results/",new_tiff,".tiff"),res=100) par(mar=c(0,0,0,0)) # Sets margins of plot in frame plot(c(min(x_files[[i]]),max(x_files[[i]])), c(min(y_files[[i]]),max(y_files[[i]])), pch=".",xlim=c(0,10),ylim=c(-9,5), xlab=c(" "),ylab=c(" ")) # Sets initial plot plot(raster(images[[i]],xmn=min(x_files[[i]]),ymn=min(y_files[[i]]), xmx=max(x_files[[i]]),ymx=max(y_files[[i]])), col=cols31) # Draws background image arrows(x_files[[i]], y_files[[i]], x_files[[i]]+scale*u_files[[i]], y_files[[i]]+scale*v_files[[i]], angle=10, length=length, col=cols31, code=1) #Draws PIV arrows dev.off() }
37ba50be84ae95da52337636161bfaff1905d221
377a111fb7585caf110377625ad0e261a44e93ed
/nick/toolbox/ddModel/ddClass0.1.1.r
e26b7786750687723482e1e90725f44d616971bb
[]
no_license
gasduster99/theses
ba385499ea0a502b9067c243f7100d82ff1ef4ce
9c5f8b5d7564292e2e36547ed8d5563a8639f158
refs/heads/master
2023-08-25T18:14:09.741032
2023-08-22T05:33:06
2023-08-22T05:33:06
217,375,576
0
0
null
null
null
null
UTF-8
R
false
false
8,531
r
ddClass0.1.1.r
# suppressWarnings(suppressMessages( library(R6, quietly=TRUE) )) suppressWarnings(suppressMessages( library(deSolve, quietly=TRUE) )) # source('modelFunk.r') source('outputFunk.r') source('classifyFunk.r') source('parSelfParFunk.r') source('optimizeFunk.r') # #CLASS # # ddModel = R6Class("DDModel", lock_objects=FALSE, # public = list( #pop N = NA, N0 = NA, B = NA, B0 = NA, N0Funk = NA, B0Funk = NA, #time time = NA, #model lsdo = NA, lq = 0, #log proportionality constant between cpue and N model = list(observation="LN"), prior = list(), #functions #computational ODE_method = 'lsode', OPT_method = 'L-BFGS-B', # initialize = function( N0 = NA, B0 = NA, time = NA, derivs = NA, N0Funk = NA, B0Funk = NA, ... ){ #misc variable digestion misc = list(...) miscNames = names(misc) for(m in miscNames){ eval(parse( text=sprintf("self$%s=misc[[m]]", m) )) } #dNdt stopifnot(is.function(derivs)) private$dNdt_classify(derivs) #N0 if( is.function(N0Funk) ){ private$N0_classify(N0Funk) N0 = self$N0Funk() } #B0 if( is.function(B0Funk) ){ private$N0_classify(B0Funk) B0 = self$B0Funk() } #preallocate N self$N0 = N0 self$B0 = B0 self$time = time self$N = matrix(NA, nrow=length(time), ncol=1) self$B = matrix(NA, nrow=length(time), ncol=1) rownames(self$N) = sprintf("TIME %d", time) rownames(self$B) = sprintf("TIME %d", time) }, # iterate = function(method=self$ODE_method){ #method : optionally update the ODE method to be handed to the ode function (default 'rk4') # #value : nothing returned, but self$N is updated with current values #prechecking #digest and possibly change ode method self$ODE_method = method #N0 & B0 if( is.function(self$N0Funk) ){ self$N0=self$N0Funk() } if( is.function(self$B0Funk) ){ self$B0=self$B0Funk() } #last minute allocation and variable updates #self$N0 = N0 #self$B0 = B0 self$N = matrix(NA, nrow=length(self$time), ncol=1) self$B = matrix(NA, nrow=length(self$time), ncol=1) rownames(self$N) = sprintf("TIME %d", self$time) rownames(self$B) = sprintf("TIME %d", self$time) #solve #capture.output( self$N <- ode(self$N0, self$time, private$dNdt, parms=NULL, method=method)[,2], file="/dev/null" ) capture.output( out <- dede(c(self$N0, self$B0), self$time, private$dNdt, parms=NULL, method=method), file="/dev/null" ) self$N = out[,2] self$B = out[,3] }, # optimize = optimize, # printer = printSelf, printSelf = function(ins=c()){ self$printer(ins, outs=c( "iterate", "optimize", "model", "prior", "like", "plotQuan", "plotMean", "plotBand", "plotRS", "quan", "N0Funk", "B0Funk", "save", "load", "printer" )) }, plotQuan = plotQuan, plotMean = plotMean, plotBand = plotBand, plotRS = plotRS, # save = function(fileName){ saveRDS(self, file=fileName) }, load = function(fileName){ readRDS(fileName) }, # like = function(data){ sum(private$dLikes[[self$model$observation]](self, data)) } ), # private = list( ## #dNdt = NA, # selfToPar = selfToPar, parToSelf = parToSelf, #NOTE: parValues should be passed with names # dNdt_classify = dNdt_classify, N0_classify = N0_classify, classify = classify, # dLikes = dLikes, qLikes = qLikes ) ) # #TEST # # w = function(a, wi, k){ wi*(1-exp(-k*a)) } # f = function(t, Y, lalpha, lbeta, gamma, a0, wi, k, catch, B0){ #linearly interpolate catches ft = floor(t) q = (t-ft) Cl = catch[ft] Cu = catch[ft+1] C = q*Cu + (1-q)*Cl if(q==0){ C=Cl } # N = Y[1] B = Y[2] # if( (t-a0)<1){ Blag = B0 }else{ Blag = lagvalue(t-a0)[2] } # #R = exp(lalpha)*Blag*(1-exp(lbeta)*gamma*Blag)^(1/gamma) alpha = exp(lalpha) beta = exp(lbeta) R = alpha*Blag*(1-gamma*beta*Blag)^(1/gamma) # print(C) out = c(N=NA, B=NA) out[1] = R - (M+C)*N out[2] = wi*(1-exp(-k*a0))*R + k*(wi*N-B) - (M+C)*B # return( list(out) ) } # g = function(t, Y, p){ #alpha, beta, gamma, a0, wi, k, catch){ #linearly interpolate catches ft = floor(t) q = (t-ft) Cl = catch[ft] Cu = catch[ft+1] C = q*Cu + (1-q)*Cl if(q==0){ C=Cl } # N = Y[1] B = Y[2] # if( (t-a0)<1){ Blag = P0 }else{ Blag = lagvalue(t-a0)[2] } # #R = exp(lalpha)*Blag*(1-exp(lbeta)*gamma*Blag)^(1/gamma) R = alpha*Blag*(1-gamma*beta*Blag)^(1/gamma) # out = c(N=NA, B=NA) out[1] = R - (M+C)*N out[2] = wi*(1-exp(-k*a0))*R + k*(wi*N-B) - (M+C)*B # return( list(out) ) } # Fs = c(seq(0.2, 2, length.out=15), rev(seq(0.1, 2, length.out=15)), rep(0.1, 15)) catch = Fs # M = 0.2 k = 0.2 # wi = 1 a0 = 2 TT = 45 # alpha = 5 beta = 1 gamma = -0.99 #gamma=0 is a problem #gamma=-1 is BH in limit; a problem otherwise # Rtil = alpha/(beta*(1+gamma)) * (1-gamma/(1+gamma))^(1/gamma) N0 = Rtil/(M)#+FF) P0 = (w(a0, wi, k)*Rtil + k*wi*N0)/(k+M)#+FF) # dOut = dede(c(N0, P0), 1:TT, g, NULL, method="lsode") # dat = ddModel$new( derivs=f, N0Funk=function(lalpha, lbeta, gamma){ # alpha = exp(lalpha) beta = exp(lbeta) # ( alpha/(beta*(1+gamma)) * (1-gamma/(1+gamma))^(1/gamma) )/M }, B0Funk=function(lalpha, lbeta, gamma, wi, k){ # alpha = exp(lalpha) beta = exp(lbeta) # ( wi*(1-exp(-k*a0))*(alpha/(beta*(1+gamma))*(1-gamma/(1+gamma))^(1/gamma)) + k*wi*(alpha/(beta*(1+gamma))*(1-gamma/(1+gamma))^(1/gamma))/M )/(k+M) }, time=1:TT, catch=Fs, a0=a0, M=M, wi=wi, k=k, #constants lalpha=log(alpha), lbeta=log(beta), gamma=0.2, #parameters lq=log(0.00049), lsdo=log(0.01160256) #nuisance parameters ) dat$iterate() # test = ddModel$new( derivs=f, N0Funk=function(lalpha, lbeta, gamma){ # alpha = exp(lalpha) beta = exp(lbeta) # ( alpha/(beta*(1+gamma)) * (1-gamma/(1+gamma))^(1/gamma) )/M }, B0Funk=function(lalpha, lbeta, gamma, wi, k){ # alpha = exp(lalpha) beta = exp(lbeta) # ( wi*(1-exp(-k*a0))*(alpha/(beta*(1+gamma))*(1-gamma/(1+gamma))^(1/gamma)) + k*wi*(alpha/(beta*(1+gamma))*(1-gamma/(1+gamma))^(1/gamma))/M )/(k+M) }, time=1:TT, catch=Fs, a0=a0, M=M, wi=wi, k=k, #constants lalpha=log(alpha), lbeta=log(beta), gamma=gamma,#parameters lq=log(0.00049), lsdo=log(0.01160256) #nuisance parameters ) test$iterate() ## #cpue = c(1.78, 1.31, 0.91, 0.96, 0.88, 0.90, 0.87, 0.72, 0.57, 0.45, 0.42, 0.42, 0.49, 0.43, 0.40, 0.45, 0.55, 0.53, 0.58, 0.64, 0.66, 0.65, 0.63) #catch = c(94, 212, 195, 383, 320, 402, 366, 606, 378, 319, 309, 389, 277, 254, 170, 97, 91, 177, 216, 229, 211, 231, 223) # #test$time = 1:length(cpue) #test$catch = catch #test$iterate() # library(pracma) # d = exp( rnorm(TT, dat$lq+log(dat$B), exp(dat$lsdo)) ) #exp(log(dat$B)+dat$lq+rlnorm(TT) # test$optimize( d, c('lsdo', 'lalpha', 'lbeta'), lower = c(-10, log(eps()), log(eps())), upper = c(10, log(10), log(10)), gaBoost = list(run=10, parallel=T, popSize=5*10^3), fitQ = F, cov = T ) test$printSelf() # plot(d) test$plotMean(add=T) test$plotBand() # dat$plotMean(add=T, col='red') ## #test$optimize( d, # c('lsdo', 'lalpha', 'lbeta', 'gamma'), # lower = c(-10, log(eps()), log(eps()), -1), # upper = c(10, log(10), log(10), 2), # gaBoost = list(run=10, parallel=T, popSize=5*10^3), # fitQ = F, # cov = T #) # ### ##test$optimize( d, ## c('lsdo', 'lalpha', 'lbeta'), ## lower = c(-10, log(eps()), log(eps())), ## upper = c(10, log(10), log(10)), ## #gaBoost = list(run=10, parallel=T, popSize=5*10^3), ## fitQ = T, ## cov = T ##) # ## #test$printSelf() #test$plotMean(add=T, col='blue') # dev.new() test$plotQuan(function(N){N}) dev.new() test$plotQuan(function(N, B){B/N})
faf17e92bf5a2804d55feeb026d3959ed200c0fc
52d489c2491476428a9a0cd11b200c63be4794eb
/man/plotts.sample.wge.Rd
faa15c2a62378529c8e51222acab7e63e447bc61
[]
no_license
cran/tswge
2ffabc4794652937b86a701ec4772b2e07697531
435566d44f7652da48e9d257040fc78b47a08101
refs/heads/master
2023-04-01T22:52:04.649970
2023-01-31T12:10:02
2023-01-31T12:10:02
236,955,358
0
1
null
null
null
null
UTF-8
R
false
false
1,672
rd
plotts.sample.wge.Rd
\name{plotts.sample.wge} \alias{plotts.sample.wge} \title{Plot Data, Sample Autocorrelations, Periodogram, and Parzen Spectral Estimate} \description{For a given realization, this function plots the data, and calculates and plots the sample autocorrelations, periodogram, and Parzen window spectral estimator in a 2x2 array of plots.} \usage{plotts.sample.wge(x, lag.max = 25, trunc = 0, arlimits=FALSE,speclimits=c(0,0), periodogram=FALSE)} \arguments{ \item{x}{A vector containing the realization} \item{lag.max}{The maximum lag at which to calculate the sample autocorrelations} \item{trunc}{The truncation point M for the Parzen spectral estimator. If M=0 theN M=2sqrt(n). If M>0 then M is the value entered} \item{arlimits}{Logical variable. TRUE plots 95 percent limit lines on sample autocorrelation plots} \item{periodogram}{Logical variable. TRUE plots periodogram, default=FALSE} \item{speclimits}{User supplied limits for Parzen spectral density and periodogram, default=function decides limits} } \value{ \item{xbar}{The sample mean of the realization} \item{autplt }{A vector containing sample autocorrelations from 0, 1, ..., aut.lag} \item{freq }{A vector containing the frequencies at which the periodogram and window estimate are calculated} \item{db }{Periodogram (in dB) calculated at the frequecies in freq} \item{freq }{Parzen spectral estimate (in dB) calculated at the frequecies in freq} } \references{"Applied Time Series Analysis with R, 2nd edition" by Woodward, Gray, and Elliott} \author{Wayne Woodward} \examples{data(wages) plotts.sample.wge(wages,trunc=0)} \keyword{ Plot } \keyword{ Periodogram } \keyword{ Parzen }
39aa627015bee7d6230ec9fffefa270b6e2b46aa
0a906cf8b1b7da2aea87de958e3662870df49727
/grattan/inst/testfiles/IncomeTax/libFuzzer_IncomeTax/IncomeTax_valgrind_files/1610051423-test.R
e6d4a9ff146446828e103de4c719967a279c9ad0
[]
no_license
akhikolla/updated-only-Issues
a85c887f0e1aae8a8dc358717d55b21678d04660
7d74489dfc7ddfec3955ae7891f15e920cad2e0c
refs/heads/master
2023-04-13T08:22:15.699449
2021-04-21T16:25:35
2021-04-21T16:25:35
360,232,775
0
0
null
null
null
null
UTF-8
R
false
false
1,467
r
1610051423-test.R
testlist <- list(rates = numeric(0), thresholds = c(NaN, -1.23414719310911e-30, 2.56680426183462e-301, -4.9540049074147e-33, -1.26836459270829e-30, 2.1788294981599e-321, -1.26836459066847e-30, -4.76141252968046e-33, -1.26836459270829e-30, 8.81442566340335e-280, -2.82145547645109e-277, 1.67129192517088e-112, 2.64121103568221e-301, 1.24660111018731e-266, -2.95250654929583e-135, -1.26836459245897e-30, NaN, 3.6634314009942e-305, 4.00791842555784e-306, -1.2683642165418e-30, 2.39958945525286e-309, 5.68604456976406e-270, -1.26836459270829e-30, -1.26836421360307e-30, 2.39958945525286e-309, 4.35857935464267e-311, 3.56048353890995e-306, -1.23416654681114e-30, -1.26836459270829e-30, -7.2239847844844e-287, -5.48681743872625e+303, 3.65398847701729e-306, NaN, -1.23414195041578e-30, -1.80650535611164e+307, -9.7757963632732e-150, NaN, NaN, NaN, 3.02610044756979e-306, -2.2962031506993e-156, -2.30331110816477e-156, -2.30331110816477e-156, -2.30331110763906e-156, -2.30331110816477e-156, -5.96890298689e+306, 1.390652843099e-309, -5.16216864106284e-306, -8.81442986644817e-280, -1.85907762421774e-183, -1.09850957322306e-314, -2.35343736497682e-185, 7036874417766.4, -2.35343736826454e-185, 2.95466177864628e-306, -2.35343736825169e-185, -5.34349793087407e-187, -2.35343736826454e-185, 2.55299237240191e-156, 2.47192511527755e-94, NaN, NaN, NaN, 1.25986739689518e-321, 0, 0, 0, 0, 0), x = -Inf) result <- do.call(grattan::IncomeTax,testlist) str(result)
4036d598882380697ff38afe7f6f9bcb6d83001c
8734b26adb5975f7b6e7685cf899d8b23599a154
/man/remove_label.Rd
df69662f117542610e054f63fb9709364c5d9911
[]
no_license
strengejacke/sjlabelled
3606b01702e59a6ac47459fd216ab468f777c266
548fa397bd013ec7e44b225dd971d19628fdc866
refs/heads/master
2022-11-12T10:34:47.538335
2022-10-23T20:16:20
2022-10-23T20:16:20
92,868,296
78
16
null
2020-11-25T14:50:47
2017-05-30T19:24:17
R
UTF-8
R
false
true
1,037
rd
remove_label.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/remove_label.R \name{remove_label} \alias{remove_label} \title{Remove variable labels from variables} \usage{ remove_label(x, ...) } \arguments{ \item{x}{A vector or data frame.} \item{...}{Optional, unquoted names of variables that should be selected for further processing. Required, if \code{x} is a data frame (and no vector) and only selected variables from \code{x} should be processed. You may also use functions like \code{:} or tidyselect's select-helpers. See 'Examples'.} } \value{ \code{x} with removed variable labels } \description{ Remove variable labels from variables. } \examples{ data(efc) x <- efc[, 1:5] get_label(x) str(x) x <- remove_label(x) get_label(x) str(x) } \seealso{ \code{\link{set_label}} to manually set variable labels or \code{\link{get_label}} to get variable labels; \code{\link{set_labels}} to add value labels, replacing the existing ones (and removing non-specified value labels). }
11146e6e8004ffeefe6b0728e1ed7517b022d88f
20fb140c414c9d20b12643f074f336f6d22d1432
/man/NISTslugPerCubFtTOkgPerCubMeter.Rd
9481a2ee1ce81e5c7430db7407864c92efc9479a
[]
no_license
cran/NISTunits
cb9dda97bafb8a1a6a198f41016eb36a30dda046
4a4f4fa5b39546f5af5dd123c09377d3053d27cf
refs/heads/master
2021-03-13T00:01:12.221467
2016-08-11T13:47:23
2016-08-11T13:47:23
27,615,133
0
0
null
null
null
null
UTF-8
R
false
false
922
rd
NISTslugPerCubFtTOkgPerCubMeter.Rd
\name{NISTslugPerCubFtTOkgPerCubMeter} \alias{NISTslugPerCubFtTOkgPerCubMeter} \title{Convert slug per cubic foot to kilogram per cubic meter } \usage{NISTslugPerCubFtTOkgPerCubMeter(slugPerCubFt)} \description{\code{NISTslugPerCubFtTOkgPerCubMeter} converts from slug per cubic foot (slug/ft3) to kilogram per cubic meter (kg/m3) } \arguments{ \item{slugPerCubFt}{slug per cubic foot (slug/ft3) } } \value{kilogram per cubic meter (kg/m3) } \source{ National Institute of Standards and Technology (NIST), 2014 NIST Guide to SI Units B.8 Factors for Units Listed Alphabetically \url{http://physics.nist.gov/Pubs/SP811/appenB8.html} } \references{ National Institute of Standards and Technology (NIST), 2014 NIST Guide to SI Units B.8 Factors for Units Listed Alphabetically \url{http://physics.nist.gov/Pubs/SP811/appenB8.html} } \author{Jose Gama} \examples{ NISTslugPerCubFtTOkgPerCubMeter(10) } \keyword{programming}
a37cc36a1bc383a9f27eed23972d2d2483cbda3d
4bbf80bcb22f39e35c7dbfa0089d557be3263100
/Scripts/Strict/Maxent_strict.R
a55e985d21bf4d3eb295a4c62cc7589ecc9a25dc
[]
no_license
ebaken/Chapter3-1
a0dc5102ebda2229deaf172b7c17f4e614ebd065
b1e703e80e389230e3c23fb24bf7359729345c8e
refs/heads/master
2020-05-17T11:55:04.918798
2019-04-26T21:00:21
2019-04-26T21:00:21
null
0
0
null
null
null
null
UTF-8
R
false
false
10,538
r
Maxent_strict.R
############################### ### MAXENT SCRIPT DRAFT for strict microhabitats only ####### ############################### # MAXENT MODELS AND EVALUATIONS library(dismo); library(rJava); library(maptools) library(raster) ###### maxent pipeline ######### # load variables # READ IN DATA # ClimateData <- stack('./Analysis_Scripts/Chapter3/Climate Data/SDM/AllDataTogCGTiff.gri') # crop data to reasonable extent max.lat = 140 min.lat = -140 max.lon = 70 min.lon = -20 geographic.extent <- extent(x = c(min.lat, max.lat, min.lon, max.lon)) predictors.crop <- crop(x = ClimateData, y = geographic.extent) predictors <- predictors.crop # load file with presence points ArbPointsS <- rgdal::readOGR("./Analysis_Scripts/Chapter3/Scripts/Strict/Points/Arb_Points_strict/chull.shp") TerrPointsS <- rgdal::readOGR("./Analysis_Scripts/Chapter3/Scripts/Strict/Points/Terr_Points_strict/chull.shp") AquaPointsS <- rgdal::readOGR("./Analysis_Scripts/Chapter3/Scripts/Strict/Points/Aqua_Points_strict/chull.shp") CavePointsS <- rgdal::readOGR("./Analysis_Scripts/Chapter3/Scripts/Strict/Points/Cave_Points_strict/chull.shp") FossPointsS <- rgdal::readOGR("./Analysis_Scripts/Chapter3/Scripts/Strict/Points/Foss_Points_strict/chull.shp") SaxPointsS <- rgdal::readOGR("./Analysis_Scripts/Chapter3/Scripts/Strict/Points/Sax_Points_strict/chull.shp") # make into data frame for maxent ArbDF <- data.frame(ArbPointsS) ArbDF <- ArbDF[,1:2] TerrDF <- data.frame(TerrPointsS) TerrDF <- TerrDF[,1:2] AquaDF <- data.frame(AquaPointsS) AquaDF <- AquaDF[,1:2] CaveDF <- data.frame(CavePointsS) CaveDF <- CaveDF[,1:2] FossDF <- data.frame(FossPointsS) FossDF <- FossDF[,1:2] SaxDF <- data.frame(SaxPointsS) SaxDF <- SaxDF[,1:2] ## take out points outside of the extent area # like korea, italy, and water points #outliers <- extract(predictors, TerrPointsS) #out <- which(is.na(outliers)) #out #View(outliers) # arb outliers dropA <- c(34) ArbNew <- ArbDF[-dropA,] #terr outliers dropT <- c(16,37,71,98,114,135,145,164,165) TerrNew <- TerrDF[-dropT,] # aqua outliers dropW <- c(20,47,87) AquaNew <- AquaDF[-dropW,] # cave outliers dropC <- c(1,2,3,4,8,9,17) CaveNew <- CaveDF[-dropC,] # sax outliers dropS <- c(6) SaxNew <- SaxDF[-dropS,] # assign occurrence points occA <- ArbNew occA <- as.matrix(occA) foldA <- kfold(occA, k=5) occtestA <- occA[foldA == 1, ] occtrainA <- occA[foldA != 1, ] # assign occurrence points occT <- TerrNew occT <- as.matrix(occT) foldT <- kfold(occT, k=5) occtestT <- occT[foldT == 1, ] occtrainT <- occT[foldT != 1, ] # assign occurrence points occW <- AquaNew occW <- as.matrix(occW) foldW <- kfold(occW, k=5) occtestW <- occW[foldW == 1, ] occtrainW <- occW[foldW != 1, ] # assign occurrence points occC <- CaveNew occC <- as.matrix(occC) foldC <- kfold(occC, k=5) occtestC <- occC[foldC == 1, ] occtrainC <- occC[foldC != 1, ] # assign occurrence points occF <- FossDF occF <- as.matrix(occF) foldF <- kfold(occF, k=5) occtestF <- occF[foldF == 1, ] occtrainF <- occF[foldF != 1, ] # assign occurrence points occS <- SaxNew occS <- as.matrix(occS) foldS <- kfold(occS, k=5) occtestS <- occS[foldS == 1, ] occtrainS <- occS[foldS != 1, ] # maxent model # maxent model with 5 replicates ArbMod <- maxent(predictors, occtrainA, args=c("-J","-P",'replicates=5'), path="./Analysis_Scripts/Chapter3/ENM/Maxent_Files/ArbMod_strict") # tried with bootstrap and didnt improve AUC, but we may need to do later? #ArbModB <- maxent(predictors, occtrainA, args=c("-J","-P",'replicates=5','replicatetype=bootstrap'), #path="./Analysis_Scripts/Chapter3/ENM/Maxent_Files/ArbModB_strict") TerrMod <- maxent(predictors, occtrainT, args=c("-J","-P",'replicates=5'), path="./Analysis_Scripts/Chapter3/ENM/Maxent_Files/TerrMod_strict") AquaMod <- maxent(predictors, occtrainW, args=c("-J","-P",'replicates=5'), path="./Analysis_Scripts/Chapter3/ENM/Maxent_Files/AquaMod_strict") CaveMod <- maxent(predictors, occtrainC, args=c("-J","-P",'replicates=5'), path="./Analysis_Scripts/Chapter3/ENM/Maxent_Files/CaveMod_strict") FossMod <- maxent(predictors, occtrainF, args=c("-J","-P",'replicates=5'), path="./Analysis_Scripts/Chapter3/ENM/Maxent_Files/FossMod_strict") SaxMod <- maxent(predictors, occtrainS, args=c("-J","-P",'replicates=5'), path="./Analysis_Scripts/Chapter3/ENM/Maxent_Files/SaxMod_strict") # see the maxent results in a browser - doesnt work for replications ArbMod #variable importance plot plot(ArbMod) # response curves response(ArbMod) #predict to entire dataset # arboreal prediction ArbPrediction <- predict(ArbMod, predictors, progress="text", filename='./Analysis_Scripts/Chapter3/ENM/Prediction/ArbMod_strict_prediction.grd', overwrite=T) ArbPredictionAverage <- mean(ArbPrediction) writeRaster(ArbPredictionAverage, paste0('./Analysis_Scripts/Chapter3/ENM/Prediction/ArbMod_prediction_strict'), overwrite=T) # terrestrial prediction TerrPrediction <- predict(TerrMod, predictors, progress="text", filename='./Analysis_Scripts/Chapter3/ENM/Prediction/TerrMod_strict_prediction.grd', overwrite=T) TerrPredictionAverage <- mean(TerrPrediction) writeRaster(TerrPredictionAverage, paste0('./Analysis_Scripts/Chapter3/ENM/Prediction/TerrMod_prediction_strict'), overwrite=T) # Aquatic prediction AquaPrediction <- predict(AquaMod, predictors, progress="text", filename='./Analysis_Scripts/Chapter3/ENM/Prediction/AquaMod_strict_prediction.grd', overwrite=T) AquaPredictionAverage <- mean(AquaPrediction) writeRaster(AquaPredictionAverage, overwrite=T, paste0('./Analysis_Scripts/Chapter3/ENM/Prediction/AquaMod_prediction_strict')) # cave prediction CavePrediction <- predict(CaveMod, predictors, progress="text", filename='./Analysis_Scripts/Chapter3/ENM/Prediction/CaveMod_strict_prediction.grd', overwrite=T) CavePredictionAverage <- mean(CavePrediction) writeRaster(CavePredictionAverage, paste0('./Analysis_Scripts/Chapter3/ENM/Prediction/CaveMod_prediction_strict')) # Fossorial prediction FossPrediction <- predict(FossMod, predictors, progress="text", filename='./Analysis_Scripts/Chapter3/ENM/Prediction/FossMod_strict_prediction.grd', overwrite=T) FossPredictionAverage <- mean(FossPrediction) writeRaster(FossPredictionAverage, paste0('./Analysis_Scripts/Chapter3/ENM/Prediction/FossMod_prediction_strict')) # Saxicolous prediction SaxPrediction <- predict(SaxMod, predictors, progress="text", filename='./Analysis_Scripts/Chapter3/ENM/Prediction/SaxMod_strict_prediction.grd', overwrite=T) SaxPredictionAverage <- mean(SaxPrediction) writeRaster(SaxPredictionAverage, paste0('./Analysis_Scripts/Chapter3/ENM/Prediction/SaxMod_prediction_strict')) # plot occurrence points on top of the niche map for specific reason, just checking # points(occ) ############# #testing points ############# #background data bg <- randomPoints(predictors, 1000) #simplest way to use 'evaluate' # evaluate every model from the replication in arb AS1 <- evaluate(ArbMod@models[[1]], p=occtestA, a=bg, x=predictors) AS1 # 0.91 AS2 <- evaluate(ArbMod@models[[2]], p=occtestA, a=bg, x=predictors) AS2 # 0.90 AS3 <- evaluate(ArbMod@models[[3]], p=occtestA, a=bg, x=predictors) AS3 # 0.90 AS4 <- evaluate(ArbMod@models[[4]], p=occtestA, a=bg, x=predictors) AS4 # 0.91 AS5 <- evaluate(ArbMod@models[[5]], p=occtestA, a=bg, x=predictors) AS5 # 0.89 # evaluate every model from the replication in terr TS1 <- evaluate(TerrMod@models[[1]], p=occtestT, a=bg, x=predictors) TS1 # 0.83 TS2 <- evaluate(TerrMod@models[[2]], p=occtestT, a=bg, x=predictors) TS2 # 0.81 TS3 <- evaluate(TerrMod@models[[3]], p=occtestT, a=bg, x=predictors) TS3 # 0.83 TS4 <- evaluate(TerrMod@models[[4]], p=occtestT, a=bg, x=predictors) TS4 # 0.81 TS5 <- evaluate(TerrMod@models[[5]], p=occtestT, a=bg, x=predictors) TS5 # 0.82 # evaluate every model from the replication in aquatic WS1 <- evaluate(AquaMod@models[[1]], p=occtestW, a=bg, x=predictors) WS1 # 0.92 WS2 <- evaluate(AquaMod@models[[2]], p=occtestW, a=bg, x=predictors) WS2 # 0.92 WS3 <- evaluate(AquaMod@models[[3]], p=occtestW, a=bg, x=predictors) WS3 # 0.91 WS4 <- evaluate(AquaMod@models[[4]], p=occtestW, a=bg, x=predictors) WS4 # 0.93 WS5 <- evaluate(AquaMod@models[[5]], p=occtestW, a=bg, x=predictors) WS5 # 0.92 # evaluate every model from the replication in cave CS1 <- evaluate(CaveMod@models[[1]], p=occtestC, a=bg, x=predictors) CS1 # 0.98 CS2 <- evaluate(CaveMod@models[[2]], p=occtestC, a=bg, x=predictors) CS2 # 0.98 CS3 <- evaluate(CaveMod@models[[3]], p=occtestC, a=bg, x=predictors) CS3 # 0.98 CS4 <- evaluate(CaveMod@models[[4]], p=occtestC, a=bg, x=predictors) CS4 # 0.98 CS5 <- evaluate(CaveMod@models[[5]], p=occtestC, a=bg, x=predictors) CS5 # 0.98 # evaluate every model from the replication in fossorial FS1 <- evaluate(FossMod@models[[1]], p=occtestF, a=bg, x=predictors) FS1 # 0.89 FS2 <- evaluate(FossMod@models[[2]], p=occtestF, a=bg, x=predictors) FS2 # 0.82 FS3 <- evaluate(FossMod@models[[3]], p=occtestF, a=bg, x=predictors) FS3 # 0.92 FS4 <- evaluate(FossMod@models[[4]], p=occtestF, a=bg, x=predictors) FS4 # 0.91 FS5 <- evaluate(FossMod@models[[5]], p=occtestF, a=bg, x=predictors) FS5 # 0.87 # evaluate every model from the replication in sax SS1 <- evaluate(SaxMod@models[[1]], p=occtestS, a=bg, x=predictors) SS1 # 0.68 SS2 <- evaluate(SaxMod@models[[2]], p=occtestS, a=bg, x=predictors) SS2 # 0.88 SS3 <- evaluate(SaxMod@models[[3]], p=occtestS, a=bg, x=predictors) SS3 # 0.86 SS4 <- evaluate(SaxMod@models[[4]], p=occtestS, a=bg, x=predictors) SS4 # 0.85 SS5 <- evaluate(SaxMod@models[[5]], p=occtestS, a=bg, x=predictors) SS5 # 0.89 # THESE ARE OTHER WAYS TO EVALUATE, BUT GIVE THE SAME RESULT # alternative 1 # extract values pvtest <- data.frame(extract(predictors, occtestV)) avtest <- data.frame(extract(predictors, bg)) e2 <- evaluate(p=pvtest, a=avtest) e2 # alternative 2 # predict to testing points testp <- predict(me, pvtest) head(testp) testa <- predict(me, avtest) e3 <- evaluate(p=testp, a=testa) e3 threshold(e3) plot(e3, 'ROC') # look into more... v <- extract(predictors, VegNew) mess <-mess(predictors, v, full=FALSE) plot(mess) mess
18feea92999e4acaf5fad1701c8e47c865c43dfd
006666eece54ebcbfc1f29b56f8146f808c781a1
/method/figure_bslmm_lmm_notcoincide.R
059fe8ac2842e9e84f5bac28dfc51e55b51fe426
[]
no_license
MoisesExpositoAlonso/nap
d56d278bcc4c7e49fb3a8d4497df962a0ed94004
8fcbe7aa89f97bcf615943318fd1daa931e7a34f
refs/heads/master
2020-03-28T09:11:16.076766
2019-05-13T00:16:13
2019-05-13T00:16:13
148,019,561
0
0
null
null
null
null
UTF-8
R
false
false
1,251
r
figure_bslmm_lmm_notcoincide.R
################################################################################ ## Run nap MCMC inference over simulated traits ################################################################################ ## Load packages library(devtools) library(dplyr) library(ggplot2) library(cowplot) library(latex2exp) library(coda) library(Rcpp) library(bigmemory) library(moiR) load_all('.') ####************************************************************************#### #### Genomematrix and fam ##### x<-attach.big.matrix("databig/example.desc") fam<-read.table("databig/simexample.fam",header=T) pheno<-colnames(fam)[6] pheno<-"b0.01_a0.01_p0_svar0.01_epi0.9_mod1_h20.96" y<-fam[,pheno] hyp<-.read_gemma(folder="output",name=pheno, what = "heritability") gammas<-.read_gemma(folder="output",name=pheno, what = "bslmm") bv<-.read_gemma(folder="output",name=pheno, what = "bv") %>% fn cor(bv,y) plot(bv,y) betas<-.read_gemma(folder="output",name=pheno, what = "lm") mycols<- which(gammas$gamma >= sort(gammas$gamma,decreasing = T)[100] ) s<-gammas[mycols,"effect"] hist(s) mycols2<- which(betas$beta >= sort(betas$beta,decreasing = T)[100] ) s<-betas[mycols2,"effect"] hist(s) length(setdiff(mycols,mycols2)) /length(unique(c(mycols,mycols2)))
48d0a8ed453597e5546f029c9d31f2c84b31894a
d11cd1801f373324eb491c832808b0e93ec0dbb3
/ui.R
2d59935360a19386c6cbe4d87cd317e47d4d7b3b
[]
no_license
RaschMaslasky/DevelopDataProductAssignment2
448419c625daebf3b8778a8afafba3d056573bac
f503295ee8a0b6fd077afaae4a4ef146fb7ea941
refs/heads/master
2021-05-05T06:28:45.258300
2018-01-24T18:18:29
2018-01-24T18:18:29
118,802,983
0
0
null
null
null
null
UTF-8
R
false
false
1,884
r
ui.R
library(shiny) library(leaflet) library(dplyr) library(sqldf) library(plotly) library(reshape) library(rsconnect) # create lookups df <- read.csv(file = "./data/df.csv", header=T, sep=',', quote = '"', fileEncoding = "UTF-8") crime.type <- levels(df$Crime.type) month <- levels(df$Month) # Define UI for application shinyUI(fluidPage( # Application title # titlePanel("world is yours"), h4("London's Crime Monitoring"), h5("mirzarashid abbasov | developing data products course | coursera | 24.JAN.2018"), # Sidebar layout rendering sidebarLayout( sidebarPanel( h4("Search parameters:"), selectInput("month", label="Period", choices = month, selected = 1), selectInput("crime.type", "Crime type", choices = crime.type, selected = 1), checkboxInput("cluster", "Cluster option"), checkboxInput("legend", "Popup option"), br(), h4("Forecast parameters:"), sliderInput("p", label = "Autoregressive,(p)", min = 0 , max = 5, value=1, step = 1), sliderInput("d", label = "Differencing, (d)", min = 0 , max = 5, value=0, step = 1), sliderInput("q", label = "Moving average, (q)", min = 0 , max = 5, value=0, step = 1), br(),br(),br(),br(),br(),br(),br() ), # Main panel rendering mainPanel( leafletOutput("mymap"), plotlyOutput("myplot") # plotlyOutput("myplot", width = "99%", height = 200) ) ), br(), h4("Introduction"), h5("The following content represents London's crime statistics"), br(), h4("Synopsis"), h5("The goal of the project is:"), h5("1. create a Shiny application and deploy it on Rstudio's servers"), h5("2. prepare a reproducible pitch presentation about application via Slidify or Rstudio Presenter"), br(), h5("Mirzarashid Abbasov, almaty, 2018") ))
78e6621b0c9b83a2357eed5d13bdcaa6e8abab14
02203a5e1487c6bf95647b38038e2428c261aad7
/R/ogrtindex.R
2c2448b4541c579b11aefa2cc4e07fd4eff84ab0
[]
no_license
cran/gdalUtils
8793292640f94d0f8960804f0ba9d4b5099baad7
9aa3955becca0970f98513ca20e4bff56be44d81
refs/heads/master
2021-06-07T07:27:23.972525
2020-02-13T19:10:02
2020-02-13T19:10:02
17,696,298
3
8
null
null
null
null
UTF-8
R
false
false
6,070
r
ogrtindex.R
#' ogrtindex #' #' R wrapper for ogrtindex: creates a tileindex #' #' @param output_dataset Character. Output tile index. #' @param src_dataset Character. Input geospatial files. #' @param lnum Numeric. n. Add layer number 'n' from each source file in the tile index. #' @param lname Character. name. Add the layer named 'name' from each source file in the tile index. #' @param f Character. output_format. Select an output format name. The default is to create a shapefile. #' @param tileindex Character. file_name. The name to use for the dataset name. Defaults to LOCATION. #' @param write_absolute_path Logical. Filenames are written with absolute paths. #' @param skip_different_projection Logical. Only layers with same projection ref as layers already inserted in the tileindex will be inserted. #' @param accept_different_schemas Logical. By default ogrtindex checks that all layers inserted into the index have the same attribute schemas. If you specify this option, this test will be disabled. Be aware that resulting index may be incompatible with MapServer! #' @param output_Vector Logical. Return output output_dataset as a Spatial* object. Currently only works with f="ESRI Shapefile". ## @param additional_commands Character. Additional commands to pass directly to ogrtindex. #' @param ignore.full_scan Logical. If FALSE, perform a brute-force scan if other installs are not found. Default is TRUE. #' @param verbose Logical. Enable verbose execution? Default is FALSE. ## @param ... Other parameters to pass to gdal_translate. #' @return NULL or SpatialPolygonsDataFrame #' #' @author Jonathan A. Greenberg (\email{gdalUtils@@estarcion.net}) (wrapper) and Frank Warmerdam (GDAL lead developer). #' @details This is an R wrapper for the 'ogrtindex' function that is part of the #' Geospatial Data Abstraction Library (GDAL). It follows the parameter naming #' conventions of the original function, with some modifications to allow for more R-like #' parameters. For all parameters, the user can use a single character string following, #' precisely, the gdalinfo format (\url{http://gdal.org/ogrtindex.html}), or, #' in some cases, can use R vectors to achieve the same end. #' #' The ogrtindex program can be used to create a tileindex - a file containing a #' list of the identities of a bunch of other files along with there spatial #' extents. This is primarily intended to be used with MapServer for tiled access #' to layers using the OGR connection type. #' #' If no -lnum or -lname arguments are given it is assumed that all layers in #' source datasets should be added to the tile index as independent records. #' #' If the tile index already exists it will be appended to, otherwise it will be #' created. #' #' It is a flaw of the current ogrtindex program that no attempt is made to copy #' the coordinate system definition from the source datasets to the tile index #' (as is expected by MapServer when PROJECTION AUTO is in use). #' #' This function assumes the user has a working GDAL on their system. If the #' "gdalUtils_gdalPath" option has been set (usually by gdal_setInstallation), #' the GDAL found in that path will be used. If nothing is found, gdal_setInstallation #' will be executed to attempt to find a working GDAL. #' #' @references \url{http://www.gdal.org/ogrtindex.html} #' #' @examples #' # We'll pre-check to make sure there is a valid GDAL install. #' # Note this isn't strictly neccessary, as executing the function will #' # force a search for a valid GDAL install. #' gdal_setInstallation() #' valid_install <- !is.null(getOption("gdalUtils_gdalPath")) #' if(require(rgdal) && valid_install) #' { #' tempindex <- tempfile(fileext=".shp") #' src_dir <- system.file("external/", package="gdalUtils") #' src_files <- list.files(src_dir,pattern=".shp",full.names=TRUE) #' ogrtindex(output_dataset=tempindex,src_dataset=src_files, #' accept_different_schemas=TRUE,output_Vector=TRUE) #' } #' @import rgdal #' @export ogrtindex <- function( output_dataset,src_dataset, lnum,lname,f,tileindex,write_absolute_path, skip_different_projection,accept_different_schemas, # additional_commands, output_Vector=FALSE, ignore.full_scan=TRUE, verbose=FALSE#, # ... ) { if(output_Vector && !requireNamespace("rgdal")) { warning("rgdal not installed. Please install.packages('rgdal') or set output_Vector=FALSE") return(NULL) } parameter_values <- as.list(environment()) if(verbose) message("Checking gdal_installation...") gdal_setInstallation(ignore.full_scan=ignore.full_scan,verbose=verbose) if(is.null(getOption("gdalUtils_gdalPath"))) return() # Start gdalinfo setup parameter_variables <- list( logical = list( varnames <- c("write_absolute_path", "skip_different_projection", "accept_different_schemas")), vector = list( varnames <- c("lnum")), scalar = list( varnames <- c()), character = list( varnames <- c("output_dataset", "lname","f","tileindex")), repeatable = list( varnames <- c("src_dataset")) ) # browser() parameter_order <- c( "write_absolute_path", "skip_different_projection", "accept_different_schemas", "lnum", "lname","f","tileindex", "output_dataset","src_dataset" ) parameter_noflags <- c("output_dataset","src_dataset") parameter_doubledash <- NULL parameter_noquotes <- unlist(parameter_variables$vector) executable <- "ogrtindex" # End gdalinfo setup cmd <- gdal_cmd_builder( executable=executable, parameter_variables=parameter_variables, parameter_values=parameter_values, parameter_order=parameter_order, parameter_noflags=parameter_noflags, parameter_doubledash=parameter_doubledash, parameter_noquotes=parameter_noquotes) if(verbose) message(paste("GDAL command being used:",cmd)) cmd_output <- system(cmd,intern=TRUE) if(output_Vector) { return( readOGR(dsn=dirname(output_dataset), layer=basename(remove_file_extension(output_dataset)))) } else { return(NULL) } }
83bd3940486438bbafbcadef1c74b603517d80f9
4c05390532a78bf078491cf37eac5d369a75f1ec
/cachematrix.R
2ef5f8c705d9fdb9225ea4b3a42cf04ccc6ba0f7
[]
no_license
Rechisoft/ProgrammingAssignment2
f16365786a49d0ce78e94ac91c53055f785344d5
d5cabdc3fa1f9c69a3619df86f74335aff00342f
refs/heads/master
2016-10-26T04:23:50.796170
2014-06-22T22:03:05
2014-06-22T22:03:05
null
0
0
null
null
null
null
UTF-8
R
false
false
1,460
r
cachematrix.R
# Implementing a special version of "solve()" called "cacheSolve()" # which will return the inverse, but without calculating it and rather # fetching it from a cache if it was calculated before during program # execution. # Function makeCacheMatrix # Creates a special matrix which is able to cache its inverse # Implemented as a list of the following functions: # set: define the matrix # get: get the matrix defined by set # setinv: calculate the inverse and cache it using solve() # getinv: gets the cached inverse makeCacheMatrix <- function(x = matrix()) { inv <- matrix(c(NA),dim(x)[1],dim(x)[2]) set <- function(y) { x <<- y inv <<- matrix(c(NA),dim(y)[1],dim(y)[2]) } get <- function() x setinv <- function(solve) inv <<- solve getinv <- function() inv list(set = set, get = get, setinv = setinv, getinv = getinv) } # Function cacheSolve # Calculates the inverse of a matrix, either by # 1) getting the inverse already calculated before from the cache, or # 2) calculating it using solve() and caching it. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' inv <- x$getinv() if (!is.na(det(inv))) { message("Getting cached inverse...") return(inv) } data <- x$get() inv <- solve(data, ...) x$setinv(inv) inv }
499755f82095d55e650567bb956dbe6f2219ded2
cdb5b04ca59edf79bdbf43d56337ab8388a1797e
/list_unmatched_taxa_that_did_not_match_against_external_taxonomy.R
390d9acb7cdb9f2039202c2b671da69bed542de0
[]
no_license
GoMexSI/GoMexSI-Queries
2f6d65ca7dbbcb411de5f571f6de9a4275c3181e
90a73733286d1718a88d9366fdeaac02475a27e3
refs/heads/master
2021-01-21T03:39:15.720735
2016-08-16T13:24:23
2016-08-16T13:24:23
65,763,186
1
0
null
2016-08-16T16:16:23
2016-08-15T20:34:33
R
UTF-8
R
false
false
415
r
list_unmatched_taxa_that_did_not_match_against_external_taxonomy.R
*the code below returns a list of unmatched taxa that did not match against external taxonomy rglobi::query('START study = node:studies("*:*") WHERE study.source=~ ".*gomexsi.*" WITH study MATCH study-[:COLLECTED]->specimen-[:CLASSIFIED_AS]->taxon-[?:SAME_AS]->otherTaxon, specimen-[:ORIGINALLY_DESCRIBED_AS]->origTaxon WHERE not(has(taxon.path)) AND not(has(otherTaxon.path)) RETURN distinct(origTaxon.name)')
9c5a749198d71d1f83eef45c4aa8e22d69d3a0e7
127e60f2de4331083574307a8637963b31aa6dc0
/pipeline/scRNA_Seq/Droplet_based_Protocols/1Run/QC_cellPop_bimodality.R
b30fcf132157896295627c562d6694f7f62e7229
[ "CC0-1.0", "MIT", "GPL-2.0-only" ]
permissive
BgeeDB/bgee_pipeline
44b0857925e67498835b44a341c42887874da8be
0d9239966dda2cb4717c8ddd48d5741b48879835
refs/heads/master
2023-09-04T08:35:20.080239
2023-05-31T13:42:40
2023-05-31T13:42:40
129,377,740
11
4
CC0-1.0
2020-01-06T14:46:43
2018-04-13T09:09:24
Perl
UTF-8
R
false
false
10,369
r
QC_cellPop_bimodality.R
## SFonsecaCosta, 2020 ## This script is used to check the bimodality of the cell population per library. ## After cell-type identification we test if the cell-population per library follow a bimodal distribution, ## by excluding some noisy genes from the population ## Usage: ## R CMD BATCH --no-save --no-restore '--args scRNASeq_Info="scRNA_Seq_info_TargetBased.txt" folder_data="folder_data" output_folder="output_folder"' QC_cellPop_bimodality.R QC_cellPop_bimodality.Rout ## scRNASeq_Info --> File that results from annotation and metadata (libraries downloaded and with extra information as SRR) ## folder_data --> Folder where are all the libraries with correspondent cell-type population identification (Raw and normalized files) ## output_folder --> Folder where the results should be saved (normally same that folder_data) ## libraries used library(data.table) library(stringr) library(dplyr) library(mclust) library(LaplacesDemon) sessionInfo() ## reading arguments cmd_args = commandArgs(TRUE); print(cmd_args) if( length(cmd_args) == 0 ){ stop("no arguments provided\n") } else { for( i in 1:length(cmd_args) ){ eval(parse(text=cmd_args[i])) } } ## checking if all necessary arguments were passed. command_arg <- c("scRNASeq_Info", "folder_data", "output_folder") for( c_arg in command_arg ){ if( !exists(c_arg) ){ stop( paste(c_arg,"command line argument not provided\n") ) } } ## Read scRNA-Seq info file. If file not exists, script stops if( file.exists(scRNASeq_Info) ){ scRNA_annotation_file <- fread(scRNASeq_Info) } else { stop( paste("The annotation file not found [", scRNASeq_Info, "]\n")) } ############################################################################################### ## function to make the deconvolution of the protein coding density deconvolution <- function(UMIgeneID){ ## select just protein_coding genes to the Mclust proteinCoding <- UMIgeneID[UMIgeneID$biotype == "protein_coding", ] decov = densityMclust(proteinCoding$ratio) proteinCoding$classification <- decov$classification return(proteinCoding) } ## plot the data for the cell population if pass the QC plotData <- function(libraryID, allInformation, deconvolutionInfo, classification, cutoff, cellPopName, modesInfo){ pdf(file = paste0(output_folder, "/", libraryID, "/QC_bimodality_",cellPopName, ".pdf")) layout(matrix(c(1,1,2,3,4,5), 3, 2, byrow = TRUE)) ## plot info about UMI counts and genes detected per individual cell. plot(allInformation$genes, allInformation$UMIcounts, xlab="Number of genes", ylab="UMI counts", main=paste0("cell pop ",cellPopName), pch=20) mtext(paste0(sizeData, " Cells")) hist(allInformation$genes, xlab="genes", main=paste0(cellPopName)) hist(allInformation$UMIcounts, xlab="UMI counts", main=paste0(cellPopName)) ## plot deconvolution curves plot(density((deconvolutionInfo$ratio)), lwd=3, main="Density protein coding", xlab="ratio") for (i in classification) { densityPlot <- density((deconvolutionInfo$ratio[deconvolutionInfo$classification == i])) densityPlot$y <- densityPlot$y * length(deconvolutionInfo$ratio[deconvolutionInfo$classification == i]) / length(deconvolutionInfo$ratio) lines(densityPlot, col="indianred", lwd=2, lty=2) ## Print gaussian number on plot text(densityPlot$x[densityPlot$y == max(densityPlot$y)], 0.005, labels = i, col="indianred", font=3) } abline(v=cutoff, lwd=1, lty=2, col="gray") legend("topright", legend = c("Protein_coding", "Deconvolution","cutoff genes"), col=c("black", "indianred", "gray"), pch=20, bty = "n") ## plot density after filtering low detected genes across the cell population pc_afterFiltering <- deconvolutionInfo[deconvolutionInfo$ratio >= cutoff, ] densityPC <- density(pc_afterFiltering$ratio) plot(densityPC,col="darkblue",lwd=2, main="Density of protein coding", xlab="ratio", xlim=c(min(densityPC$x), max(densityPC$x))) mtext(paste0("Noisy genes < ", round(cutoff, digits = 3))) legend("topright", legend = c(paste0("Bimodality = ", is.bimodal(pc_afterFiltering$ratio, min.size=0.1)), paste0("Mode_1 = ", round(modesInfo[1], digits = 2)), paste0("Mode_2 = ", round(modesInfo[2], digits = 2))), bty = "n") dev.off() } bimodality_targetBased <- file.path(output_folder, "bimodality_targetBased.txt") if (!file.exists(bimodality_targetBased)){ file.create(bimodality_targetBased) cat("library\texperimentID\tCell_Name_ID\tcomment\n",file = bimodality_targetBased, sep = "\t") } else { print("File already exist.....") } ## apply for each library/cellpop for (libraryID in unique(scRNA_annotation_file$libraryId)) { ## verify if the code already run for this library (check if the bimodality_DONE file already exist) bimodalityDone <- file.exists(file.path(folder_data, libraryID, "bimodality_DONE.txt")) if (bimodalityDone == TRUE){ message("Bimodality done for this library: ", libraryID) } else { message("Treating library: ", libraryID) ## select all cell population for the library AllCellPop <- list.files(path = file.path(folder_data, libraryID), pattern = "^Raw_Counts_") experimentID <- scRNA_annotation_file$experimentId[scRNA_annotation_file$libraryId == libraryID] for (cellPop in AllCellPop) { cellPopName <- str_remove(cellPop, "Raw_Counts_") cellPopName <- str_remove(cellPopName, ".tsv") message("Doing: ", cellPopName) cellpop <- fread(file.path(folder_data,libraryID,cellPop)) ## remove info about gene_name, biotype, type sizeData <- length(cellpop)-5 colectInfo <- as.data.table(cellpop %>% dplyr::select("gene_id", "biotype", "type", "cellTypeName", "cellTypeId")) ## just make QC bimodality if cell population have at least 50 cells if (sizeData >= 50){ genicRegion <- as.data.table(dplyr::filter(cellpop, type == "genic")) genicRegion <- genicRegion[, -c("biotype", "type", "cellTypeName", "cellTypeId")] ## UMI counts and genes detected per cell using all genic region UMIcounts <- as.data.frame(colSums((genicRegion[,2:ncol(genicRegion)]))) colnames(UMIcounts) <- "UMIcounts" UMIgenes <- as.data.frame(apply(genicRegion[,2:length(genicRegion)],2,function(x)sum(x != 0))) colnames(UMIgenes) <- "genes" allInformation <- cbind(UMIcounts, UMIgenes) allInformation$cells <- rownames(allInformation) ## verify in how many genes we have UMI higher 0 across the cell population UMIgeneID <- as.data.frame(apply(genicRegion[,2:length(genicRegion)],1,function(x)sum(x != 0))) colnames(UMIgeneID) <- "genes" UMIgeneID$ratio <- UMIgeneID$genes/sizeData UMIgeneID$gene_id <- genicRegion$gene_id UMIgeneID <- merge(UMIgeneID, colectInfo, by = "gene_id") ## remove genes never detected in the cell population = 0 UMIgeneID <- UMIgeneID[UMIgeneID$ratio > 0, ] ## deconvolution of protein coding density deconvolutionInfo <- deconvolution(UMIgeneID = UMIgeneID) classification <- sort(unique(deconvolutionInfo$classification)) ## verify the minimum amount of genes that can be classified as noisy genes (this means detected in few cells) for (i in classification) { cutoff <- min((deconvolutionInfo$ratio[deconvolutionInfo$classification == i])) proteinCoding <- deconvolutionInfo[deconvolutionInfo$ratio >= cutoff, ] bimodalityCalculation <- is.bimodal(proteinCoding$ratio, min.size=0.1) modesInfo <- Modes(proteinCoding$ratio, min.size=0.1) if (bimodalityCalculation == TRUE){ break } } ## verify if 1 mode > 0.5 and 2 mode < 0.8 in the ratio (in order to use the bimodality distribution to validate genes that are always detected in the cell-population) mode_1 <- modesInfo$modes[1] > 0.5 mode_2 <- modesInfo$modes[2] < 0.8 if (bimodalityCalculation == TRUE & mode_1 == FALSE & mode_2 == FALSE){ message("The cell population ", cellPopName, " from the library ", libraryID ," follow a bimodal distribution.") ## retrieve modes info modesInfo <- modesInfo$modes ## plot data plotData(libraryID = libraryID, allInformation = allInformation, deconvolutionInfo = deconvolutionInfo, classification = classification, cutoff = cutoff, cellPopName = cellPopName, modesInfo = modesInfo) } else if (bimodalityCalculation == TRUE & mode_1 == TRUE | bimodalityCalculation == TRUE & mode_2 == TRUE){ message("The cell population ", cellPopName, " from the library ", libraryID ," not present confidence enough to detect a set of genes that should be always detected for the cell-type.") ## add to the excluded file libraries/cell pop infoCollected <- data.frame(libraryID, experimentID, cellPopName, "mode_1 or mode_2 not fit the minimum requirement") write.table(infoCollected, file = bimodality_targetBased, quote = FALSE, sep = "\t", append = TRUE, col.names = FALSE, row.names = FALSE) } else { message("The cell population ", cellPopName, " from the library ", libraryID ," is not bimodal.") ## add to the excluded file libraries/cell pop infoCollected <- data.frame(libraryID, experimentID, cellPopName, "not bimodal") write.table(infoCollected, file = bimodality_targetBased, quote = FALSE, sep = "\t", append = TRUE, col.names = FALSE, row.names = FALSE) } ## collect information for libraries/cell pop not pass the minimum requirement 50 cells or are not bimodal population } else { message("The cell population ", cellPopName, " from the library ", libraryID ," have < 50 cells.") ## add to the excluded file libraries/cell pop infoCollected <- data.frame(libraryID, experimentID, cellPopName, "< 50 cells") write.table(infoCollected, file = bimodality_targetBased, quote = FALSE, sep = "\t", append = TRUE, col.names = FALSE, row.names = FALSE) } } ## control file in case densityMclust stops in some library because of (.Machine$double.xmax) file.create(file.path(folder_data, libraryID, "bimodality_DONE.txt")) } }
b7450e54effe6e49e84c27e9088c8a805243a0e4
f0915ecdf96ea1ae3fd9b8b57410989156273f37
/classes.R
e7bbdffb9919f38683cdf9211dbeb6f102be519d
[]
no_license
Yaskomega/LinkedDataClustering
f4b607e76a20275d304cda47041f3f07e0cd659b
407d18da58147b2b71cd8eb5e8f36a727551b7e3
refs/heads/master
2021-05-11T05:52:47.855949
2018-07-05T13:58:54
2018-07-05T13:58:54
117,972,719
0
1
null
null
null
null
UTF-8
R
false
false
3,791
r
classes.R
# ######################################################################## # Classe Object qui correspond à un noeud du graphe résultat # @attribute name : la valeur du noeud (soit l'URI, soit le littéral) # @attribute links : la liste d'objects de type Link qui correspond au voisinage # ######################################################################## Object <- setClass( # Set the name for the class "Object", # Define the slots slots = c( name = "character", links = "list" ), # Set the default values for the slots. (optional) prototype=list( name = "", links = NULL ), # Make a function that can test to see if the data is consistent. # This is not called if you have an initialize function defined! validity=function(object) { if(FALSE) { return("The parameters are not correct.") } return(TRUE) } ) # ######################################################################## # Classe Link qui correspond aux objets B et C dans un triplet ABC # @attribute property : un objet de type Object correspondant à la propriété du lien # @attribute object : un objet de type Object correspondant à la valeur du noeud associé à la propriété # ######################################################################## Link <- setClass( # Set the name for the class "Link", # Define the slots slots = c( property = "Object", object = "Object" ), # Set the default values for the slots. (optional) prototype=list( property = NULL, object = NULL ), # Make a function that can test to see if the data is consistent. # This is not called if you have an initialize function defined! validity=function(object) { if(FALSE) { return("The parameters are not correct.") } return(TRUE) } ) # ######################################################################## # Fonction qui permet de savoir si une liste d'objets contient # une occurence de l'object passé en paramètre # @param list_of_objects : la liste d'object à inspecter # @param item : l'object à rechercher dans la liste # @return true si l'occurence est trouvée, false sinon # ######################################################################## contains <- function (list_of_objects , item){ if(length(list_of_objects) > 0){ for( i in 1:length(list_of_objects)){ if(identical(list_of_objects[[i]], item)){ return(TRUE) } } } return(FALSE) } # ######################################################################## # Fonction qui permet de savoir si une liste d'objets Link contient # une occurence de l'object passé en paramètre # @param list_of_link : la liste d'object à inspecter # @param link : l'object à rechercher dans la liste # @return true si l'occurence est trouvée, false sinon # ######################################################################## containsPropertyAndObject <- function (list_of_link , link){ return(contains(list_of_link, link)) } # ######################################################################## # Fonction qui permet de savoir si une liste d'objets Link contient # une occurence ayant la même valeur d'attribut property que celui de # l'object passé en paramètre # @param list_of_link : la liste d'object à inspecter # @param link : l'object contenant l'attribut property à rechercher dans la liste # @return true si l'occurence est trouvée, false sinon # ######################################################################## containsProperty <- function (list_of_link , link){ if(length(list_of_link) > 0){ for( i in 1:length(list_of_link)){ if(identical(list_of_link[[i]]@property, link@property)){ return(TRUE) } } } return(FALSE) }
af502178123d95d1dac01ead153bf73fce2bb44f
c91afc12900d00fabd0e3546b0d2cbd43142ee0b
/man/FuzzySets-methods.Rd
66fba9dd926ecadbd7bd990715ad130c4536e205
[ "MIT" ]
permissive
kevinrue/unisets
7b598969fe1ca06438da7ba4cc4f443b18d23cb3
da84fd280dfd44ecd5839051931660691a238889
refs/heads/master
2021-07-22T20:19:47.143976
2020-05-11T21:45:41
2020-05-11T21:45:41
165,846,880
3
2
NOASSERTION
2020-05-11T21:45:43
2019-01-15T12:26:01
R
UTF-8
R
false
true
3,255
rd
FuzzySets-methods.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/AllMethods.R, R/FuzzySets-class.R \docType{methods} \name{FuzzySets-methods} \alias{FuzzySets-methods} \alias{membership,FuzzySets-method} \alias{membership<-,FuzzySets-method} \alias{as.matrix.FuzzySets} \alias{as.FuzzySets.matrix} \alias{as.FuzzySets} \title{Methods for \code{FuzzySets} Objects} \usage{ \S4method{membership}{FuzzySets}(object) \S4method{membership}{FuzzySets}(object) <- value \method{as.matrix}{FuzzySets}(x, fill = NA_real_, ...) as.FuzzySets.matrix(matrix, ...) } \arguments{ \item{object, x}{An object of class inheriting from \code{\linkS4class{FuzzySets}}.} \item{value}{An object of a class specified in the S4 method signature or as outlined in 'Accessors'.} \item{fill}{Value with which to fill in structural missings, passed to \code{\link[=acast]{acast()}}. Defaults to \code{NA_real_}, to contrast with relations explictly associated with a membership function of 0.} \item{...}{Additional arguments passed to and from other methods.} \item{matrix}{A \code{matrix}. The matrix will be coerced to \code{double} type and the value will be taken to indicate the membership function.} } \description{ This page documents the S4 generics and methods defined for objects inheriting of the \code{\linkS4class{FuzzySets}} class. The \code{FuzzySets} class directly extends \code{\linkS4class{Sets}} and thus inherits of all methods defined for the parent class. In the usage below, \code{object} and \code{x} represent an object of class inheriting from \code{\linkS4class{FuzzySets}}, and \code{value} is an object of a class specified in the S4 method signature or as outlined in 'Accessors'. } \section{Accessors}{ \code{membership(object)} returns a numeric vector of membership function for each relation. } \section{Coercion}{ \code{as(x, "matrix")} and \code{as.matrix(x)} return a \code{matrix} with elements as rows, sets as columns, and a numeric value indicating the membership function. } \section{Coercion to matrix}{ As it is possible to store multiple relations between the same gene and gene set, it may be necessary to collapse multiple observations of the membership function into a single value. To this end, the form \code{as.matrix(x, fun.aggregate)} can be used to provide an aggregation function. See examples. } \examples{ # Constructor ---- # Visually intuitive definition of sets, elements, and membership sets <- list( set1=c("A"=0.1, "B"=0.2), set2=c("B"=0.3, "C"=0.4, "D"=0.5), set3=c("E"=0.8)) # unlist the set names unlistSets <- rep(names(sets), lengths(sets)) # unlist the element names unlistElements <- unlist(sapply(sets, names), use.names = FALSE) # unlist the membership values unlistMembership <- unlist(sets, use.names = FALSE) # Reformat as a table relations <- DataFrame( element=unlistElements, set=unlistSets, membership=unlistMembership ) fs <- FuzzySets(relations=relations) fs # Accessors ---- membership(fs) fs1 <- fs membership(fs1)[1] <- 0 # Coercion from/to FuzzySets ---- matrix1 <- as(fs, "matrix") # Coercion to FuzzySets ---- fs1 <- as(matrix1, "FuzzySets") } \seealso{ \code{\linkS4class{FuzzySets}}, \code{\link{Sets-methods}}. } \author{ Kevin Rue-Albrecht }
a86374933a651e2ff872b95efe68a51eff1d0cfd
59ae1d56485c9c6f7d102d5149149383ba545100
/inst/test_random_data_frames.R
e0c832e165fac000fc6c7252de8b1489ab4a16bd
[]
no_license
marymoni/bcp
463bfda838f29bb0217beb904ee29d0c26aad89e
4a6c8b8423a0962920f51014fe07f68720c31913
refs/heads/main
2023-02-23T04:04:23.606907
2021-02-01T23:27:06
2021-02-01T23:27:06
328,242,734
1
0
null
null
null
null
UTF-8
R
false
false
1,871
r
test_random_data_frames.R
library(bcp) generate_data_frame = function(nrow, ncol) { col_types = list( `integer` = function() runif(nrow, -.Machine$integer.max, .Machine$integer.max), `double` = function() rnorm(nrow), `character` = function() paste("str", as.character(rnorm(nrow))), `factor` = function() as.factor(paste("factor", as.character(runif(nrow, 1, 100)))), `logical` = function() rnorm(nrow) > 0, `Date` = function() as.Date("1970-01-01") + runif(nrow, 0, 25000) ) col_data = lapply(seq_len(ncol), function(i) { type_id = runif(1, 1, length(col_types)) col_types[[type_id]]() }) names(col_data) = paste("col", seq_along(col_data), sep = "_") res = data.frame(col_data) return(res) } test_scenarios = list( `1` = list(nrow = 100, ncol = 20), `2` = list(nrow = 51000, ncol = 30), `3` = list(nrow = 1000, ncol = 80), `4` = list(nrow = 100000, ncol = 5), `5` = list(nrow = 101001, ncol = 1) ) conn = odbcDriverConnect('driver={SQL Server};server=DESKTOP-0U0OJS1\\SQLEXPRESS;database=test;trusted_connection=true') for(i in seq_along(test_scenarios)) { print(sprintf("scenario %d; nrow = %d; ncol = %d", i, test_scenarios[[i]]$nrow, test_scenarios[[i]]$ncol)) df = generate_data_frame(nrow = test_scenarios[[i]]$nrow, ncol = test_scenarios[[i]]$ncol) table_name = sprintf("dbo.DF%d", i) time = system.time({ bcp(conn, df, table_name, auto_create_table = TRUE, drop_if_exists = TRUE) }) print(time) } df_perf = generate_data_frame(nrow = 40000, ncol = 60) sqlQuery(conn, "IF OBJECT_ID('dbo.PerfSqlSaveTest') IS NOT NULL DROP TABLE dbo.PerfSqlSaveTest") system.time({ bcp(conn, df_perf, "dbo.PerfBcpTest", auto_create_table = TRUE, drop_if_exists = TRUE) }) system.time({ sqlSave(conn, df_perf, "dbo.PerfSqlSaveTest") })
118e130eecf5b5ebdd5f7887d5dae8826f56e894
725a33f27fce430ee481a3542aae5bb81a94dfc0
/man/appendEnv.Rd
a997f0529a79cdafd14bb09eb825d713d5726496
[ "BSD-3-Clause" ]
permissive
cbielow/PTXQC
fac47ecfa381737fa0cc36d5ffe7c772400fb24e
f4dc4627e199088c83fdc91a1f4c5d91f381da6c
refs/heads/master
2023-07-20T00:39:45.918617
2023-05-17T14:23:03
2023-05-17T14:23:03
20,481,452
41
30
NOASSERTION
2023-05-17T14:23:04
2014-06-04T11:53:49
HTML
UTF-8
R
false
true
795
rd
appendEnv.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fcn_misc.R \name{appendEnv} \alias{appendEnv} \title{Add the value of a variable to an environment (fast append)} \usage{ appendEnv(env_name, v, v_name = NULL) } \arguments{ \item{env_name}{String of the environment variable} \item{v}{Value to be inserted} \item{v_name}{String used as variable name. Automatically generated if omitted.} } \value{ Always TRUE } \description{ The environment must exist, and its name must be given as string literal in 'env_name'! The value of the variable 'v' will be stored under the name given in 'v_name'. If 'v_name' is not given, a variable name will be created by increasing an internal counter and using the its value padded with zeros as name (i.e., "0001", "0002" etc). }
55d90447756acf11b690c20cb5c5d41c75a59344
49b90e00efe83a3d8b59b51f40c3bc5e886ddbb3
/plot3.R
74042988e8acb855dc8a7b35faa332b245f7761c
[]
no_license
wiltbemj/ExData_Plotting1
2ebdcec0247c5396dbfa59cce046445d3791fd16
86a7325bc506f0bc7fb5f1ca92871bee0840b1a0
refs/heads/master
2021-01-16T22:50:52.079553
2015-08-04T16:44:36
2015-08-04T16:44:36
40,151,030
0
0
null
2015-08-03T22:29:09
2015-08-03T22:29:09
null
UTF-8
R
false
false
828
r
plot3.R
file = 'household_power_consumption.txt' #File is to big read the whole thing every time so lets get header information and then the info #from the dates requested tmp <- read.table(file,sep=';',nrows=1,stringsAsFactors = FALSE) start = 66637 end = 69517 epow <- read.table(file,sep=';',na.strings = '?',header=FALSE,skip=start,nrows = end-start) colnames(epow) <- unlist(tmp) datetime <- strptime(paste(epow$Date,epow$Time),"%d/%m/%Y %T") png(file='plot3.png') plot(datetime,epow$Sub_metering_1,type='l', ylab = 'Energy Submetering [kW]', xlab = 'Date Time', main = 'UCI Indvidual Electrical Power Dataset\nFeb 1-2 2007') lines(datetime,epow$Sub_metering_2,type='l',col='red') lines(datetime,epow$Sub_metering_3,type='l',col='blue') legend('topright',colnames(epow[7:9]),col=c('black','red','blue'),lwd=1) dev.off()
6136ff92893e6116398c4379b78c863d075329f3
1c27b5c1fd9ed44e04b6ded55361dd9d7bfa0b81
/practice_quiz3_script.R
7cc1614bfaa9ab0768d8d11dc42cdad7fca50c36
[]
no_license
veesta/practice_quiz_3
a615cfa85f1dcc1ff41b4c4aa356036b5b89ba5d
67b4ed5300ab7037736e506f7396fc091d6f8531
refs/heads/master
2021-01-11T08:24:40.805272
2016-10-29T17:22:56
2016-10-29T17:22:56
72,289,497
0
0
null
null
null
null
UTF-8
R
false
false
2,303
r
practice_quiz3_script.R
####Differences between Correlations ###Comparing Correlations within a Published Paper ##Question 1 #Based on the above correlation matrix, determine if the rating-complaint correlation is stronger than the #rating-critical correlation. Use cocor package and ?cocor.dep.groups.overlap command library(tidyverse) library(cocor) #?cocor.dep.groups.overlap cocor.dep.groups.overlap(.83, .16, .19, 30, alternative= "two.sided", test ="all", alpha = 0.05, conf.level = 0.95, null.value = 0, data.name = NULL, var.labels = NULL, return.htest = FALSE) ##Question 2 ##Based on the above correlation matrix, determine if the rating-complaint correlation is stronger than the #raises-critical correlation. Use cocor package and ?cocor.dep.groups.nonoverlap command #?cocor.dep.groups.nonoverlap cocor.dep.groups.nonoverlap(.83, .38, .59, .16, .38, .19, 30, alternative = "two.sided", test="all", alpha= 0.05, var.labels=NULL, return.htest = FALSE) ###Replication ##Question 3 #You decide to run a replication of this study. You want to evaluate the rating-privileges correlation #You plan on using a sample size of N = 100. What is the prediction interval when you use N = 100? library (predictionInterval) pi.r(r=.43,n=30,rep.n=100) ##Question 4 #What replication sample size do you need to ensure the prediction interval width is not greater than #.50? Trick: why is obtaining a prediction interval that narrow problematic in this scenario? pi.r(r=.43,n=30,rep.n=7000) #Prediction Width can only get as low as .6 ##Question 5 #A new paper examines the rating-privileges correlation. It used a sample size of 1000 and got a correlation of #.1. Is this correlation different - use cocor.indep.groups #?cocor.indep.groups cocor.indep.groups(.43, .1, 30, 1000, alternative= "two.sided", test = "all", alpha = 0.05, conf.level = 0.95, null.value = 0, data.name = NULL, var.labels = NULL, return.htest = FALSE) #Question 6 #What can you conclude about the strength of the rating-privileges correlation #and the results based on Question 5 #calculate confidence interval around rating-privileges from our study psych::r.con(.43, n=30)
dda1a6ceb65765b758cb559b2c517bf516cb2e6b
d6e59f0820a8165dbdef44a77d14f13db076bbb0
/R/isoclim.R
d604a172381bfaf8c562d815cd6473e8e8eb5bd7
[ "MIT" ]
permissive
AlexSoudant/isoclim-demonstration
cb5c884e56df01ac7dbbc0274ee0986d5129185e
2c87ad0493bc2de209cb4ab17d72234bab23a19d
refs/heads/master
2020-12-24T06:41:25.955189
2016-06-01T13:22:35
2016-06-01T13:22:35
60,178,294
0
0
null
null
null
null
UTF-8
R
false
false
5,700
r
isoclim.R
# Name : isoclim.R # Type : Program # Object : Construct a work environment. # Cast programs for data manipulation. # Destruct work environment. # Input : See Input section # Output : datasets and figures # Author : A. Soudant # R version : 2.10.1 # Creation date : Jan 2010 # Modified date : June 2015 #__________________________________________________________________Environment # Project path (TO MODIFY) .ROOT <- "/home/..." # Data directory (TO MODIFY) site <- "site name" # To Modify depending on the study site # Paths to the data directory (TO MODIFY) .DATA <- paste(.ROOT,"data",sep="/") #_____________________________________________________________________Input # Selection of the time frame and year to study y <- 1997:2009 # settings for the size of the plot window in inches X11.options(width = 10*1, height = 1*8, xpos = 0, pointsize = 10) setwd(.DATA) # load the different raw isotope time series located in original.data.sets (TO MODIFFY) iso1 <- read.table("Isotope1.txt",header=T) iso2 <- read.table("Isotope2.txt",header=T) iso3 <- read.table("Isotope3.txt",header=T) # intra-annual sample resolution (microns) sample.res <- 80 # Study site coordinates latitude <- 61 longitude <- 24 # Flux tower resolution (typically 48 or 24) FT.res <- 48 # Select which method to characterise the growing season #1: default method using PAR and temperature thresholds #2: alternative method using ET #3: alternative method using NEE GS.method <- 1 # tresholds to determine Onset and cessation dates with smoothing splines #Based on PAR (in micromol.m-2.s-1) treshold.Rad <- 435 # Based on air temperature (in degree Celcius) treshold.T <- 10 # Attribute dates for onset and cessation of radial growth according to 2% and 99% of cumulative NEE values reached respectively treshold.NEE.onset <- 2 treshold.NEE.cessation <- 99 # Attribute dates for onset and cessation of radial growth according to 10% and 95% of cumulative ET values reached respectively treshold.ET.onset <- 10 treshold.ET.cessation <- 95 # Select which cell phase to study: #1: cell division (no cell life time) | 2: cell enlargement | 3: secondary wall thickening | 4: total growth cellphase <- 4 # Select which feature to divide in 3 sections: #1: tree-rings #2: growing season division <- 1 #_____________________________________________________________________Programs isoclim <- function() { # Create the plots for raw isotope series plot.rawseries(iso1,iso2,iso3,sample.res) #Create the standardised istope time series interpolation.tech(y,iso1,iso2,iso3) # type "isotope.data" to see the standardised istope time series and the mean signal # Atmosptheric corrections for isotope time series 1991 - 2010 atm.correction() # type "atm.cor" to see the atmospheric correction values # Create the dataset for the atmospheric corrected isotope time series corrected.iso(y,isotope.data,atm.cor) # type "EPS" to see the EPS value # type "mean.isotope" to see the mean isotope time series # type "cor.iso" to see the corrected isotope time series # Create the plots for standardised and the atmospheric corrected isotope series plot.standardseries(y,isotope.data,mean.isotope,cor.iso,EPS,sample.res) # Calculates the potential downwelling shortwave radiation at the surface # Necessary for growing season calculation #rad.pot(y,latitude,longitude,FT.res) # Calculate the growing season dates based on PAR and temperature treshold OR Evapotranspiration OR NEE gs.calc(y,GS.method,cor.iso,treshold.Rad,treshold.T,treshold.NEE.onset,treshold.NEE.cessation,treshold.ET.onset,treshold.ET.cessation,FT.res) # type "data.gs" to see onset and cessation dates selected # Gompertz fitting to obtain intra-annual time resolved stable isotope series #Gompertz.calc(y,cor.iso,data.gs) gompertz.calc.example() # type "gompertz.parameters" to see final parameters beta and keta for the Gompertz curve # type "final.isotope" to see the isotope time resolved high resolution isotope series # Set the cell life time for cell formation,enlargement, secondary wall thicknening and total growth cell.lifetime() # Perform the matching procedure between the isotope dates and the weather variables year by year match.climate(y,cellphase,final.isotope,increment.division,increment.enlargement,increment.wallthick,increment.total,FT.res) # Create the intra-annual dataset containing the matched isotopes - climate data intraannual.data(y,final.isotope) # type "climate.iso" to see the intra-annually matched isotopes - climate data # Create the annual dataset object containing the matched isotopes - climate data annual.data(y,climate.iso) # type "annual.dataset" to see annually matched isotopes - climate data # Divide the tree-ring or the growing season into three sections for climate analysis feat.division(y,division,climate.iso) # type "data.early", "data.mid" or "data.late" to see the splitted dataset #_____________________________________________________________________ Plotting #Plotting tools for linear regression between isotope and climate (Temperature, PAR, Precipitation) # simple linear correlations month by month at the inter-annual resolution plot.correlation(annual.dataset,climate.iso) # Produce graphics for climate correlation with isotopes at the inter-annual scale plot.interannual(y,annual.dataset) # Produce graphics for climate correlation with isotopes at the intra-annual scale plot.intraannual(y,climate.iso,data.early,data.mid,data.late) # type lr.prop to see linear regressions properties for each combination of sections and climate variables }
2df7b5ed740cb89675259e0728759b62f1159dd3
845df2fbc7466f3f0e1edf2b0a37ecd8443d0363
/datachallenge.r
a41a1b116af5e7b02183da3f445e2797cc46d765
[]
no_license
Sagarika22/Marketing-Analytics
219d2d5c9436c894fcbfe29669e979a399f9d7c6
31fc43aa230765f33695985695731ce24e8c516a
refs/heads/master
2020-04-02T12:50:33.510306
2018-10-24T07:02:30
2018-10-24T07:02:30
154,454,319
0
0
null
null
null
null
UTF-8
R
false
false
4,636
r
datachallenge.r
datascience<-read.csv("/Users/sagarikadutta/Downloads/data_science_challenge_samp_18.csv") View(datascience) str(datascience) summary(datascience) #Changing from factor to numeric of total spend datascience$total_spend<-as.numeric(datascience$total_spend)/100 options(digits=9) datascience$total_spend<-as.character(datascience$total_spend) datascience$total_spend<-as.numeric(datascience$total_spend) #removing column from data where date is more than 03-26-2016 datascience$order_date<-as.Date(datascience$order_date) install.packages("dplyr") library(dplyr) datascience<-datascience[datascience$order_date>="2015-03-20" & datascience$order_date<="2016-03-26",] View(datascience) #ordeering the dataset datascience<-datascience[order(datascience$cust_id,datascience$order_date),] #generating the new feature as date difference that is difference between minimum date and given date library(dplyr) datascience<-datascience%>% mutate(order_date = as.Date(order_date, "%m/%d/%Y")) mindate<-datascience %>% group_by(cust_id) %>% summarise(min_date=min(order_date)) View(mindate) datascience<-merge(datascience,mindate,by="cust_id") order_date<-as.POSIXct(datascience$order_date) min_date<-as.POSIXct(datascience$min_date) diffmindate<-difftime(datascience$min_date,datascience$order_date) View(diffmindate) diffmindate<-(-1)*diffmindate/(60*60*24) datascience<-cbind(datascience,diffmindate) datascience$diffmindate<-as.numeric(datascience$diffmindate) #generating week number on the basis of problem (Sun-Sat) install.packages("lubridate") library(lubridate) weeknumber<-epiweek(datascience$order_date) datascience<-cbind(datascience,weeknumber) library(dplyr) datascience<-datascience %>% group_by(cust_id) %>% mutate(WeekDifference = c(0, diff(weeknumber))) #finding the latest week difference install.packages("sqldf") library(sqldf) frequency<-sqldf("SELECT cust_id, count(*) as 'frequencyofvisit' from datascience group by cust_id") datascience<-merge(datascience,frequency,by="cust_id") recency<-sqldf("SELECT cust_id,round((372-(diffmindate))/7,0) as 'recent week' from datascience") datanew<-cbind.data.frame(datascience,recency) View(datanew) #checking missing values,infinites and NaNs sum(sapply(datanew,is.na)) sum(sapply(datanew,is.nan)) sum(sapply(datanew,is.infinite)) #defining the target variable:based on data if they visit next week then 1 else 0 datanew$newcolumn<-ifelse(datanew$WeekDifference==1 | datanew$WeekDifference==-52,1,0) colnames(datanew)[colnames(datanew)=="newcolumn"] <- "Targetv" #finding correlations cor(datanew$Targetv,datanew$frequencyofvisit) cor(datanew$Targetv,datanew$diffmindate) #boosting the model set.seed(3421) index=sample(2,nrow(datanew),replace=TRUE,prob=c(0.6,0.4)) train=datanew[index==1,] test=datanew[ind==2,] install.packages("gbm") library("gbm") gbmModel = gbm(formula =Targetv~frequencyofvisit+train$`recent week`+diffmindate, distribution = "bernoulli", data = train, n.trees = 50000, shrinkage = .01, n.minobsinnode =10) gbmTrainPredictions = predict(object = gbmModel, newdata = train, n.trees = 1500, type = "response") summary(gbmModel, plot = FALSE) summary(gbmTrainPredictions) gbm.perf(gbmModel) #probability model library(nnet) prob.model=multinom(formula= Targetv~units_purchased+total_spend+datanew$`recent week`+frequencyofvisit,data=datanew) coeff=summary(prob.model)$coefficients std=summary(prob.model)$standard.errors print(coeff) print(coeff/std) #model with the only customers who visited next week and purchased less than 3 nm=which(datanew$Targetv==1 & datanew$units_purchased<=3) summary(datanew[nm,]) #new model on the above criteria datanew.model=lm(formula=Targetv~frequencyofvisit+units_purchased+`recent week`,data= datanew[nm,]) summary(datanew.model) #boosting the model set.seed(3421) index=sample(2,nrow(datanew),replace=TRUE,prob=c(0.6,0.4)) train=datanew[index==1,] test=datanew[ind==2,] install.packages("gbm") library("gbm") gbmModel = gbm(formula =Targetv~frequencyofvisit+train$`recent week`+diffmindate, distribution = "bernoulli", data = train, n.trees = 50000, shrinkage = .01, n.minobsinnode =10) gbmTrainPredictions = predict(object = gbmModel, newdata = train, n.trees = 1500, type = "response") summary(gbmModel, plot = FALSE) summary(gbmTrainPredictions) gbm.perf(gbmModel)
43b7190b131328945af0bf0c3f6699fc7ab8b6b7
568d00a08792adb6a25d7283dc10181461bdbc64
/builtenvir/man/lag.basis.Rd
da769a46490b84dc9d48b6fea81ef4b065dc2c14
[]
no_license
Biostatistics4SocialImpact/builtenvir
8c85de475d9a16646320d2455f625908e24ffe35
d6d5eb0004bbe03b29160a75e927f0fe00560c53
refs/heads/master
2021-01-23T16:14:42.293703
2017-12-05T00:58:55
2017-12-05T00:58:55
93,289,285
0
0
null
null
null
null
UTF-8
R
false
true
920
rd
lag.basis.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/lag.basis.R \name{lag.basis} \alias{lag.basis} \title{Cubic Radial Basis Functions for Distributed Lags} \usage{ \method{lag}{basis}(lag, center = TRUE, scale = FALSE) } \arguments{ \item{lag}{Distributed lag to compute basis of} \item{center}{Either \code{logical} or \code{numeric} value to indicate if the lag should be mean centered before computing basis (\code{center = TRUE}), or else giving the value to center lag at.} \item{scale}{Either \code{logical} or \code{numeric} value to indicate if the lag should be standard deviation-scaled before computing basis (\code{center = TRUE}), or else giving the value to scale lag by.} } \value{ \code{\link{LagBasis}} object containing the basis matrix. } \description{ Compute cubic radial basis for a given lag set. } \examples{ l <- seq(0.1, 10, length.out = 100) lb <- lag.basis(l) }