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
b748819aa6494b1593f6fdb654177cf7f1f55297
a58b45b89139bf17831f51890021131f84cf1f04
/script/rep_info.R
39f01b6a2ed2d8c0e22e3d0dfc65f735ba397d39
[]
no_license
BETAPANDERETA/rocket-engine-data-analysis
c0ee07cb19cb8c84e96ebf6c55cdff7e3205c92d
a187c561f1d326a492ae26f75407f16d3f4e104c
refs/heads/master
2023-01-20T21:55:48.929723
2020-11-25T03:01:49
2020-11-25T03:01:49
305,259,434
1
0
null
null
null
null
UTF-8
R
false
false
5,357
r
rep_info.R
# --------------------------------------------- # AUTOR: Leonardo Betancur A.K.A BETAPANDERETA| # CONTACTO: <lbetancurd@unal.edu.co> | # --------------------------------------------- library(extrafont) # Cargando fonts --> Revisar disponibles con windosFonts() library(ggplot2) # Gráficos library(mgcv) #---> Usar GAM library(lme4) # Usar BIC para estimar la regresión #_______________________________________________ # DATOS PROCESADOS_M1 | #_______________________________________________| #data_csv = "data/clean_data.csv" #data_util = read.table(data_csv,header = TRUE,sep=",") #data_y = c(data_util$Impulso) #data_x = c(data_util$t) #_______________________________________________ # DATOS SIN PROCESAR_M1 | #_______________________________________________ #data_csv = "data/dirt_data.csv" #data_util = read.table(data_csv,header = TRUE,sep=",") #data_y = c(data_util$Impulso) #data_x = c(data_util$t) #_______________________________________________ # DATOS PROCESADOS_M2 | #_______________________________________________| #data_csv = "data/clean_data_m2.csv" #data_util = read.table(data_csv,header = TRUE,sep=",") #data_y = c(data_util$Impulso) #data_x = c(data_util$t) #_______________________________________________ # DATOS SIN PROCESADOS_M2 | #_______________________________________________| data_csv = "data/dirt_data_m2.csv" data_util = read.table(data_csv,header = TRUE,sep=",") data_y = c(data_util$Impulso) data_x = c(data_util$t) g_p = 2 # Grado de polinomio - regresión gam_curve = gam(data_y ~ s(data_x)) # Regresión GAM loes_curve = loess(data_y ~ data_x) # Regresión LOESS sm_curve = lm(data_y ~ poly(data_x,degree = g_p,raw = TRUE)) # Regresión polinomial est_mr = BIC(sm_curve) # Índice BIC, tomar la regresión que dé menor BIC [4] bic = paste("BIC:",est_mr) print(bic) print(summary(sm_curve)) # Stats de la regresión polinomial #_______________________________________________ # GRÁFICOS CON GGPLOT2 | #_______________________________________________| plot_gg = function(data,x,y,lb_x,lb_y,title){ # Gráficos usando ggplot2 ggplot(data,aes(x=x,y=y))+ ggtitle(title)+ theme_bw()+ geom_point()+ geom_line(aes(colour="Registros"))+ geom_hline(yintercept=0)+ #geom_smooth( # Regresión GAM # method = "gam", # se = FALSE, # linetype = "dashed", # aes(colour="Regresión GAM") #)+ #geom_smooth( # Regresión LOESS # method = "loess", # se = FALSE, # linetype = "twodash", # aes(colour="Regresión LOESS") #)+ #geom_smooth( # Regresión polinomial # method = "lm", # formula = y ~ poly(x,degree = g_p,raw = TRUE), # se = FALSE, # aes(colour="Regresión polinómica") #)+ #stat_smooth( # Área bajo la curva basado en [1] # geom = 'area', # method = 'lm', # formula = y ~ poly(x,degree = g_p,raw = TRUE), # alpha = .4, aes(fill = "Impulso Total") #) + scale_fill_manual( name="Conv. área sombreada", values="pink" )+ theme( text=element_text(family="RomanS_IV25"), plot.title = element_text(color="red", size=14,family = "Technic"), legend.title = element_text(size=10) )+ xlab(lb_x)+ylab(lb_y)+ # leyendas en el plot tomado de [2] scale_colour_manual( name="Convenciones lineas", values=c("black","blue","grey","red") ) } #_______________________________________________ # GRÁFICOS CON R | #_______________________________________________| plot_r = function(x,y,r_pol,r_gam,r_loess){ plot( x,y, bty = "l", pch = 16, cex = .9 ) legend("topright", legend=c("Regresión P(x)", "Regresión GAM","Regresión LOESS"), col=c("blue", "green","red"), lty=1,lwd = 2, cex=0.8 ) lines(predict(r_pol), # Regresión polinomial col = "blue", lwd = 2) lines(predict(r_gam), # Regresión GAM col = "green", lwd = 2) lines(predict(r_loess), # Regresión LOESS col = "red", lwd = 2) } #_______________________________________________ # GRAFICANDO | #_______________________________________________| lab_g =c("Tiempo (s)","Gramos - fuerza (g)","Curva de impulso") graf_gg = plot_gg(data_util,data_x,data_y,lab_g[1],lab_g[2],lab_g[3]) print(graf_gg) #_______________________________________________ # REFERENCIAS | #_______________________________________________| # [1] https://stackoverflow.com/questions/40133833/smooth-data-for-a-geom-area-graph # [2] https://stackoverflow.com/questions/36276240/how-to-add-legend-to-geom-smooth-in-ggplot-in-r # Diferencia entre poly(raw = TRUE) y I(x): # [3] https://stackoverflow.com/questions/19484053/what-does-the-r-function-poly-really-do # [4] https://youtu.be/QptI-vDle8Y
d688aef5e830e7fab6d5f93194e416b2dfdb12fa
87f20607fc468c291f31f46c2718ddbbc69d3a75
/man/preprocess_secuences.Rd
472e83e6d47e3a7c6b05fed67d4be38d6bc91481
[ "MIT" ]
permissive
santiago1234/iCodon
ffce61abc8b69b38b138861e5c098454311c4c83
c6739dde6b03e3516e8a464aea3e64449c0f980d
refs/heads/master
2023-04-07T20:43:43.191022
2022-07-30T19:10:45
2022-07-30T19:10:45
238,309,734
13
2
null
null
null
null
UTF-8
R
false
true
741
rd
preprocess_secuences.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ml-preprocessing.R \name{preprocess_secuences} \alias{preprocess_secuences} \title{Preprocess sequence for prediction mRNA stability} \usage{ preprocess_secuences(secuencias, specie_ = "human") } \arguments{ \item{secuencias}{character, a vector of dna sequences to predict. If more than one sequence is supplied, then the sequences should be unique. (No repeated sequences)} \item{specie_}{character: one of human, mouse, fish, or xenopus} } \value{ A tibble: \code{length(secuencia)} x 423, preprocessed data for estimating mrna stability } \description{ Preprocess sequence for prediction mRNA stability } \examples{ preprocess_secuences(test_seq, "mouse") }
361b5a14d31fdf0fa02d207ae8a48c19d85b0486
d8ff92d904d21c1ab52d056fe6e624abfad939b4
/R/prVis.R
2624c6bb833db20a8920a34f24e8ded244e5a4cf
[]
no_license
guhjy/prVis
4c1ea6cc85b7843808725bdce331a5116026fba2
587582d463f66a87e91a84ec0b4ff50b554ff045
refs/heads/master
2020-04-11T12:00:30.488013
2018-12-13T21:16:27
2018-12-13T21:16:27
null
0
0
null
null
null
null
UTF-8
R
false
false
14,952
r
prVis.R
# two-dimensional visualization of the X data in classification problems, # similar in spirit to ordinary PCA and t-sne, color coded by Y values # (class IDs in classification case, subinternvals of Y in regression # case) # t-sne, e.g. in the Rtsne package, applied in dimension k, attempts to # find a k-dimensional manifold for which most of the data are "near"; # for visualization purposes, typically k = 2, which is assumed here # the idea here is to expand the data with polynomial terms, using # getPoly(), then apply PCA to the result # typically these methods are applied only to a subsample of the data, # due both to the lengthy computation time and the "black screen # problem" (having a lot of points fills the screen, rendering the plot # useless) # arguments: # xy: data frame # labels: if TRUE, last column is Y for a classification problem; # must be an R factor, unless nIntervals is non-NULL, in # which case Y will be discretized to make labels # deg: degree of polynomial expansion # scale: if TRUE, first call scale() on the X data # nSubSam: number of rows to randomly select; 0 means get all # nIntervals: in regression case, number of intervals to use for # partioning Y range to create labels # outliersRemoved: specify how many outliers to remove from # the plot, calculated using mahalanobis distance. if # outliersRemoved is between 0 and 1, a corresponding # percentage of the data will be removed # pcaMethod: specify how eigenvectors will be calculated, using # prcomp or RSpectra # saveOutputs: specify the name of the file where the results will be saved. # default file is 'lastPrVisOut'. set to the empty string to # not save results. # cex: argument to R plot(), controlling point size # alpha: a number between 0 and 1 that can be used to specify transparency # for alpha blending. If alpha is specified ggplot2 will be used to # create the plot prVis <- function(xy,labels=FALSE,yColumn = ncol (xy), deg=2, scale=FALSE,nSubSam=0,nIntervals=NULL, outliersRemoved=0,pcaMethod="prcomp", saveOutputs="lastPrVisOut",cex=0.5, alpha=0) { # safety check if (!pcaMethod %in% c('prcomp','RSpectra')) stop("pcaMethod should be either NULL, prcomp, or RSpectra") nrxy <- nrow(xy) ncxy <- ncol(xy) if (labels) { if (yColumn > ncol(xy) || yColumn <= 0) stop("The column specified is out of range") tmp <- xy[, ncxy] xy[, ncxy] <- xy[, yColumn] # swapping the last column with the user-specified column xy[, yColumn] <- tmp } rns <- row.names(xy) if (scale) { if (labels) { xy[,-ncxy] <- scale(xy[,-ncxy]) } else xy <- scale(xy) row.names(xy) <- rns } if (nSubSam < nrxy && nSubSam > 0) xy <- xy[sample(1:nrxy,nSubSam),] if (labels) { ydata <- xy[,ncxy] if (is.null(nIntervals) && !is.factor(ydata)) stop('Y must be a factor for classif.; set nIntervals for regress.') if (!is.null(nIntervals)) { rng <- range(ydata) increm <- (rng[2] - rng[1]) / nIntervals ydata <- round((ydata - rng[1]) / increm) ydata <- as.factor(ydata) } xdata <- xy[,-ncxy, drop=FALSE] } else xdata <- xy xdata <- as.matrix(xdata) polyMat <- getPoly(xdata, deg)$xdata if (pcaMethod == "prcomp") { x.pca <- prcomp(polyMat,center=TRUE) xdata <- x.pca$x[,1:2] } else { require(RSpectra) x.cov <- cov(polyMat) x.eig <- eigs(x.cov,2) x.pca <- x.eig xdata <- as.matrix(polyMat) %*% x.eig$vectors[,1:2] colnames(xdata) <- c("PC1","PC2") } if (outliersRemoved > 0 && outliersRemoved <= nrow(xdata)){ # percentage based outlier removal if (outliersRemoved < 1){ outliersRemoved = floor(outliersRemoved * nrow(xdata)) } # calculate mahalanobis distances for each data point xdataCov <- var(xdata) distances <- mahalanobis(xdata,colMeans(xdata),xdataCov) # find which row the max distances correspond to rownames(xdata) <- 1:nrow(xdata) if (labels) names(ydata) <- 1:nrow(xdata) names(distances) <- rownames(xdata) sortedDistances <- sort(distances, decreasing=TRUE) outliers <- names(sortedDistances)[1:outliersRemoved] # remove outliers xdata <- xdata[!rownames(xdata) %in% outliers,] if (labels) ydata <- ydata[!names(ydata) %in% outliers] } if (alpha) { require(ggplot2) if (labels) { plotObject <- qplot(x=xdata[,1],y=xdata[,2],xlab="PC1",ylab="PC2", alpha=alpha,col=ydata,size=I(cex)) } else { plotObject <- qplot(x=xdata[,1],y=xdata[,2],xlab="PC1",ylab="PC2", alpha=alpha,size=I(cex)) } print(plotObject) } else { if (labels) { plot(xdata, col=ydata, pch=15, cex=cex) } else { plot(xdata, pch=15, cex=cex) } } if (saveOutputs != ""){ if (labels && is.factor(ydata)) #xy has factor column, colName stores the name for all continuou #yname stores the name for the factor col outputList <- list(gpOut=polyMat,prout=x.pca, colName=colnames(xy[, -ncxy]), yCol = ydata, yname=colnames(xy)[ncxy]) else # xy has no factor column outputList <- list(gpOut=polyMat,prout=x.pca, colName=colnames(xy)) save(outputList,file=saveOutputs) } } # intended to be used when a plot produced by prVis() is on the screen; # chooses np points at random from the PCA output, writing their row # numbers on the plot; these are the numbers from the full dataset, even # if nSubSam > 0; the argument savedPrVisOut is the return value of # prVis() # # arguments: # np: the number of points to add row numbers to. if no value of np is # provided, rownumbers will be added to all datapoints # savedPrVisOut: the name of the file where a previous call to prVis was # stored. # area: vector with in the form of [x_start, x_finish, y_start, y_finish]. # x_start, x_finish, y_start, and y_finish should all be between 0 # and 1. These values correspond to percentages of the graph from # left to right and bottom to top. [0,1,0,1] specifies the entirety # of the graph. [0,0.5,0.5,1] specifies upper-left quadrant. x_start # must be less than x_finish and y_start must be less than y_finish addRowNums <- function(np=0,area=c(0,1,0,1),savedPrVisOut="lastPrVisOut") { load(savedPrVisOut) pcax <- outputList$prout$x[,1:2] if(is.null(row.names(pcax))) row.names(outputList$prout$x) <- as.character(1:nrow(outputList$prout$x)) if(identical(area, c(0,1,0,1))){ # get boundaries of graph xMin <- min(outputList$prout$x[,1]) xMax <- max(outputList$prout$x[,1]) yMin <- min(outputList$prout$x[,2]) yMax <- max(outputList$prout$x[,2]) # error checking on inputs xI <- area[1] xF <- area[2] yI <- area[3] yF <- area[4] if (xI < 0 | xI > 1 | xF < 0 | xF > 1 | xI > xF) if (yI < 0 | yI > 1 | yF < 0 | yF > 1 | yI > yF){ stop('invalid area boundaries, 0 < x_start < x_finish < 1, 0 < y_start < y_finish < 1. area is in the form of c(x_start,x_finish,y_start, y_finish)') } # scale x interval xI <- (xMax - xMin)*xI + xMin xF <- (xMax - xMin)*xF + xMin # scale y interval yI <- (yMax - yMin)*yI + yMin yF <- (yMax - yMin)*yF + yMin # filter to datapoints within specified range pcax <- pcax[which(pcax[,1] <= xF & pcax[,1] >= xI & pcax[,2] <= yF & pcax[,2] > yI),] } npcax <- nrow(pcax) tmp <- sample(1:npcax,np,replace=FALSE) rowNames <- row.names(pcax[tmp,]) print('highlighted rows:') sorted <- sort(as.numeric(rowNames)) for (i in 1:length(rowNames)) { rn <- rowNames[i] print(sorted[i]) coords <- pcax[rn,] text(coords[1],coords[2],rn) } } # colorCode: display color coding for user-specified vairables or expressions. # Normally called after prVis, produce a new coloring of the same plot produced # by prVis. # arguments: # colName: user can specify the column that he or she wants to produce # the color on. The column specified must be a continuous one. # If you want to produce the coloring based on a factor column, # prVis has already had the functionality. # n: rainbow parameter. We produce the coloring of a continuous variable # using function rainbow, and n is passed in to the function as an # option. # exps: expressions that create a label column that produces coloring. # If user specifies colName, he or she cannot provide arguments # for exps, since they are two ways to produce coloring (should # be mutually exclusive). User can supply several expressions, # each one corresponding to a group (a label, a color, a level), # and concatenating by c(). The expression should be mutually # exclusive, since a data point cannot be in two colors. # expression format: # <exp> ::= <subexpression> [(+|*) <subexpression>] # <subexpression> ::= columnname relationalOperator value # Note: * represents logic and, + represents logic or # savedPrVisOut: the file that stores a prVis object colorCode <- function(colName="",n=256,exps="", savedPrVisOut="lastPrVisOut", cex = 0.5) { load(savedPrVisOut) xdata <- outputList$gpOut[,1:length(outputList$colName)] plotData <- outputList$prout$x[,1:2] if (colName == "" && exps == "") stop("colName and expressions(exps) not specified") if (colName != "" && exps == "") { if (!colName %in% outputList$colName) stop("The column specified is not a continuous one or not found") else { # do continue color (rainbow) colNum = which(colName == outputList$colName) d <- xdata[,colNum] minVal <- min(d) maxVal <- max(d) diffVal <- maxVal - minVal colorPalette <- rev(rainbow(n,start=0,end=0.7)) colorIndexes <- sapply(d, function(x) ((x - minVal) * n) %/% diffVal) plot(plotData, col=colorPalette[colorIndexes]) } } else if(colName != "" && exps != "") # illegal specify both stop("colName for rainbow, exps for createFactor column") else { # create a label column with potentially more than one labels numberOfRows <- length(outputList$prout$x[,1]) userCol <- rep(NA, numberOfRows) # initialize label column hasY <- !(is.null(outputList$yname)) if (hasY) #original dataset has a factor column factorCol <- outputList$yCol hasLabel <- c() # track rows that has already had a label, check for relable for (i in 1:length(exps)) { # delete all white spaces (compress the string) exp <- gsub(" ", "", exps[i], fixed = TRUE) labelName <- exp #use the expression as the label name subExp <- unlist(strsplit(exp, "\\+|\\*")) for (m in 1:length(subExp)) exp <- sub(subExp[m], "", exp, fixed = T) exp <- unlist(strsplit(exp, split="")) #string to vector of characters #number of +/* operators should be one less than the number of constraints if (length(exp) != length(subExp) - 1) stop (length(exp)," +/* not match ",length(subExp)," constraints") for (j in 1:length(subExp)) { # solve one expression by solving all constraints # Ex has one constraint but the relational operator is extracted # EX : "Male", "1" Ex <- unlist(strsplit(subExp[j],"(==|>=|<=|>|<|!=)")) #relational ops if (length(Ex) != 2) # Ex should have two components: column name, value stop ("The constraint must follow the format: 'yourCol' 'relationalOperator' 'value'") else { tmp <- paste("\\b", Ex[1], sep="") tmp <- paste(tmp, "\\b", sep="") columnNum <- grep(tmp, outputList$colName) if (!length(columnNum) && (!hasY || tmp != outputList$yname)) stop("The specified column ",Ex[1]," is not found in the data frame xy") # restore the relational operator relationalOp <- sub(Ex[1], "", subExp[j], fixed= TRUE) relationalOp <- sub(Ex[2], "", relationalOp, fixed= TRUE) if (hasY && tmp == outputList$yname) # Ex[1] is the factorcol { if (!Ex[2] %in% levels(factorCol)) stop ("The label ", Ex[2], " is not in the factor column") # when ecounter operations between labels, only == and != make sense if (!relationalOp %in% c("==", "!=")) stop ("Use of the inappropriate operator ", relationalOp) # get the row numbers of data that satisfy the constraint userExp[i] rowBelong <- switch(relationalOp, "==" = which(factorCol == Ex[2]), "!=" = which (factorCol != Ex[2])) } else { # EX[1] is a continuous column, so Ex[2] should be a number val <- as.double(Ex[2]) if (is.null(val)||val< min(xdata[[columnNum]])||val > max(xdata[[columnNum]])) stop("The value ", Ex[2], " is out of the range") # get the row numbers of data that satisfy the constraint userExp[i] rowBelong <- switch(relationalOp, "==" = which(xdata[[columnNum]] == val), "!=" = which (xy[[columnNum]] != val),">="= which(xdata[[columnNum]]>=val), "<="=which(xdata[[columnNum]] <= val), ">" = which (xdata[[columnNum]] > val), "<" = which(xdata[[columnNum]] < val)) } } if (j == 1) # initialize labelData labelData <- rowBelong else { if (exp[j-1] == "*") # And, get the intersection of the row numbers labelData <- intersect(labelData, rowBelong) else # Or, get the union labelData <- union(labelData, rowBelong) } } # end for loop # check for overlaps! will cause relabel of certain data that satisfy two or # more expressions. Enforcing mutually exclusiveness between expressions if (length(intersect(labelData, hasLabel)) != 0) stop ("The expression ", i, " tries to relabel some data, the groups must be mutually exclusive") # gives the label to data that satisfy the expression userCol[labelData] <- labelName # update hasLabel to keep track of all data has been labeled hasLabel <- union(labelData, hasLabel) } # end big for loop if (length(hasLabel) == 0) # no matching data of the expressions stop ("Expression(s) match no data points") userCol[-hasLabel] <- "others" userCol <- as.factor(userCol) plot (plotData, col=userCol, pch=15, cex=cex) } # end createCol }
2a87270d132e197c8a76039782220e6ce2f3df94
c7d84bf201e560096c7925b9586343fac438d74a
/lectuer2-2.R
2f202e5fb2e3a0c9e9317b48bdc75557fe5dad02
[]
no_license
narendrameena/diffrentRScripts
029301f875d97c1ec5cea5c706e27fef9995f55a
e83942da0021a36284bea4124a3b6930032d9f63
refs/heads/master
2021-01-01T16:47:24.060418
2017-07-21T07:56:24
2017-07-21T07:56:24
97,921,634
0
0
null
null
null
null
UTF-8
R
false
false
1,528
r
lectuer2-2.R
library(devtools) install_github("jennybc/gapminder") library(gapminder) data(gapminder) head(gapminder) s =gapminder$year[[1952]] table(gapminder$year ==1952) hist(gapminder$lifeExp[which(gapminder$year==1952)]) hist(log10(gapminder$lifeExp[which(gapminder$year==1952)])) mean(gapminder$lifeExp[which(gapminder$year==1952)] <=40) mean(gapminder$lifeExp[which(gapminder$year==1952)]<=60 )-mean( gapminder$lifeExp[which(gapminder$year==1952)] <=40) prop =function(q){ mean(50<=q) } qs =seq(from=min(1),to=max(100),length=20) props =sapply(qs,prop) plot(qs,props) props =sapply(qs,function(q) mean(30<=q)) plot(ecdf) pop = gapminder$pop[which(gapminder$year==1952)] s = split(gapminder$pop[which(gapminder$year==1952)],gapminder$country[which(gapminder$year==1952)]) s s<- plot(gapminder$country[which(gapminder$year==1952)],log10(gapminder$pop[which(gapminder$year==1952)]), type="h") s hist(log10(gapminder$pop[which(gapminder$year==1952)])) sd(log10(gapminder$pop[which(gapminder$year==1952)])) mean(log10(gapminder$pop[which(gapminder$year==1952)])) fun <- function(q){ return(pnorm(q,mean=mean(log10(gapminder$pop[which(gapminder$year==1952)])),sd=sd(log10(gapminder$pop[which(gapminder$year==1952)])))) } nd<-fun(7)-fun(6) nd n = length(log10(gapminder$pop[which(gapminder$year==1952)])) n nc=n*nd nc qqnorm(log10(gapminder$pop[which(gapminder$year==1952)])) ps=((1:n)-0.5)/n ps qqnorm(ps) sort(log10(gapminder$pop[which(gapminder$year==1952)])) plot(qnorm(ps),sort(log10(gapminder$pop[which(gapminder$year==1952)])))
61dbe80fa10793473067f427c00f7c4a87269cf7
4daca2e1978ed5fb927db5af6e6e36a372608c16
/R/functions/descriptorImportancePlots.R
916a972555bc04db265ad988ba791c6f84027ee3
[ "CC-BY-4.0" ]
permissive
jasenfinch/Index_measures_for_oak_decline_severity_using_phenotypic_descriptors
518ac57f78d23bad929e26284e4dbbaa30fa8ca8
c4928890a4993dcca5797d4f854027f1f6d70404
refs/heads/master
2023-03-17T11:57:03.033059
2021-03-09T20:31:14
2021-03-09T20:31:14
165,732,718
0
0
null
null
null
null
UTF-8
R
false
false
4,419
r
descriptorImportancePlots.R
descriptorImportancePlots <- function(PDI_descriptor_importance,DAI_descriptor_importance){ importance_plots <- list( a = { dat <- PDI_descriptor_importance %>% arrange(`%IncMSE`) %>% mutate(Feature = factor(Feature,levels = Feature), rev_Rank = Feature %>% seq_along()) descriptorLabels <- dat$Feature %>% as.character() %>% { .[str_detect(.,coll('Agrilus exit hole density (m^-2)'))] <- expression(Agrillus~exit~hole~density ( m^-2 ) ) .[str_detect(.,coll('Crown volume (m^3)'))] <- expression(Crown~volume ( m^3 ) ) return(.) } ggplot(dat,aes(y = Feature,x = `%IncMSE`)) + geom_segment(aes(y = rev_Rank,yend = rev_Rank,x = -5,xend = `%IncMSE`)) + geom_point(fill = ptol_pal()(1),shape = 21,size = 2) + theme_bw() + theme(plot.title = element_text(face = 'bold',hjust = 0.5), axis.title = element_text(face = 'bold',size = 10), panel.grid = element_blank(), panel.border = element_blank(), plot.margin = unit(c(5.5, 0, 5.5, 5.5), "pt"), axis.line.x = element_line(), axis.text.y = element_text(colour = 'black'), axis.ticks.y = element_blank()) + labs(title = 'a) PDI', x = '% increase in\nMSE', y = NULL) + scale_y_discrete(labels = descriptorLabels) + scale_x_reverse(limits = c(112,-5), expand = c(0,0)) }, b = { dat <- DAI_descriptor_importance %>% arrange(`%IncMSE`) %>% mutate(Feature = factor(Feature,levels = Feature), rev_Rank = Feature %>% seq_along()) descriptorLabels <- dat$Feature %>% as.character() %>% { .[str_detect(.,coll('Agrilus exit hole density (m^-2)'))] <- expression(Agrillus~exit~hole~density ( m^-2 ) ) .[str_detect(.,coll('Crown volume (m^3)'))] <- expression(Crown~volume ( m^3 ) ) return(.) } ggplot(dat,aes(y = Feature,x = `%IncMSE`)) + geom_segment(aes(y = rev_Rank,yend = rev_Rank,x = -5,xend = `%IncMSE`)) + geom_point(fill = ptol_pal()(1),shape = 21,size = 2) + theme_bw() + theme(plot.title = element_text(face = 'bold',hjust = 0.5), axis.title = element_text(face = 'bold',size = 10), panel.grid = element_blank(), panel.border = element_blank(), plot.margin = unit(c(5.5, 5.5, 5.5, 0), "pt"), axis.line.x = element_line(), axis.text.y = element_text(colour = 'black'), axis.ticks.y = element_blank()) + labs(title = 'b) DAI', x = '% increase in\nMSE', y = NULL) + scale_y_discrete(labels = descriptorLabels, position = 'right') + scale_x_continuous(limits = c(-5,112), expand = c(0,0)) } ) rank_links <- PDI_descriptor_importance %>% arrange(`%IncMSE`) %>% mutate(Feature = factor(Feature,levels = Feature), PDI_Rank = Feature %>% seq_along()) %>% select(-`%IncMSE`,-IncNodePurity) %>% left_join(DAI_descriptor_importance %>% arrange(`%IncMSE`) %>% mutate(Feature = factor(Feature,levels = Feature), DAI_Rank = Feature %>% seq_along()) %>% select(-`%IncMSE`,-IncNodePurity), by = "Feature") %>% ggplot() + geom_segment(x = 0, xend = 0, y = 1,yend = 36) + geom_segment(x = 1, xend = 1, y = 1,yend = 36) + geom_segment(aes(y = PDI_Rank, yend = DAI_Rank, x = 0, xend = 1), linetype = 5) + theme_bw() + theme(panel.border = element_blank(), panel.grid = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.text = element_blank(), plot.margin = unit(c(5.5, 0, 5.5, 0), "pt")) + scale_x_continuous(expand = c(0,0)) + scale_y_discrete(labels = descriptorLabels) wrap_plots(importance_plots$a,rank_links,importance_plots$b,widths = c(2,1,2)) }
5525d708ae110e18d54f817be141e08c67eda71c
a4bf8ea2ca052a6ebaa8d32ea427eb4f747e3b67
/inst/doc/edl.R
1da1a0657ee594f760b1f6a5de31c290b7f21d7f
[]
no_license
cran/edl
941498a8f2b8d8df00ffa7c317d707ff25c189f9
c40160df056e31bfafda4197405bddf89158d4b4
refs/heads/master
2023-08-11T09:11:13.818275
2021-09-20T06:40:05
2021-09-20T06:40:05
357,249,841
0
0
null
null
null
null
UTF-8
R
false
false
7,970
r
edl.R
## ----setup, include=FALSE----------------------------------------------------- knitr::opts_chunk$set(echo = TRUE, fig.width = 4, fig.height = 4) ## ----load-packages,message=FALSE---------------------------------------------- library(edl) ## ----------------------------------------------------------------------------- data(dat) head(dat) ## ----------------------------------------------------------------------------- dat$Cues <- paste("BG", dat$Shape, dat$Color, sep="_") dat$Outcomes <- paste(dat$Category) dat$Frequency <- dat$Frequency2 # remove remaining columns to simplify this example: dat <- dat[, c("Cues", "Outcomes", "Frequency")] # add ID for learning events: dat$ID <- 1:nrow(dat) head(dat) ## ----------------------------------------------------------------------------- table(dat$Outcomes) ## ----------------------------------------------------------------------------- # by default 1 run, with tokens randomized: train <- createTrainingData(dat) head(train) # Frequency is always 1: unique(train$Frequency) # total counts per outcome match original frequencies: table(train$Outcomes) table(train$ID) ## ---- eval=FALSE-------------------------------------------------------------- # wm <- RWlearning(train) ## ---- include=FALSE----------------------------------------------------------- wm <- RWlearning(train, progress = FALSE) ## ----------------------------------------------------------------------------- length(wm) # ... which is the same as the number of rows in the training data: nrow(train) ## ----------------------------------------------------------------------------- # after the first learning event: wm[[1]] # the final state of the network: wm[[length(wm)]] ## ----------------------------------------------------------------------------- # after the first learning event: getWM(wm,1) ## ----------------------------------------------------------------------------- wm2 <- sapply(1:length(wm), function(x){getWM(wm,x)}, simplify = FALSE) # inspect the list of states: length(wm2) wm2[[1]] ## ----------------------------------------------------------------------------- # weights for outcome "plant" weights <- getWeightsByOutcome(wm, outcome="plant") head(weights) tail(weights) ## ----------------------------------------------------------------------------- # weights for cue "red" weights <- getWeightsByCue(wm, cue="red") head(weights) tail(weights) ## ----------------------------------------------------------------------------- act <- getActivations(wm, data=train) head(act) ## ----------------------------------------------------------------------------- act <- getActivations(wm, data=train, select.outcomes = TRUE) head(act) ## ----------------------------------------------------------------------------- act$Activation <- apply(act, 1, function(x){ out <- x['Outcomes'] return(as.numeric(x[out])) }) head(act) ## ----plots-1, fig.width=8----------------------------------------------------- oldpar <- par(mfrow=c(1,2), cex=1.1) # plot left: plotCueWeights(wm, cue="brown") # plot right: plotOutcomeWeights(wm, outcome="animal") par(oldpar) ## ----plots-2, fig.width=8----------------------------------------------------- oldpar <- par(mfrow=c(1,2), cex=1.1) # plot left: # 1. get outcome values: out <- getValues(train$Outcomes, unique=TRUE) out <- out[out != "animal"] # 2. plot all outcomes, except 'plural': lab <- plotCueWeights(wm, cue="brown", select.outcomes = out, col=1, add.labels=FALSE, xlab='', ylim=range(getWM(wm))) # 3. add plural: lab2 <- plotCueWeights(wm, cue="brown", select.outcomes = "animal", col=2, lwd=2, adj=0, add=TRUE, font=2) # 4. add legend: legend_margin('bottom', ncol=4, legend=c(lab2$labels, lab$labels), col=c(lab2$col, lab$col), lty=c(lab2$lty, lab$lty), lwd=c(lab2$lwd, lab$lwd), bty='n', cex=.85) # plot right, different layout variant: out <- getValues(dat$Cues, unique=TRUE) out <- out[out != "animal"] lab <- plotOutcomeWeights(wm, outcome="animal", select.cues = out, col=alpha(1, f=.25), lty=1, pos=4, ylim=c(-.02,.2), font=2, ylim=range(getWM(wm))) lab2 <- plotOutcomeWeights(wm, outcome="animal", select.cues = "brown", col='red', lwd=2, pos=4, add=TRUE, font=2) par(oldpar) ## ----getWeights-1------------------------------------------------------------- weights <- getWeightsByCue(wm, cue="brown") head(weights) ## ---- fig.width=8, results='hold'--------------------------------------------- oldpar <- par(mfrow=c(1,2), cex=1.1) # an observed cueset: plotActivations(wm, cueset="BG_cat_brown") # an un-observed cueset: plotActivations(wm, cueset="BG_cat_yellow") par(oldpar) ## ----continue-1--------------------------------------------------------------- # create a second data set with different frequencies: data(dat) head(dat) ## ----------------------------------------------------------------------------- dat$Cues <- paste("BG", dat$Shape, dat$Color, sep="_") dat$Outcomes <- paste(dat$Category) dat$Frequency <- dat$Frequency1 # remove remaining columns to simplify this example: dat <- dat[, c("Cues", "Outcomes", "Frequency")] # add ID for learning events: dat$ID <- 1:nrow(dat) head(dat) # create training data: train2 <- createTrainingData(dat) ## ----------------------------------------------------------------------------- # continue learning from last weight matrix: wm2 <- RWlearning(train2, wm=getWM(wm), progress = FALSE) # number of learned event matches rows in dat2: nrow(train2) length(wm2) # Alternatively, add the learning events to the existing output list wm1: wm3 <- RWlearning(train2, wm=wm, progress = FALSE) # number of learned event are now added to wm1: length(wm3) ## ----------------------------------------------------------------------------- out <- getValues(dat$Cues, unique=TRUE) out <- out[out != "animal"] lab <- plotOutcomeWeights(wm3, outcome="animal", select.cues = out, col=alpha(1, f=.25), lty=1, pos=4, ylim=c(-.02,.2), font=2, ylim=range(getWM(wm3)), xmark=TRUE, ymark=TRUE, las=1) lab2 <- plotOutcomeWeights(wm3, outcome="animal", select.cues = "brown", col='red', lwd=2, pos=4, add=TRUE, font=2) abline(v=length(wm), lty=3) ## ----------------------------------------------------------------------------- # select weight matrix: mat <- getWM(wm) # for a cueset: activationsMatrix(mat,cues="BG_cat_brown") # for a specific outcome: activationsMatrix(mat,cues="BG_cat_brown", select.outcomes = "animal") # for a group of cuesets (all connection weights will be added): activationsMatrix(mat,cues=c("BG_cat_brown", "BG_cat_blue")) ## ----------------------------------------------------------------------------- # new dummy data: dat <- data.frame(Cues = c("noise", "noise", "light"), Outcomes = c("food", "other", "food_other"), Frequency = c(5, 10, 15) ) dat$Cues <- paste("BG", dat$Cues, sep="_") train <- createTrainingData(dat) wm <- RWlearning(train, progress = FALSE) # list with activations for observed outcomes: act <- activationsEvents(wm, data=train) head(act) # calculate max activation: maxact <- lapply(act, function(x){ return(max(x, na.rm=TRUE)) }) unlist(maxact) # Using argument 'fun': act <- activationsEvents(wm, data=train, fun="max") head(act) ## ----------------------------------------------------------------------------- # list with activations for observed outcomes: act <- activationsCueSet(wm, cueset=c("BG_noise", "BG_light", "BG_somethingelse")) names(act) head(act[[1]]) # also activations for non-trained connections: head(act[[3]]) ## ----------------------------------------------------------------------------- # list with activations for observed outcomes: act <- activationsOutcomes(wm, data=train) head(act)
f9e45ef6b8af83ad12427af9b37ece404d0e5608
2fb32969061efc165421d571e688848240e537a5
/man/plostitle.Rd
60d20941deb0ddf912ad83625b881df69757ceec
[]
no_license
phillord/rplos
cb740bb57eb9f249e94aa360ca11c6d36144f439
a0e75c4399d85fd98709fcccdc28bf7e5ff32471
refs/heads/master
2021-01-15T18:41:41.776122
2012-10-23T15:18:37
2012-10-23T15:18:37
8,477,914
1
0
null
null
null
null
UTF-8
R
false
false
985
rd
plostitle.Rd
\name{plostitle} \alias{plostitle} \title{Search PLoS Journals titles.} \usage{ plostitle(terms, fields = NULL, limit = NULL, url = "http://api.plos.org/search", key = getOption("PlosApiKey", stop("need an API key for PLoS Journals"))) } \arguments{ \item{terms}{search terms for article titles (character)} \item{fields}{fields to return from search (character) [e.g., 'id,title'], any combination of search fields [see plosfields$field]} \item{limit}{number of results to return (integer)} \item{url}{the PLoS API url for the function (should be left to default)} \item{key}{your PLoS API key, either enter, or loads from .Rprofile} } \value{ Titles, in addition to any other fields requested in a data.frame. } \description{ Search PLoS Journals titles. } \examples{ \dontrun{ plostitle(terms='drosophila', fields='title', limit=99) plostitle(terms='drosophila', fields='title,journal', limit=10) plostitle(terms='drosophila', limit = 5) } }
a2bcbe3fce797b854786d6827d60bca3ba8d7bfc
64257a0e57cf928b0ae7676a108a3688001181bd
/tests/testthat/test-count_events.R
5b81b9c4419bcb0c048109af32c7c2d9dea6ff8e
[ "BSD-3-Clause" ]
permissive
marcpaterno/artsupport
9842a678c8070468dd93a258810b84067fe22f32
803310561741c4aa54bdd44e393da9ae8551bfa0
refs/heads/master
2020-06-30T06:49:04.780687
2020-04-20T23:14:48
2020-04-20T23:14:48
74,387,093
0
1
NOASSERTION
2019-02-07T07:11:33
2016-11-21T17:15:33
R
UTF-8
R
false
false
468
r
test-count_events.R
context("count_events") test_that("counting (distinct) events works for unlabeled data", { a <- load_module_timing("timing-a.db") expect_equal(count_events(a), 120) b <- load_module_timing("timing-b.db") expect_equal(count_events(b), 240) }) test_that("counting (distinct) events works for labeled data", { a <- load_module_timing("timing-a.db", "a") b <- load_module_timing("timing-b.db", "b") x <- rbind(a, b) expect_equal(count_events(x), 360) })
3fa9eeef2f9df5e8b2e60f6fc9ffc80b2ce0ca47
9713c2a057cb71e8641e6f40fea276ac4e722a34
/Paper/Descriptive_Analysis.R
90eadbb3b234cd39d7934c70a16555d4a75ac330
[]
no_license
Insper-Data/Data_Macro
4da269c71d2af6d72a1965659083a547e2403688
c805895f45ddc162d614829e8ca1b70677a3b4f7
refs/heads/master
2023-07-12T02:30:39.424353
2021-08-25T22:11:04
2021-08-25T22:11:04
296,466,536
4
4
null
2020-11-02T21:52:55
2020-09-17T23:44:59
HTML
UTF-8
R
false
false
20,078
r
Descriptive_Analysis.R
# JANUARY 2021 # Script to generate figures used in our paper # Authors: Augusto Netto, Gabriela Garcia, Maria Clara Drzeviechi and Victor H. Alexandrino #-------------------------------------------------------------------------------------------- # Libraries library(scales) library(dplyr) library(ggthemes) library(spData) library(readr) library(readxl) library(spData) library(plotly) library(sf) library(viridis) library(ggcharts) library(ggrepel) library(cowplot) library(tidyr) library(dplyr) library(grid) library(forecast) # Calling our dataset dataset_total_jan_2021 <- read.csv("https://raw.githubusercontent.com/Insper-Data/Data_Macro/master/Paper/Datasets/dataset_total_jan_2021.csv") dataset_total <- dataset_total_jan_2021 #-------------------------------------------------------------------------------------------- # STYLIZED FACTS ABOUT THE DATABASE #-------------------------------------------------------------------------------------------- # 1. The importance of debt debt_to_gdp_graph <- dataset_total %>% rename(Development = develop) %>% group_by(Development, year) %>% summarise(debt_to_GDP = mean(debt_to_GDP)) %>% ggplot(aes(x = year, y = debt_to_GDP, color=Development )) + scale_color_manual(values = c("EM" = "red4", "AM" = "navyblue"))+ geom_point() + geom_line()+ labs(x = "Year", y = "Debt-to-GDP Ratio (%)", title = "", subtitle = "") + scale_x_continuous(limits = c(2004, 2019), seq(2004,2019,by=2), name = "Year") + ylim(30,90)+ theme_bw() debt_to_gdp_graph # 2. dataset_total %>% filter(year %in% c(2004, 2010, 2014, 2019), !is.na(develop)) %>% rename(Development = develop) %>% bar_chart(x = country, y = debt_to_GDP, facet = year, top_n = 10, fill = Development) + labs( x = "", y = "Debt-to-GDP Ratio (%)", title = "", fill = "Development") + theme_classic() + scale_fill_manual("Development", values = c("EM" = "red4", "AM" = "navyblue"))+ theme(legend.title = element_text(face = "bold", size = 10)) # 3. graph_debt_foreign_pp <- dataset_total %>% filter(!is.na(develop)) %>% rename(Development = develop) %>% group_by(year, Development) %>% summarise(foreign_participation_percent_GDP = mean(foreign_participation_percent_GDP)) %>% ggplot(aes(x = year, y = foreign_participation_percent_GDP, color=Development )) + scale_color_manual(values = c("EM" = "red4", "AM" = "navyblue"))+ geom_point() + geom_line()+ labs(x = "Year", y = "Foreign Participation in Sovereign Debt in Terms of GDP (%)", title = "", subtitle = "") + scale_x_continuous(limits = c(2004, 2019), seq(2004,2019,by=2), name = "Year") + #ylim(50,160)+ theme_light() graph_debt_foreign_pp # 4. dataset_total %>% rename(Development = develop) %>% filter(year %in% c(2004, 2010, 2014, 2019), !is.na(Development)) %>% bar_chart(x = country, y = (foreign_participation_percent_GDP), facet = year, top_n = 10, fill = Development) + labs( x = "", y = "Foreign Participation in Sovereign Debt in Terms of GDP (%)", title = "", fill = "Development") + theme_classic() + theme(legend.title = element_text(face = "bold", size = 10)) + scale_fill_manual("Development", values = c("EM" = "red4", "AM" = "navyblue")) ################################################ FUNDAMENTALS ################################################################################################################ # 5.1 dataset_total %>% filter(develop == "AM") %>% ggplot(aes(x = fx_volatility, y = foreign_participation_percent_GDP)) + geom_point(color="navyblue")+ labs(x = "Exchange Rate Volatility", y = "Foreign Participation in Sovereign Debt in Terms of GDP (%)") + xlim(0,1)+ theme_bw() # 5.2 dataset_total %>% filter(develop == "EM" ) %>% ggplot(aes(x = fx_volatility, y = foreign_participation_percent_GDP)) + geom_point(color="red4")+ labs(x = "Exchange Rate Volatility", y = "Foreign Participation in Sovereign Debt in Terms of GDP (%)") + xlim(0,1)+ theme_bw() # 5.3 Mostra a relação da inflação com a participação na dívida e o tamanho da bolinha é o PIB percapita (note que ele vai diminuindo) dataset_total %>% group_by(country) %>% mutate(mean_indebt = mean(debt_to_GDP, na.rm = T), mean_inflation = mean(inflation_end, na.rm = T), mean_fiscal = mean(lending_borrowing_percent_GDP, na.rm = T), mean_percapita = mean(GDP_percapita_cur_USD, na.rm = T), upper = max(foreign_participation_percent_GDP), lower = min(foreign_participation_percent_GDP), GDP_percapita_cur_USD = GDP_percapita_cur_USD/1000) %>% ggplot() + geom_point(aes(x = mean_inflation, y = foreign_participation_percent_GDP, colour = develop, size = GDP_percapita_cur_USD), alpha = .2) + #geom_errorbar(aes(ymin = lower, ymax = upper), width = .2) + labs(x = "Mean Inflation Between 2004-2019 (%)", y = "Foreign Participation in Sovereign\n Debt in Terms of GDP (%)") + scale_color_manual(values = c("navyblue", "red4")) + guides(col=guide_legend(""), size=guide_legend("GDP per capita \n(thousand USD)")) + theme_light() + theme(axis.text.y = element_text(margin = margin(l = 8)), axis.text.x = element_text(margin = margin(b = 8))) # 5.4 Mesmo que no de cima, mas colorindo por país dataset_total %>% group_by(country) %>% mutate(mean_indebt = mean(debt_to_GDP, na.rm = T), mean_inflation = mean(inflation_end, na.rm = T), mean_fiscal = mean(lending_borrowing_percent_GDP, na.rm = T), mean_percapita = mean(GDP_percapita_cur_USD, na.rm = T)) %>% ggplot() + geom_point(aes(x = mean_inflation, y = foreign_participation_percent_GDP, colour = country, size = political_stability_rank), alpha = .5)+ #labs(x = "ln(GDP per capita USD)", y = "Foreign Participation in Sovereign Debt in Terms of GDP (%)") + #scale_color_viridis_d("magma") + theme_light() + theme(legend.position = "none") # 5.5 Relação entre volatilidade do crescimento real e a participação dataset_total %>% group_by(country) %>% mutate(mean_indebt = mean(debt_to_GDP, na.rm = T), mean_inflation = mean(inflation_end, na.rm = T), mean_fiscal = mean(lending_borrowing_percent_GDP, na.rm = T), mean_percapita = mean(GDP_percapita_cur_USD, na.rm = T), GDP_growth = (GDP_cte_billions - lag(GDP_cte_billions, k = 1))/lag(GDP_cte_billions, k = 1), sd_GDP_growth = sd(GDP_growth, na.rm = T), mean_share = mean(foreign_participation_percent_GDP)) %>% ggplot() + geom_label(aes(x = sd_GDP_growth, y = mean_share, colour = develop, size = mean_indebt, label = country), alpha = .3) + #labs(x = "ln(GDP per capita USD)", y = "Foreign Participation in Sovereign Debt in Terms of GDP (%)") + scale_color_manual(values = c("navyblue", "red4")) + theme_light() + facet_wrap(~develop) + theme(legend.position = "none") # 5.6 Relação entre média do crescimento real e a participação - sensibilizando por Rule of Law dataset_total %>% group_by(country) %>% mutate(mean_indebt = mean(debt_to_GDP, na.rm = T), mean_inflation = mean(inflation_end, na.rm = T), mean_fiscal = mean(lending_borrowing_percent_GDP, na.rm = T), mean_percapita = mean(GDP_percapita_cur_USD, na.rm = T), GDP_growth = (GDP_cte_billions - lag(GDP_cte_billions, k = 1))/lag(GDP_cte_billions, k = 1), mean_GDP_growth = mean(GDP_growth, na.rm = T), sd_GDP_growth = sd(GDP_growth, na.rm = T), mean_rule = mean(rule_of_law_rank, na.rm = T), mean_share_ex_off = mean(foreign_ex_officials_participation_percent_GDP)) %>% ggplot() + geom_label(aes(x = mean_GDP_growth, y = mean_share_ex_off, colour = develop, size = mean_rule, label = country), alpha = .3) + guides(size = guide_legend("Rule of\nLaw"), colour = FALSE) + labs(x = "Mean GDP Growth Between 2004-2019 (%)", y = "Mean Foreign Participation in\nSovereign Debt in Terms of GDP (%)") + scale_color_manual(values = c("navyblue", "red4")) + theme_light() + theme(axis.text.y = element_text(margin = margin(l = 8)), axis.text.x = element_text(margin = margin(b = 8))) + facet_wrap(~develop) # 5.7 Relação entre volatilidade do cambio e a participação - sensibilizando por debt-to-gdp dataset_5.7_int <- dataset_total %>% filter(country == "United States") %>% group_by() %>% select(year, inflation_end) %>% rename(US_inflation_rate = inflation_end) dataset_5.7 <- dataset_total %>% left_join(dataset_5.7_int, by = "year") dataset_5.7 %>% group_by(country) %>% mutate(mean_indebt = mean(debt_to_GDP, na.rm = T), mean_inflation = mean(inflation_end, na.rm = T), mean_fiscal = mean(lending_borrowing_percent_GDP, na.rm = T), mean_percapita = mean(GDP_percapita_cur_USD, na.rm = T), GDP_growth = (GDP_cte_billions - lag(GDP_cte_billions, k = 1))/lag(GDP_cte_billions, k = 1), mean_GDP_growth = mean(GDP_growth, na.rm = T), sd_GDP_growth = sd(GDP_growth, na.rm = T), x = US_inflation_rate/inflation_end, fx_vol_real = mean(x, na.rm = T), mean_share_ex_off = mean(foreign_ex_officials_participation_percent_GDP)) %>% ggplot() + geom_point(aes(x = log(fx_volatility*10000), y = foreign_participation_percent_GDP, colour = develop, size = debt_to_GDP), alpha = .3) + #labs(x = "ln(GDP per capita USD)", y = "Foreign Participation in Sovereign Debt in Terms of GDP (%)") + scale_color_manual(values = c("navyblue", "red4")) + theme_light() #+ facet_wrap(~develop) + theme(legend.position = "none") # 5.8 Níveis de inflação dividindo por desenvolvimento x_order <- c("From -1 to 2.5", "From 2.5 to 5", "From 5 to 7.5", "From 7.5 to 10", "From 10 to 12.5", "From 12.5 to 15", "15 +") dataset_total %>% mutate(inflation_level = ifelse(inflation_end > - 1 & inflation_end <= 2.5, "From -1 to 2.5", ifelse(inflation_end < 5, "From 2.5 to 5", ifelse(inflation_end < 7.5, "From 5 to 7.5", ifelse(inflation_end < 10, "From 7.5 to 10", ifelse(inflation_end < 12.5, "From 10 to 12.5", ifelse(inflation_end < 15, "From 12.5 to 15", "15 +"))))))) %>% filter(!is.na(inflation_level)) %>% ggplot() + geom_violin(aes(factor(inflation_level, levels = x_order), foreign_participation_percent_GDP, fill = develop, colour = develop), trim = T) + geom_vline(xintercept = 1.5, color = "black", size = .6) + geom_vline(xintercept = 2.5, color = "black", size = .6) + geom_vline(xintercept = 3.5, color = "black", size = .6) + geom_vline(xintercept = 4.5, color = "black", size = .6) + geom_vline(xintercept = 5.5, color = "black", size = .6) + geom_vline(xintercept = 6.5, color = "black", size = .6) + scale_color_manual(values = c("navyblue", "red4")) + scale_fill_manual(values = c("navyblue", "red4")) + guides(fill = guide_legend(""), color = guide_legend("")) + theme_light() + labs(x = "Inflation Level (%)", y = "Foreign Participation in Sovereign\n Debt in Terms of GDP (%)") + theme(axis.line.x = element_line(colour = "black", size = .6), axis.line.y = element_line(colour = "black", size = .6), axis.text.y = element_text(margin = margin(l = 8)), axis.text.x = element_text(margin = margin(b = 8))) # 5.8 Níveis de inflação x_order <- c("From -1 to 2.5", "From 2.5 to 5", "From 5 to 7.5", "From 7.5 to 10", "From 10 to 12.5", "From 12.5 to 15", "15 +") dataset_total %>% mutate(inflation_level = ifelse(inflation_end > - 1 & inflation_end <= 2.5, "From -1 to 2.5", ifelse(inflation_end < 5, "From 2.5 to 5", ifelse(inflation_end < 7.5, "From 5 to 7.5", ifelse(inflation_end < 10, "From 7.5 to 10", ifelse(inflation_end < 12.5, "From 10 to 12.5", ifelse(inflation_end < 15, "From 12.5 to 15", "15 +"))))))) %>% filter(!is.na(inflation_level)) %>% ggplot() + geom_violin(aes(factor(inflation_level, levels = x_order), foreign_participation_percent_GDP), fill = "black") + scale_color_manual(values = c("navyblue", "red4")) + scale_fill_manual(values = c("navyblue", "red4")) + theme_light() + xlab("Inflation Levels (%)") # 5.9 Relação entre volatilidade do cambio e a participação - sensibilizando por rule of law dataset_5.9_int <- dataset_total %>% filter(country == "United States") %>% group_by() %>% select(year, inflation_end) %>% rename(US_inflation_rate = inflation_end) dataset_5.9 <- dataset_total %>% left_join(dataset_5.9_int, by = "year") dataset_5.9 %>% group_by(country) %>% mutate(mean_indebt = mean(debt_to_GDP, na.rm = T), mean_inflation = mean(inflation_end, na.rm = T), mean_fiscal = mean(lending_borrowing_percent_GDP, na.rm = T), mean_percapita = mean(GDP_percapita_cur_USD, na.rm = T), GDP_growth = (GDP_cte_billions - lag(GDP_cte_billions, k = 1))/lag(GDP_cte_billions, k = 1), mean_GDP_growth = mean(GDP_growth, na.rm = T), sd_GDP_growth = sd(GDP_growth, na.rm = T), x = US_inflation_rate/inflation_end, fx_vol_real = mean(x, na.rm = T), mean_share_ex_off = mean(foreign_ex_officials_participation_percent_GDP)) %>% ggplot() + geom_point(aes(x = log(fx_volatility*10000), y = foreign_participation_percent_GDP, colour = develop, size = rule_of_law_rank), alpha = .4) + labs(x = "FX Volatility*", y = "Foreign Participation in Sovereign\n Debt in Terms of GDP (%)") + scale_color_manual(values = c("navyblue", "red4")) + guides(col=guide_legend(""), size=guide_legend("Rule of\nLaw Rank")) + theme_light() + theme(axis.text.y = element_text(margin = margin(l = 8)), axis.text.x = element_text(margin = margin(b = 8))) ################################## EXTERNAL FACTORS ############################################################## dataset_total2 <- dataset_total %>% select(vix_EUA, foreign_participation_percent_GDP, year, develop, country) dataset_total2 <- dataset_total2 %>% group_by(year) %>% mutate(VIX = mean(vix_EUA)) dataset_total2 <- dataset_total2 %>% group_by(year, develop) %>% mutate(foreign_GDP = mean(foreign_participation_percent_GDP)) dataset_total2 <- dataset_total2 %>% select(3,4,6,7) dataset_total2 <- dataset_total2 %>% distinct() dataset3 <- dataset_total2 dataset3 <- dataset3 %>% mutate(foreign_AM = ifelse(develop == "AM", foreign_GDP, 0)) dataset3 <- dataset3 %>% filter(foreign_AM != 0) dataset4 <- dataset_total2 dataset4 <- dataset4 %>% mutate(foreign_EM = ifelse(develop =="EM", foreign_GDP, 0)) dataset4 <- dataset4 %>% filter(foreign_EM != 0) dataset3 <- dataset3 %>% select(1,3,5) dataset4 <- dataset4 %>% select(1,3,5) dataset4 <- dataset4 %>% left_join(dataset3, by="year") dataset4 <- dataset4 %>% select(2,3,4,7) dataset4 <- dataset4 %>% rename(VIX = 2, AM = 4, EM = 3 ) %>% mutate(VIX = (VIX/100)) dataset4 <- dataset4 %>% select(year, VIX, AM, EM) %>% gather(key = "variable", value = "value", -year) ggplot(dataset4, aes(x = year, y = value)) + geom_line(aes(color = variable), size = 1) + scale_color_manual(values = c("navyblue", "red4" , "black")) + labs(x = "Year", y = "", title = "", subtitle = "") + scale_x_continuous(limits = c(2004, 2019), seq(2004, 2019, by=2), name = "Year") + scale_y_continuous(breaks=NULL) + theme_bw() # Another way to display the same graph: dataset5 <- dataset_total %>% select(year, vix_EUA) %>% filter(row_number() <= 16) %>% rename(value = vix_EUA) %>% mutate(variable = "US VIX") dataset6 <- dataset_total %>% filter(!is.na(foreign_participation_percent_GDP)) %>% group_by(year, develop) %>% summarise(foreign_GDP = mean(foreign_participation_percent_GDP), year = year) %>% select(c(year, foreign_GDP)) %>% distinct() %>% rename(variable = develop, value = foreign_GDP) p1 <- dataset5 %>% ggplot() + geom_line(aes(x = year, y = value, colour = variable), size = 1) + scale_color_manual(values = c("black")) + labs(x = "", y = "US VIX", title = "", subtitle = "") + scale_x_continuous(limits = c(2004, 2019), seq(2004, 2019, by=2), name = "Year") + #scale_y_continuous(breaks=NULL) + theme_light() + theme(legend.title = element_blank(), axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.line.x = element_line(color = "black"), panel.border = element_blank(), plot.caption = element_blank(), axis.text.y = element_text(margin = margin(l = 8))) (p2 <- dataset6 %>% ggplot(aes(x = year, y = value, fill = variable)) + geom_col(position = "dodge") + scale_fill_manual(values = c("navyblue", "red4")) + labs(x = "Year", y = "Foreign Participation in \nSovereign Debt (% of GDP)", title = "", subtitle = "") + scale_x_continuous(limits = c(2003, 2020), seq(2004, 2019, by = 2), name = "Year") + #scale_y_continuous(breaks=NULL) + theme_light() + theme(legend.title = element_blank(), plot.title = element_blank(), axis.line.x = element_line(color = "black"), panel.border = element_blank(), plot.subtitle = element_blank(), axis.text.y = element_text(margin = margin(l = 8)))) grid.newpage() grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last")) #DXY # 3. dataset7 <- dataset_total %>% select(year, dxy) %>% filter(row_number() <= 16) %>% rename(value = dxy) %>% mutate(variable = "DXY") dataset8 <- dataset_total %>% filter(!is.na(foreign_participation_percent_GDP)) %>% group_by(year, develop) %>% summarise(foreign_GDP = mean(foreign_participation_percent_GDP), year = year) %>% select(c(year, foreign_GDP)) %>% distinct() %>% rename(variable = develop, value = foreign_GDP) p3 <- dataset7 %>% ggplot() + geom_line(aes(x = year, y = value, colour = variable), size = 1) + scale_color_manual(values = c("black")) + labs(x = "", y = "DXY", title = "", subtitle = "") + scale_x_continuous(limits = c(2004, 2019), seq(2004, 2019, by=2), name = "Year") + #scale_y_continuous(breaks=NULL) + theme_light() + theme(legend.title = element_blank(), axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.line.x = element_line(color = "black"), panel.border = element_blank(), plot.caption = element_blank(), axis.text.y = element_text(margin = margin(l = 8))) (p4 <- dataset8 %>% ggplot(aes(x = year, y = value, fill = variable)) + geom_col(position = "dodge") + scale_fill_manual(values = c("navyblue", "red4")) + labs(x = "Year", y = "Foreign Participation in \nSovereign Debt (% of GDP)", title = "", subtitle = "") + scale_x_continuous(limits = c(2003, 2020), seq(2004, 2019, by = 2), name = "Year") + #scale_y_continuous(breaks=NULL) + theme_light() + theme(legend.title = element_blank(), plot.title = element_blank(), axis.line.x = element_line(color = "black"), panel.border = element_blank(), plot.subtitle = element_blank(), axis.text.y = element_text(margin = margin(l = 8)))) grid.newpage() grid.draw(rbind(ggplotGrob(p3), ggplotGrob(p4), size = "last"))
c99243c954f65096e4ddcc8921b21bf586d24444
b7e84b97452dde338b7bc8f9d8e9df33168a61d1
/project/man/wrangle.TablesList.Rd
569b91539d302080b4d12078709192366639ed17
[ "MIT" ]
permissive
melissachamary/RDataWrangler
338bf153e55bc25cb954312cdab61223413a73e8
5337ae7793738c6d2bd698a5559757cb65101a10
refs/heads/master
2020-04-27T06:42:39.176883
2019-05-07T07:08:58
2019-05-07T07:08:58
173,745,360
0
0
null
null
null
null
UTF-8
R
false
true
782
rd
wrangle.TablesList.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/DataWrangle.R \name{wrangle.TablesList} \alias{wrangle.TablesList} \title{wrangle.TablesList Import data table list into R (according source_file description) and wrangle into new data table list following wrangle_parameter_file description.} \usage{ wrangle.TablesList(wrangler_parameter, table_list, call_customFunction) } \arguments{ \item{wrangle_parameter}{file of parameter data frame (see format)} \item{sources_file}{name of data frame on which foreign key constraint is checked} } \value{ list of data table } \description{ wrangle.TablesList Import data table list into R (according source_file description) and wrangle into new data table list following wrangle_parameter_file description. }
25a665f012d90ee8bf88d2282d58d94de73fe12a
45a5b0036c075cf4ecb71d0018443b1b125e1fac
/man/print.predict.ocm.Rd
084ab1f4f4bb34e540b5dceed8a627fa77fb0218
[]
no_license
SvetiStefan/ordinalCont
54a45adfc0b6638a904529e569e773a2277d4d27
fc94c4c90a71f920103f877a7d3abb0a8c77c0f8
refs/heads/master
2021-05-28T20:07:44.093122
2015-05-26T05:46:23
2015-05-26T05:46:23
null
0
0
null
null
null
null
UTF-8
R
false
false
867
rd
print.predict.ocm.Rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/ocm.methods.R \name{print.predict.ocm} \alias{print.predict.ocm} \title{Print the output of predict method} \usage{ \method{print}{predict.ocm}(x, ...) } \arguments{ \item{x}{an object of class \code{predict.ocm}} \item{...}{further arguments passed to or from other methods} } \description{ Print method for class \code{predict.ocm} } \details{ The table of predictions from \code{predict.ocm} is printed. } \examples{ ANZ0001.ocm <- ANZ0001[ANZ0001$cycleno==0 | ANZ0001$cycleno==5,] ANZ0001.ocm$cycleno[ANZ0001.ocm$cycleno==5] <- 1 fit.overall <- ocm(overall ~ cycleno + age + bsa + treatment, data=ANZ0001.ocm) pred <- predict(fit.overall) print(pred) } \author{ Maurizio Manuguerra, Gillian Heller } \seealso{ \code{\link{predict.ocm}}, \code{\link{ocm}} } \keyword{predict}
e97a560a3485fa2044fbac55b58fb294c3b6f61e
f7da4c0a8eabae8bcc23f15095cb534204d5794d
/scripts/lake_meta.r
3cc9bbbad67c24513278a243dc1d4d0fe7dbcc95
[]
no_license
calandryll/coursey_pond
9e94e8640cfedba2d68326029329408c36fc4728
a35baa50c17397e31d6a760017c8b2b123c874a4
refs/heads/master
2021-04-28T13:27:54.662225
2018-02-19T19:06:43
2018-02-19T19:06:43
122,106,407
0
0
null
null
null
null
UTF-8
R
false
false
2,039
r
lake_meta.r
source('scripts/fun.prod.new.r') coursey = read.csv("csv/CP_cleaned.csv") coursey = coursey %>% mutate(Date = ymd_hms(Date, tz = 'EST')) coursey = coursey %>% mutate(Wind_cor = WSpd * (10 / 4.5)^0.15, k600 = k.crusius.base(Wind_cor, method = 'bilinear'), K_wind = k600.2.kGAS.base(k600, Temp, gas = 'O2')) prod.ols = production(coursey, wind = 'Wind_cor', method = 'ols') prod.mle = production(coursey, wind = 'Wind_cor', method = 'mle', error.type = 'OE') prod.classic = production(coursey, wind = 'Wind_cor', method = 'classic') prod.kal = production(coursey, wind = 'Wind_cor', method = 'kalman') prod.bayes = production(coursey, wind = 'Wind_cor', method = 'bayesian') coursey.stats = coursey %>% mutate(Wind_cor = (WSpd * (10/4.5)^0.15)) %>% group_by(Date_2) %>% summarise(Avg_Temp = mean(Temp, na.rm = T), Avg_ODO = mean(ODO_mgL, na.rm = T), Avg_Sat = mean(ODO_sat, na.rm = T), Max_ODO = max(ODO_mgL), Min_ODO = min(ODO_mgL), Max_Sat = max(ODO_sat), Min_Sat = min(ODO_sat), Avg_chl = mean(Chl, na.rm = T), Avg_BGA = mean(BGA, na.rm = T), Max_PAR = max(TotPAR, na.rm = T), Avg_Per = mean(TotPrcp, na.rm = T), Avg_Wind = mean(Wind_cor, na.rm = T)) %>% mutate(Date = ymd(Date_2, tz = 'EST')) %>% select(-Date_2) prod.ols = inner_join(prod.ols, coursey.stats) prod.mle = inner_join(prod.mle, coursey.stats) prod.classic = inner_join(prod.classic, coursey.stats) prod.kal = inner_join(prod.kal, coursey.stats) prod.bayes = inner_join(prod.bayes, coursey.stats) write.csv(prod.ols, 'csv/prod_ols.csv', row.names = FALSE) write.csv(prod.mle, 'csv/prod_mle.csv', row.names = FALSE) write.csv(prod.classic, 'csv/prod_classic.csv', row.names = FALSE) write.csv(prod.kal, 'csv/prod_kalman.csv', row.names = FALSE) write.csv(prod.bayes, 'csv/prod_bayesian.csv', row.names = FALSE) write.csv(coursey, 'csv/coursey_lakemeta.csv', row.names = FALSE)
a29967e0d692bbfd5135abb7b83729a2750c2c18
6b39480379545b6a50d863f8263bb0c0a5e56cfb
/scripts/1_getting_started.R
d0aa1dbbf8bbdfe3b0038f7b89082bc9b73600b4
[]
no_license
loremarchi/hands-on-machine-learning-R-module-3
6b9dbe6aba6d871a41eb83361bb2aa9e100674b8
4077d3fd4cc84ad3dc507d66203a2ceae0e90454
refs/heads/main
2023-07-13T00:33:08.777046
2021-08-29T09:24:41
2021-08-29T09:24:41
null
0
0
null
null
null
null
UTF-8
R
false
false
715
r
1_getting_started.R
############################################## # Getting started ############################################## ## -------------------------------------------------------------------------------------------------------------------------------------------------- library(keras) x <- k_constant(c(1, 2, 3, 4, 5, 6), shape = c(3, 2)) x ## -------------------------------------------------------------------------------------------------------------------------------------------------- k_mean(x, axis = 1) k_mean(x, axis = 2) ## Your Turn! ## --------------------------------------------------------------------------------------------------------------------------------------------------
4e885f06bc322551fa1319b45232de972c58055e
38a5a35e74e487f400fccb327749a1a97e0309a8
/code/create_biccn_signac.R
365498d9d962a05482908d66b0d55aa5d72137c4
[]
no_license
timoast/signac-paper
1d0f303f20ab018aa69e8929f6a66cc110e1c81f
1cdbb6dd6a5ad817bd23bb7d65319d5bf802455f
refs/heads/master
2023-08-25T10:59:33.951761
2021-11-01T21:05:01
2021-11-01T21:05:01
309,495,686
7
3
null
null
null
null
UTF-8
R
false
false
1,453
r
create_biccn_signac.R
library(Signac) library(Seurat) library(GenomicRanges) library(future) plan("multicore", workers = 8) options(future.globals.maxSize = +Inf) annot <- readRDS("data/biccn/annotations.rds") # load metadata metadata <- read.table("data/biccn/Supplementary Table 2 - Metatable of nuclei.tsv", sep="\t", skip=1) rownames(metadata) <- metadata$V1 colnames(metadata) <- c("cell", "sample", "barcode", "logUM", "TSSe", "class", "MajorType", "SubType", "na") cells <- metadata$cell frags <- "data/biccn/fragments.bed.gz" peaks <- read.table(file = "data/biccn/unified_peaks.bed", sep = "\t", header = TRUE) peaks <- makeGRangesFromDataFrame(peaks) start.time <- Sys.time() fragments <- CreateFragmentObject( path = frags, cells = cells ) # quantify counts <- FeatureMatrix( fragments = fragments, features = peaks, cells = cells ) # create object assay <- CreateChromatinAssay(counts = counts, fragments = fragments, annotation = annot) obj <- CreateSeuratObject(counts = assay, assay = "ATAC") gc() # QC obj <- NucleosomeSignal(obj) obj <- TSSEnrichment(obj) # LSI obj <- FindTopFeatures(obj) obj <- RunTFIDF(obj) obj <- RunSVD(obj) # clustering obj <- FindNeighbors(obj, reduction = "lsi", dims = 2:100) obj <- FindClusters(obj) # UMAP obj <- RunUMAP(obj, reduction = "lsi", dims = 2:100) elapsed <- as.numeric(Sys.time() - start.time, units = "secs") writeLines(text = as.character(elapsed), con = "data/biccn/signac_total_runtime.txt")
cdf869e8520eb555d7a0c6126c5d8f298072709f
7870272b64347ed7e88f26be3d4082a9ba4c5ba6
/IJCAJ/dividetest.R
51e44eff2bb2e5afb1865a0736ddf0c901bc0d07
[]
no_license
jiahui-qin/MachineLearning
6ded04dca27f2024f0bd386fc78cd3ef1d844e3c
e80f48ca7946cd6baee3a9939099fd118b1831b2
refs/heads/master
2021-09-16T03:25:37.483320
2018-06-15T16:02:43
2018-06-15T16:02:43
104,068,207
0
0
null
null
null
null
UTF-8
R
false
false
252
r
dividetest.R
#划分测试集 #先用item_id 举例子 train_list <- fct_count(subset(train,train$context_timestamp != 6)$item_id)$f ifelse(train[which(train$context_timestamp == 6),]$item_id %in% train_list, train[which(train$context_timestamp == 6),]$item_id ,-1)
355e985731c26e8b954fb0926e646dc8ae3ebf77
bb660ae1c6194d054248ca508475493ee264a6ae
/man/near_channel_stats.Rd
e10bb2ffbf2108ac2813235ef5d48d3e7f9887c4
[ "MIT" ]
permissive
hrvg/RiverML
bdfdd6d47f2bb7a7a26c255fa4bf268b11f59c43
22b3223f31f310e00313096b7f1fb3a9ab267990
refs/heads/master
2023-04-10T05:02:17.788230
2020-10-08T16:13:21
2020-10-08T16:13:21
288,584,365
0
0
NOASSERTION
2020-12-04T01:19:50
2020-08-18T23:18:50
R
UTF-8
R
false
true
798
rd
near_channel_stats.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/tam-dm.R \name{near_channel_stats} \alias{near_channel_stats} \title{Derive near-channel statistics: "median","mean", "min", "max", "sd", "skew"} \usage{ near_channel_stats(i, .ls, .lines, .stat, bf = 100) } \arguments{ \item{i}{numeric, indice} \item{.ls}{a RasterStack of terrain analysis rasters, passed from \code{get_stats_df()}} \item{.lines}{a SpatialLinesDataFrame, passed from \code{get_stats_df()}} \item{.stat}{character, list of statistics to derive, passed from \code{get_stats_df()}} \item{bf}{numeric, size of the riparian buffer, default to 100 m} } \value{ a numeric vector of statistics } \description{ Derive near-channel statistics: "median","mean", "min", "max", "sd", "skew" } \keyword{tam-dm}
34157f936498a529391bf1d5a936f500837e0638
eb469ba06f74d3fc458b5daa94fec2a78b339bc9
/man/nysr.Rd
4091cf01298e891ec5378d392b44e3ed341b49d1
[]
no_license
cran/thickmatch
a4eb817c8c7af842826b14b12bd855dce108e41d
061dad4bca821e1a2bef6fdade4a6f94c2a0a17a
refs/heads/master
2020-07-21T23:44:36.260401
2020-04-11T12:30:02
2020-04-11T12:30:02
207,004,052
0
0
null
null
null
null
UTF-8
R
false
false
14,271
rd
nysr.Rd
\name{nysr} \alias{nysr} \docType{data} \title{ Adolescent Work Intensity and Substance Use } \description{ NYSR data on adolescent work intensity and substance Use. } \usage{data("nysr")} \format{ A data frame with 2816 observations on the following 18 variables. \describe{ \item{\code{IDS}}{NYSR identification number} \item{\code{intense}}{Based on question ``During the school year, about how many hours per week did you normally work at a paid job, or did you not have a job". ``Never": student did not have a job; ``Moderate": 1-19 hours; ``Intense": >=20 hours. } \item{\code{family.income}}{Household income with 5000 = (between 0-10,000), 15000= (between 10,000 and 20,000),..., 95000 = (between 90,000 and 100,000) and 105,000 (above 100,000).} \item{\code{family.income.impute}}{Household income with 5000 = (between 0-10,000), 15000= (between 10,000 and 20,000),..., 95000 = (between 90,000 and 100,000) and 105,000 (above 100,000). For subjects with missing family income, the mean is imputed.} \item{\code{family.income.mis}}{dummy variable for whether household income is missing and the mean is imputed.} \item{\code{family.structure}}{``Two Parent Biological": both biological father and mother living with child; ``Two Parent Nonbiological": someone assuming a mother role (biological, adoptive, stepparent) living with a husband who assumes a father role (biological, adoptive, step parent) where both parents are biological; ``Single Parent/Other": any other living situation for child. } \item{\code{highest.education.parent.in.household}}{Maximum education level of household resident who assumes a mother role (biological, adoptive, stepparent) and household resident who assumes a father role (biological, adoptive, stepparent). If the child is living with a single parent, then this is just the education level of that single parent.} \item{\code{highest.education.parent.in.household.impute}}{Maximum education level of household resident who assumes a mother role (biological, adoptive, stepparent) and household resident who assumes a father role (biological, adoptive, stepparent). If the child is living with a single parent, then this is just the education level of that single parent. For subjects with missing highest education of parent in household, the mean is imputed.} \item{\code{highest.education.parent.in.household.mis}}{Dummy variable for whether household income is missing and the mean is imputed.} \item{\code{female}}{1 = female, 0 = male} \item{\code{race.black}}{1=black race, 0=other} \item{\code{race.hispanic}}{1=hispanic race, 0=other} \item{\code{age.teenager}}{age of teenager. Age is imputed with the mean if it is missing} \item{\code{school.dropout}}{Dummy variable of whether student has dropped out of school} \item{\code{alcohol.use}}{Based on question ``How often, if at all, do you drink alcohol, such as beer, wine or mixed drinks, not including at religious services". ``Never": answered ``Never"; ``Moderate": answered ``A few times year" or ``About once a month"; ``Heavy": answered ``A few times a month", ``About once a week", ``A few times a week" or ``Almost every day". } \item{\code{marijuana.use}}{Based on question ``How often, if ever, have you used marijuana?". ``Never": answered ``Never"; ``Experimenter" answered ``You tried it once or twice"; ``Continual User": answered ``You use it occasionally" or ``You use it regularly". } \item{\code{p}}{Propensity score. } \item{\code{plogit}}{Logit of propensity score. } } } \details{ The following code constructed the data as used here. wave1data$family.income=rep(NA,nrow(wave1data)) wave1data$family.income[wave1data$PINCOME1==1 & wave1data$PINCOME2==4]=5000 wave1data$family.income[wave1data$PINCOME1==1 & wave1data$PINCOME2==3]=15000 wave1data$family.income[wave1data$PINCOME1==1 & wave1data$PINCOME2==2]=25000 wave1data$family.income[wave1data$PINCOME1==1 & wave1data$PINCOME2==1]=35000 wave1data$family.income[wave1data$PINCOME1==2 & wave1data$PINCOME3==1]=45000 wave1data$family.income[wave1data$PINCOME1==2 & wave1data$PINCOME3==2]=55000 wave1data$family.income[wave1data$PINCOME1==2 & wave1data$PINCOME3==3]=65000 wave1data$family.income[wave1data$PINCOME1==2 & wave1data$PINCOME3==4]=75000 wave1data$family.income[wave1data$PINCOME1==2 & wave1data$PINCOME3==5]=85000 wave1data$family.income[wave1data$PINCOME1==2 & wave1data$PINCOME3==6]=95000 wave1data$family.income[wave1data$PINCOME1==2 & wave1data$PINCOME3==7]=105000 # For subjects with missing family income data, fill in mean and create a missing data indicator wave1data$family.income.mis=is.na(wave1data$family.income) #wave1data$family.income[wave1data$family.income.mis==1]=mean(wave1data$family.income,na.rm=TRUE) # Find family structure variable wave1data$family.structure=rep(NA,nrow(wave1data)) # wave1data$family.structure[wave1data$PMOTHER==1 & wave1data$PLIVE==1 & wave1data$PSPRELAT==1]="Two Parent Biological" # wave1data$family.structure[wave1data$PMOTHER==1 & wave1data$PLIVE==2 & wave1data$PPARTPAR==1]="Two Parent Biological" # wave1data$family.structure[wave1data$PFATHER==1 & wave1data$PLIVE==1 & wave1data$PSPRELAT==1]="Two Parent Biological" # wave1data$family.structure[wave1data$PFATHER==1 & wave1data$PLIVE==2 & wave1data$PPARTPAR==1]="Two Parent Biological" # wave1data$family.structure[wave1data$PMOTHER==1 & (wave1data$PSPRELAT==2 | wave1data$PSPRELAT==3)]="Two Parent Nonbiological" # wave1data$family.structure[wave1data$PFATHER==1 & (wave1data$PSPRELAT==2 | wave1data$PSPRELAT==3)]="Two Parent Nonbiological" # wave1data$family.structure[(wave1data$PMOTHER==2 | wave1data$PMOTHER==3) & (wave1data$PSPRELAT==1 | wave1data$PSPRELAT==2 | wave1data$PSPRELAT==3)]="Two Parent Nonbiological" # wave1data$family.structure[(wave1data$PFATHER==2 | wave1data$PFATHER==3) & (wave1data$PSPRELAT==1 | wave1data$PSPRELAT==2 | wave1data$PSPRELAT==3)]="Two Parent Nonbiological" # wave1data$family.structure[is.na(wave1data$family.structure)]="Single Parent/Other" wave1data$family.structure[wave1data$PMOTHER==1 & wave1data$PLIVE==1 & wave1data$PSPRELAT==1]=1 wave1data$family.structure[wave1data$PMOTHER==1 & wave1data$PLIVE==2 & wave1data$PPARTPAR==1]=1 wave1data$family.structure[wave1data$PFATHER==1 & wave1data$PLIVE==1 & wave1data$PSPRELAT==1]=1 wave1data$family.structure[wave1data$PFATHER==1 & wave1data$PLIVE==2 & wave1data$PPARTPAR==1]=1 wave1data$family.structure[wave1data$PMOTHER==1 & (wave1data$PSPRELAT==2 | wave1data$PSPRELAT==3)]=1 wave1data$family.structure[wave1data$PFATHER==1 & (wave1data$PSPRELAT==2 | wave1data$PSPRELAT==3)]=1 wave1data$family.structure[(wave1data$PMOTHER==2 | wave1data$PMOTHER==3) & (wave1data$PSPRELAT==1 | wave1data$PSPRELAT==2 | wave1data$PSPRELAT==3)]=1 wave1data$family.structure[(wave1data$PFATHER==2 | wave1data$PFATHER==3) & (wave1data$PSPRELAT==1 | wave1data$PSPRELAT==2 | wave1data$PSPRELAT==3)]=1 wave1data$family.structure[is.na(wave1data$family.structure)]=0 # Highest parent education in household dadeductemp=rep(NA,nrow(wave1data)) dadeductemp[wave1data$PDADEDUC==0 | wave1data$PDADEDUC==1 | wave1data$PDADEDUC==2]=0 dadeductemp[wave1data$PDADEDUC==3 | wave1data$PDADEDUC==4 | wave1data$PDADEDUC==5 | wave1data$PDADEDUC==7]=1 dadeductemp[wave1data$PDADEDUC==6 | wave1data$PDADEDUC==8]=2 dadeductemp[wave1data$PDADEDUC==9 | wave1data$PDADEDUC==10]=3 dadeductemp[wave1data$PDADEDUC>=11 & wave1data$PDADEDUC<=14]=4 momeductemp=rep(NA,nrow(wave1data)) momeductemp[wave1data$PMOMEDUC==0 | wave1data$PMOMEDUC==1 | wave1data$PMOMEDUC==2]=0 momeductemp[wave1data$PMOMEDUC==3 | wave1data$PMOMEDUC==4 | wave1data$PMOMEDUC==5 | wave1data$PMOMEDUC==7]=1 momeductemp[wave1data$PMOMEDUC==6 | wave1data$PMOMEDUC==8]=2 momeductemp[wave1data$PMOMEDUC==9 | wave1data$PMOMEDUC==10]=3 momeductemp[wave1data$PMOMEDUC>=11 & wave1data$PMOMEDUC<=14]=4 parents.highest.educ=pmax(dadeductemp,momeductemp,na.rm=TRUE) # wave1data$highest.education.parent.in.household=rep(NA,nrow(wave1data)) # wave1data$highest.education.parent.in.household[parents.highest.educ==0]="Less than high school" # wave1data$highest.education.parent.in.household[parents.highest.educ==1]="High school degree" # wave1data$highest.education.parent.in.household[parents.highest.educ==2]="AA/vocational degree" # wave1data$highest.education.parent.in.household[parents.highest.educ==3]="BA/BS degree" # wave1data$highest.education.parent.in.household[parents.highest.educ==4]="Higher degree" # wave1data$highest.education.parent.in.household[is.na(parents.highest.educ)]="Missing" wave1data$highest.education.parent.in.household=rep(NA,nrow(wave1data)) wave1data$highest.education.parent.in.household[parents.highest.educ==0]=0 wave1data$highest.education.parent.in.household[parents.highest.educ==1]=1 wave1data$highest.education.parent.in.household[parents.highest.educ==2]=1 wave1data$highest.education.parent.in.household[parents.highest.educ==3]=2 wave1data$highest.education.parent.in.household[parents.highest.educ==4]=3 #wave1data$highest.education.parent.in.household[is.na(parents.highest.educ)]=mean(parents.highest.educ,na=T) wave1data$highest.education.parent.in.household.mis=is.na(parents.highest.educ) # Gender of teenager wave1data$gender=rep(NA,nrow(wave1data)) #wave1data$gender[wave1data$TEENSEX==0]="MALE" #wave1data$gender[wave1data$TEENSEX==1]="FEMALE" wave1data$female=wave1data$TEENSEX # Race/ethnicity of teenager wave1data$race.ethnicity=rep(NA,nrow(wave1data)) # wave1data$race.ethnicity[wave1data$TEENRACE==1]="White/Other" # wave1data$race.ethnicity[wave1data$TEENRACE==2]="African American" # wave1data$race.ethnicity[wave1data$TEENRACE==3]="Hispanic" # wave1data$race.ethnicity[wave1data$TEENRACE>=4]="White/Other" wave1data$race.black=wave1data$TEENRACE==2 wave1data$race.hispanic=wave1data$TEENRACE==3 # Age of teenager wave1data$age.teenager=wave1data$AGE wave1data$age.missing=(wave1data$AGE==888) # Fill in mean value for teenager with missing age wave1data$age.teenager[wave1data$AGE==888]=NA #wave1data$age.teenager[is.na(wave1data$age.teenager)]=mean(wave1data$age.teenager,na.rm=TRUE) # Has student dropped out of school wave1data$school.dropout=(wave1data$PSCHTYP==4) # Work intensity (intensity of adolescent employment) wave1data$work.intensity=rep(NA,nrow(wave1data)) wave1data$work.intensity[wave1data$WORKHRS==0]="Nonworker" # Intense: >=20 hours wave1data$work.intensity[wave1data$WORKHRS>=1 & wave1data$WORKHRS<20]="Moderate" wave1data$work.intensity[wave1data$WORKHRS>=20 & wave1data$WORKHRS<200]="Intense" # Alcohol use wave1data$alcohol.use=rep(NA,nrow(wave1data)) wave1data$alcohol.use[wave1data$DRINK==7]="Never" wave1data$alcohol.use[wave1data$DRINK==5 | wave1data$DRINK==6]="Moderate" wave1data$alcohol.use[wave1data$DRINK<=4]="Heavy" # Marijuana use wave1data$marijuana.use=rep(NA,nrow(wave1data)) wave1data$marijuana.use[wave1data$POT==1]="Never" wave1data$marijuana.use[wave1data$POT==2]="Experimenter" wave1data$marijuana.use[wave1data$POT==3 | wave1data$POT==4]="Continual User" ## Drop from consideration for matching fifth and sixth graders; students missing work intnsity, alcohol use and marijuana use; students with moderate working intensity wave1data$not.included.in.sample=(wave1data$PSCHGRA2==5 | wave1data$PSCHGRA2==6 | wave1data$age.missing==TRUE | is.na(wave1data$work.intensity) | is.na(wave1data$alcohol.use) | is.na(wave1data$marijuana.use) | wave1data$work.intensity=="Moderate") # Create variable which identifies whether wave 1 interview exists for subject interviewerdata=read.csv("C:/Users/ruoqi/Desktop/Penn/research/Dylan-ThickDescription/ivlink.csv") wave1interviews=interviewerdata$ids[!(interviewerdata$iver=="W3" | interviewerdata$iver=="W4")] wave1data$wave1.interview=wave1data$IDS%in%wave1interviews wave1data$wave1.interview=wave1data$wave1.interview& (!wave1data$family.income.mis) & (!wave1data$highest.education.parent.in.household.mis) data=wave1data dsub=data[which(data$not.included.in.sample==FALSE),] dim(dsub) #2816 932 dsub=dsub[which(dsub$work.intensity!='Moderate'),] dim(dsub) # 2816 932 dsub$intense=rep(0,dim(dsub)[1]) dsub$intense[which(dsub$work.intensity=='Intense')]=1 #propensity score dsub$family.income.impute=dsub$family.income dsub$family.income.impute[dsub$family.income.mis==1]=mean(dsub$family.income,na.rm=TRUE) dsub$highest.education.parent.in.household.impute=dsub$highest.education.parent.in.household dsub$highest.education.parent.in.household.impute[dsub$highest.education.parent.in.household.mis==1]=mean(dsub$highest.education.parent.in.household,na.rm=T) model<-glm(intense~family.income.impute+family.income.mis+ highest.education.parent.in.household.impute+highest.education.parent.in.household.mis+ female+race.black+race.hispanic+age.teenager+school.dropout, family=binomial(link='logit'),data=dsub,x=TRUE) x=subset(dsub[c('family.income.impute','family.income.mis','family.structure', 'highest.education.parent.in.household.impute','highest.education.parent.in.household.mis', 'female','race.black','race.hispanic','age.teenager','school.dropout')]) pred <- predict(model, newdata = x, type = 'response') dsub$p=pred dsub$plogit=car::logit(pred) #boxplot(prop~intense,data=dsub) dsub=subset(dsub[c('IDS','intense','family.income','family.income.impute','family.income.mis','family.structure', 'highest.education.parent.in.household','highest.education.parent.in.household.impute','highest.education.parent.in.household.mis', 'female','race.black','race.hispanic','age.teenager','school.dropout','alcohol.use','marijuana.use','p','plogit')]) nysr=dsub save(nysr, file = "nysr.rda") } \source{ The National Survey of Youth and Religion. } \references{ Longest, K. C. and Shanahan M. J., Adolescent Work Intensity and Substance Use: The Mediational and Moderational Roles of Parenting, Journal of Marriage and Family, Vol. 69, No. 3, pp. 703-720. } \examples{ data("nysr") summary(nysr) } \keyword{datasets}
3fcacdd933e4f58403a5e1a6c0efa60f05e8aea3
eb4883c3d4c45d719c16109f9113869059488c22
/plot2.R
97b970dfb952ee84d7991db8f19509cbf836911c
[]
no_license
maridelf/ExData_Plotting1
f2f949417385bbb56a253ba2c606e85478e46d99
3d141b798d29ea186628731710feb98ba867aa27
refs/heads/master
2021-01-23T10:34:53.847674
2017-06-01T21:08:20
2017-06-01T21:08:20
93,072,555
0
0
null
2017-06-01T15:33:18
2017-06-01T15:33:17
null
UTF-8
R
false
false
555
r
plot2.R
plot2 <- function(feb1_2 = data.frame(), readdata = TRUE) { library(dplyr) library(lubridate) source("getDataFeb1_2.R") if(readdata) {feb1_2 <- getDataFeb1_2()} with(feb1_2, plot(dt, Global_active_power, main = "", type="l", xlab = "", ylab = "Global Active Powers (kilowatts)") ) ## by default png is 480x480 px dev.copy(png, file="plot2.png") dev.off() }
678c2616a061e8fd8d62d8c28f7ea5793841c8c8
485ad4123816e24842bf7c388d084b24e772b926
/R/tif.R
9854b5e2609addefd49925d37f936fe2d662a6ea
[]
no_license
cran/cacIRT
57c446a880fb52552b231a19e666765f96260df8
8fde3135204cb26982e22ad7ca5842a5b744d3cd
refs/heads/master
2021-01-01T18:34:41.707166
2015-08-28T01:08:33
2015-08-28T01:08:33
17,694,912
0
2
null
null
null
null
UTF-8
R
false
false
230
r
tif.R
tif <- function (ip, x, D = 1.7) { i = iif(ip, x, D) if (is.null(dim(i$f))) dim(i$f) = c(length(i$x), length(i$f)) f = apply(i$f, 1, sum) r = list(x = i$x, f = f, ni = ncol(i$f)) return(r) }
d03ab76db827a6db4c789028eaa6de5a13eee5bf
83cd2dd744e10494b4461b70b8804b21b2b78341
/file2tokens.R
6eebf6cd61842b6da6168c17ceb10306cfb911f8
[ "MIT" ]
permissive
dmitrytoda/SwiftPredict
ece6ead11282ebff935656019ccf145d9c2afcfb
9693bac0dd52ce07ca23461e35d866014ee6a7d8
refs/heads/main
2023-02-12T04:26:16.378593
2021-01-08T18:03:35
2021-01-08T18:03:35
315,111,716
1
0
null
null
null
null
UTF-8
R
false
false
746
r
file2tokens.R
library(tm) file2tokens <- function (infile) { # Reads ALL lines from infile and converts to a list of # char vectors, each element of a vector representing a token con <- file(infile, 'r') text <- readLines(con) close(con) # remove empty strings (artifact of sampling) text <- text[text!=''] # A token = starts with a letter or a digit # then may have some more letters, digits, or &-'’ symbols # alternatively, acronyms like U.S. are also tokens my_tokenizer <- as.Token_Tokenizer(Regexp_Tokenizer( "[a-zA-Z0-9]+[a-zA-Z0-9&-'’]*|([a-zA-Z]\\.){2,}" )) sapply(text, my_tokenizer) }
4606d642408a9d76bcd5165f9848c015965f02b3
d5cd873bd84c6294df226984346fdf68e0f395aa
/CellChat/AnalyseCellCellCommunicationInIntestinalData.R
15585ea1661ca2fde0c51177e665a947af19581b
[]
no_license
Wenxue-PKU/scRNASeqAnalysisAndModelling
9056cb0820ea4fba15b05154083d453a8b35c865
69a249dce6862a7ab359b9570596997da61d84c3
refs/heads/master
2023-01-06T14:00:08.560215
2020-10-10T03:43:42
2020-10-10T03:43:42
null
0
0
null
null
null
null
UTF-8
R
false
false
716
r
AnalyseCellCellCommunicationInIntestinalData.R
### Application of Suoqin Jin's CellChat package to various datas on intestinal tissue (healthy and UC) # Load the relevant packages library(dplyr) library(Seurat) library(patchwork) library(ggplot2) library(CellChat) library(ggalluvial) ### Set the ligand-receptor database. Here we will use the "Secreted signalling" database for cell-cell communication (let's look at ECM-receptor in the future ) CellChatDB <- CellChatDB.mouse # The othe roption is CellChatDB.human showDatabaseCategory(CellChatDB) CellChatDB.use <- subsetDB(CellChatDB, search = "Secreted Signaling") # Other options include ECM-Receptor and Cell-Cell Contact # Unlike the wound healing data, we first need to pre-process the data in Seurat.
c9d546a3e4eb8d527c2cc57ebc954a8926754d16
c1034eb8f34b18105acf3244bf9a0b0339d6ca8d
/man/jm.prob.Rd
0d19d20ce1e950e6b2ad20f41126294cf5f37806
[ "MIT" ]
permissive
svkucheryavski/mdatools
f8d4eafbb34d57283ee753eceea1584aed6da3b9
2e3d262e8ac272c254325a0a56e067ebf02beb59
refs/heads/master
2023-08-17T16:11:14.122769
2023-08-12T16:58:49
2023-08-12T16:58:49
11,718,739
31
11
NOASSERTION
2020-07-23T18:50:22
2013-07-28T11:10:36
R
UTF-8
R
false
true
520
rd
jm.prob.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ldecomp.R \name{jm.prob} \alias{jm.prob} \title{Calculate probabilities for distance values and given parameters using Hotelling T2 distribution} \usage{ jm.prob(u, eigenvals, ncomp) } \arguments{ \item{u}{vector with distances} \item{eigenvals}{vector with eigenvalues for PCA components} \item{ncomp}{number of components} } \description{ Calculate probabilities for distance values and given parameters using Hotelling T2 distribution }
0b629146921d411a1ff2c0c676ecbf9769bd38f4
be2e286124b952221135f0ac736423b3032f0906
/dist/main.js
de702e8022a7f2270884a693fce2f52256cf2aed
[ "MIT" ]
permissive
moelders/react-windowed-select
9529ce177c3b97d489f0ad64ac9115de7890c408
ca52057ff5315f23c6b2f7ceb3b0f05fe427cf63
refs/heads/master
2023-05-14T16:07:33.515525
2021-06-02T15:04:03
2021-06-02T15:04:03
373,188,020
0
0
null
null
null
null
UTF-8
R
false
true
15,650
js
main.js
module.exports=function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=5)}([function(e,t){e.exports=require("react")},function(e,t,r){"use strict";r.d(t,"a",(function(){return i})),r.d(t,"c",(function(){return a})),r.d(t,"d",(function(){return s})),r.d(t,"b",(function(){return c})),r.d(t,"e",(function(){return u}));var n=r(0),o=function(e,t){for(var r=0,n=t.length,o=e.length;r<n;r++,o++)e[o]=t[r];return e};function i(e){return void 0!==((e=e||[])[0]||{}).options?e.reduce((function(e,t){return e+t.options.length}),0):e.length}function a(e){return e.reduce((function(e,t){var r=t.props.children,i=void 0===r?[]:r;return o(o(o([],e),[n.cloneElement(t,{type:"group"},[])]),i)}),[])}function l(e){return!0===e.props.isFocused}function s(e){return Math.max(e.findIndex(l),0)}function c(e){var t=e.groupHeadingStyles,r=e.noOptionsMsgStyles,n=e.optionStyles,o=e.loadingMsgStyles;return function(e){var i=e.props,a=i.type,l=i.children,s=i.inputValue,c=i.selectProps,u=c.noOptionsMessage,f=c.loadingMessage;if("group"===a){var d=t.height;return void 0===d?25:d}if("option"===a){var p=n.height;return void 0===p?35:p}if("function"==typeof u&&l===u({inputValue:s})){var h=r.height;return void 0===h?35:h}if("function"==typeof f&&l===f({inputValue:s})){var m=o.height;return void 0===m?35:m}return 35}}var u=function(e,t){return e+t}},function(e,t){e.exports=require("react-select")},function(e,t,r){"use strict";var n=r(1),o=r(0);function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function a(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function l(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function s(e,t){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}var c=function(e,t){var r;void 0===t&&(t=s);var n,o=[],i=!1;return function(){for(var a=[],l=0;l<arguments.length;l++)a[l]=arguments[l];return i&&r===this&&t(a,o)||(n=e.apply(this,a),i=!0,r=this,o=a),n}};var u="object"==typeof performance&&"function"==typeof performance.now?function(){return performance.now()}:function(){return Date.now()};function f(e){cancelAnimationFrame(e.id)}function d(e,t){var r=u();var n={id:requestAnimationFrame((function o(){u()-r>=t?e.call(null):n.id=requestAnimationFrame(o)}))};return n}var p=null;function h(e){if(void 0===e&&(e=!1),null===p||e){var t=document.createElement("div"),r=t.style;r.width="50px",r.height="50px",r.overflow="scroll",r.direction="rtl";var n=document.createElement("div"),o=n.style;return o.width="100px",o.height="100px",t.appendChild(n),document.body.appendChild(t),t.scrollLeft>0?p="positive-descending":(t.scrollLeft=1,p=0===t.scrollLeft?"negative":"positive-ascending"),document.body.removeChild(t),p}return p}var m=function(e,t){return e};function v(e){var t,r,n=e.getItemOffset,s=e.getEstimatedTotalSize,u=e.getItemSize,p=e.getOffsetForIndexAndAlignment,v=e.getStartIndexForOffset,y=e.getStopIndexForStartIndex,S=e.initInstanceProps,O=e.shouldResetStyleCacheOnItemSizeChange,I=e.validateProps;return r=t=function(e){function t(t){var r;return(r=e.call(this,t)||this)._instanceProps=S(r.props,l(l(r))),r._outerRef=void 0,r._resetIsScrollingTimeoutId=null,r.state={instance:l(l(r)),isScrolling:!1,scrollDirection:"forward",scrollOffset:"number"==typeof r.props.initialScrollOffset?r.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},r._callOnItemsRendered=void 0,r._callOnItemsRendered=c((function(e,t,n,o){return r.props.onItemsRendered({overscanStartIndex:e,overscanStopIndex:t,visibleStartIndex:n,visibleStopIndex:o})})),r._callOnScroll=void 0,r._callOnScroll=c((function(e,t,n){return r.props.onScroll({scrollDirection:e,scrollOffset:t,scrollUpdateWasRequested:n})})),r._getItemStyle=void 0,r._getItemStyle=function(e){var t,o=r.props,i=o.direction,a=o.itemSize,l=o.layout,s=r._getItemStyleCache(O&&a,O&&l,O&&i);if(s.hasOwnProperty(e))t=s[e];else{var c=n(r.props,e,r._instanceProps),f=u(r.props,e,r._instanceProps),d="horizontal"===i||"horizontal"===l,p="rtl"===i,h=d?c:0;s[e]=t={position:"absolute",left:p?void 0:h,right:p?h:void 0,top:d?0:c,height:d?"100%":f,width:d?f:"100%"}}return t},r._getItemStyleCache=void 0,r._getItemStyleCache=c((function(e,t,r){return{}})),r._onScrollHorizontal=function(e){var t=e.currentTarget,n=t.clientWidth,o=t.scrollLeft,i=t.scrollWidth;r.setState((function(e){if(e.scrollOffset===o)return null;var t=r.props.direction,a=o;if("rtl"===t)switch(h()){case"negative":a=-o;break;case"positive-descending":a=i-n-o}return a=Math.max(0,Math.min(a,i-n)),{isScrolling:!0,scrollDirection:e.scrollOffset<o?"forward":"backward",scrollOffset:a,scrollUpdateWasRequested:!1}}),r._resetIsScrollingDebounced)},r._onScrollVertical=function(e){var t=e.currentTarget,n=t.clientHeight,o=t.scrollHeight,i=t.scrollTop;r.setState((function(e){if(e.scrollOffset===i)return null;var t=Math.max(0,Math.min(i,o-n));return{isScrolling:!0,scrollDirection:e.scrollOffset<t?"forward":"backward",scrollOffset:t,scrollUpdateWasRequested:!1}}),r._resetIsScrollingDebounced)},r._outerRefSetter=function(e){var t=r.props.outerRef;r._outerRef=e,"function"==typeof t?t(e):null!=t&&"object"==typeof t&&t.hasOwnProperty("current")&&(t.current=e)},r._resetIsScrollingDebounced=function(){null!==r._resetIsScrollingTimeoutId&&f(r._resetIsScrollingTimeoutId),r._resetIsScrollingTimeoutId=d(r._resetIsScrolling,150)},r._resetIsScrolling=function(){r._resetIsScrollingTimeoutId=null,r.setState({isScrolling:!1},(function(){r._getItemStyleCache(-1,null)}))},r}a(t,e),t.getDerivedStateFromProps=function(e,t){return g(e,t),I(e),null};var r=t.prototype;return r.scrollTo=function(e){e=Math.max(0,e),this.setState((function(t){return t.scrollOffset===e?null:{scrollDirection:t.scrollOffset<e?"forward":"backward",scrollOffset:e,scrollUpdateWasRequested:!0}}),this._resetIsScrollingDebounced)},r.scrollToItem=function(e,t){void 0===t&&(t="auto");var r=this.props.itemCount,n=this.state.scrollOffset;e=Math.max(0,Math.min(e,r-1)),this.scrollTo(p(this.props,e,t,n,this._instanceProps))},r.componentDidMount=function(){var e=this.props,t=e.direction,r=e.initialScrollOffset,n=e.layout;if("number"==typeof r&&null!=this._outerRef){var o=this._outerRef;"horizontal"===t||"horizontal"===n?o.scrollLeft=r:o.scrollTop=r}this._callPropsCallbacks()},r.componentDidUpdate=function(){var e=this.props,t=e.direction,r=e.layout,n=this.state,o=n.scrollOffset;if(n.scrollUpdateWasRequested&&null!=this._outerRef){var i=this._outerRef;if("horizontal"===t||"horizontal"===r)if("rtl"===t)switch(h()){case"negative":i.scrollLeft=-o;break;case"positive-ascending":i.scrollLeft=o;break;default:var a=i.clientWidth,l=i.scrollWidth;i.scrollLeft=l-a-o}else i.scrollLeft=o;else i.scrollTop=o}this._callPropsCallbacks()},r.componentWillUnmount=function(){null!==this._resetIsScrollingTimeoutId&&f(this._resetIsScrollingTimeoutId)},r.render=function(){var e=this.props,t=e.children,r=e.className,n=e.direction,a=e.height,l=e.innerRef,c=e.innerElementType,u=e.innerTagName,f=e.itemCount,d=e.itemData,p=e.itemKey,h=void 0===p?m:p,v=e.layout,g=e.outerElementType,y=e.outerTagName,S=e.style,O=e.useIsScrolling,I=e.width,b=this.state.isScrolling,_="horizontal"===n||"horizontal"===v,M=_?this._onScrollHorizontal:this._onScrollVertical,x=this._getRangeToRender(),w=x[0],R=x[1],P=[];if(f>0)for(var z=w;z<=R;z++)P.push(Object(o.createElement)(t,{data:d,key:h(z,d),index:z,isScrolling:O?b:void 0,style:this._getItemStyle(z)}));var T=s(this.props,this._instanceProps);return Object(o.createElement)(g||y||"div",{className:r,onScroll:M,ref:this._outerRefSetter,style:i({position:"relative",height:a,width:I,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:n},S)},Object(o.createElement)(c||u||"div",{children:P,ref:l,style:{height:_?"100%":T,pointerEvents:b?"none":void 0,width:_?T:"100%"}}))},r._callPropsCallbacks=function(){if("function"==typeof this.props.onItemsRendered&&this.props.itemCount>0){var e=this._getRangeToRender(),t=e[0],r=e[1],n=e[2],o=e[3];this._callOnItemsRendered(t,r,n,o)}if("function"==typeof this.props.onScroll){var i=this.state,a=i.scrollDirection,l=i.scrollOffset,s=i.scrollUpdateWasRequested;this._callOnScroll(a,l,s)}},r._getRangeToRender=function(){var e=this.props,t=e.itemCount,r=e.overscanCount,n=this.state,o=n.isScrolling,i=n.scrollDirection,a=n.scrollOffset;if(0===t)return[0,0,0,0];var l=v(this.props,a,this._instanceProps),s=y(this.props,l,a,this._instanceProps),c=o&&"backward"!==i?1:Math.max(1,r),u=o&&"forward"!==i?1:Math.max(1,r);return[Math.max(0,l-c),Math.max(0,Math.min(t-1,s+u)),l,s]},t}(o.PureComponent),t.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},r}var g=function(e,t){e.children,e.direction,e.height,e.layout,e.innerTagName,e.outerTagName,e.width,t.instance},y=function(e,t,r){var n=e.itemSize,o=r.itemMetadataMap,i=r.lastMeasuredIndex;if(t>i){var a=0;if(i>=0){var l=o[i];a=l.offset+l.size}for(var s=i+1;s<=t;s++){var c=n(s);o[s]={offset:a,size:c},a+=c}r.lastMeasuredIndex=t}return o[t]},S=function(e,t,r,n,o){for(;n<=r;){var i=n+Math.floor((r-n)/2),a=y(e,i,t).offset;if(a===o)return i;a<o?n=i+1:a>o&&(r=i-1)}return n>0?n-1:0},O=function(e,t,r,n){for(var o=e.itemCount,i=1;r<o&&y(e,r,t).offset<n;)r+=i,i*=2;return S(e,t,Math.min(r,o-1),Math.floor(r/2),n)},I=function(e,t){var r=e.itemCount,n=t.itemMetadataMap,o=t.estimatedItemSize,i=t.lastMeasuredIndex,a=0;if(i>=r&&(i=r-1),i>=0){var l=n[i];a=l.offset+l.size}return a+(r-i-1)*o},b=v({getItemOffset:function(e,t,r){return y(e,t,r).offset},getItemSize:function(e,t,r){return r.itemMetadataMap[t].size},getEstimatedTotalSize:I,getOffsetForIndexAndAlignment:function(e,t,r,n,o){var i=e.direction,a=e.height,l=e.layout,s=e.width,c="horizontal"===i||"horizontal"===l?s:a,u=y(e,t,o),f=I(e,o),d=Math.max(0,Math.min(f-c,u.offset)),p=Math.max(0,u.offset-c+u.size);switch("smart"===r&&(r=n>=p-c&&n<=d+c?"auto":"center"),r){case"start":return d;case"end":return p;case"center":return Math.round(p+(d-p)/2);case"auto":default:return n>=p&&n<=d?n:n<p?p:d}},getStartIndexForOffset:function(e,t,r){return function(e,t,r){var n=t.itemMetadataMap,o=t.lastMeasuredIndex;return(o>0?n[o].offset:0)>=r?S(e,t,o,0,r):O(e,t,Math.max(0,o),r)}(e,r,t)},getStopIndexForStartIndex:function(e,t,r,n){for(var o=e.direction,i=e.height,a=e.itemCount,l=e.layout,s=e.width,c="horizontal"===o||"horizontal"===l?s:i,u=y(e,t,n),f=r+c,d=u.offset+u.size,p=t;p<a-1&&d<f;)p++,d+=y(e,p,n).size;return p},initInstanceProps:function(e,t){var r={itemMetadataMap:{},estimatedItemSize:e.estimatedItemSize||50,lastMeasuredIndex:-1};return t.resetAfterIndex=function(e,n){void 0===n&&(n=!0),r.lastMeasuredIndex=Math.min(r.lastMeasuredIndex,e-1),t._getItemStyleCache(-1),n&&t.forceUpdate()},r},shouldResetStyleCacheOnItemSizeChange:!1,validateProps:function(e){e.itemSize}});var _=function(){return(_=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)},M=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r};function x(e){var t=e.data,r=e.index,n=e.setMeasuredHeight,i=(e.height,o.useRef(null));return o.useLayoutEffect((function(){if(i.current){var e=i.current.getBoundingClientRect().height;n({index:r,measuredHeight:e})}}),[i.current]),o.createElement("div",{key:"option-"+r,ref:i},t)}t.a=function(e){var t=o.useMemo((function(){var t=o.Children.toArray(e.children),r=t[0]||{};if(o.isValidElement(r)){var i=r.props,a=(void 0===i?{}:i).data,l=(void 0===a?{}:a).options,s=(void 0===l?[]:l).length>0,c=s&&Object(n.c)(t);return s?c:t}return[]}),[e.children]),r=e.getStyles,i=r("groupHeading",e),a=r("loadingMessage",e),l=r("noOptionsMessage",e),s=r("option",e),c=Object(n.b)({groupHeadingStyles:i,noOptionsMsgStyles:l,optionStyles:s,loadingMsgStyles:a}),u=o.useMemo((function(){return t.map(c)}),[t]),f=o.useMemo((function(){return Object(n.d)(t)}),[t]),d=t.length,p=r("menuList",e),h=p.maxHeight,m=p.paddingBottom,v=void 0===m?0:m,g=p.paddingTop,y=void 0===g?0:g,S=M(p,["maxHeight","paddingBottom","paddingTop"]),O=o.useMemo((function(){return u.reduce(n.e,0)}),[u]),I=O+v+y,w=Math.min(h,I),R=Math.floor(O/d),P=e.innerRef,z=e.selectProps||{},T=z.classNamePrefix,j=z.isMulti,C=o.useRef(null),E=o.useRef({});o.useEffect((function(){E.current={}}),[e.children]);var D=function(e){var t,r=e.index,n=e.measuredHeight;E.current[r]&&E.current[r]===n||(E.current=_(_({},E.current),((t={})[r]=n,t)),C.current&&C.current.resetAfterIndex(r))};return o.useEffect((function(){f>=0&&null!==C.current&&C.current.scrollToItem(f)}),[f,t,C]),o.createElement(b,{className:T?T+"__menu-list"+(j?" "+T+"__menu-list--is-multi":""):"",style:S,ref:C,outerRef:P,estimatedItemSize:R,innerElementType:o.forwardRef((function(e,t){var r=e.style,n=M(e,["style"]);return o.createElement("div",_({ref:t,style:_(_({},r),{height:parseFloat(r.height)+v+y+"px"})},n))})),height:w,width:"100%",itemCount:d,itemData:t,itemSize:function(e){return E.current[e]||u[e]}},(function(e){var t=e.data,r=e.index,n=e.style;return o.createElement("div",{style:_(_({},n),{top:parseFloat(n.top.toString())+y+"px"})},o.createElement(x,{data:t[r],index:r,setMeasuredHeight:D,height:u[r]}))}))}},function(e,t,r){"use strict";var n=r(3),o=r(0),i=r(2),a=r.n(i),l=r(1),s=function(){return(s=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)},c=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r};t.a=o.forwardRef((function(e,t){var r=e.windowThreshold,i=void 0===r?100:r,u=c(e,["windowThreshold"]),f=o.useMemo((function(){return Object(l.a)(u.options)}),[u.options])>=i;return o.createElement(a.a,s({},u,{components:s(s({},u.components),f?{MenuList:n.a}:{}),ref:t}))}))},function(e,t,r){"use strict";r.r(t);var n=r(4),o=r(2);for(var i in o)["default","WindowedMenuList"].indexOf(i)<0&&function(e){r.d(t,e,(function(){return o[e]}))}(i);var a=r(3);r.d(t,"WindowedMenuList",(function(){return a.a})),t.default=n.a}]);
6d52c1d40090e7e2bb8c9efdad66750417587f39
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/gasper/R/GVN.R
416e22e407722ebd6ead7588d845b502a9f3c7cf
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
R
false
false
864
r
GVN.R
#' Graph Von Neumann Estimator. #' #' Graph equivalent of the Von Neummann variance estimator. #' #' @export GVN #' @param y Noisy data. #' @param A Adjacency matrix. #' @param L Laplacian matrix. #' @examples #' data(minnesota) #' A <- minnesota$A #' L <- laplacian_mat(A) #' x <- minnesota$xy[ ,1] #' n <- length(x) #' f <- sin(x) #' sigma <- 0.1 #' noise <- rnorm(n, sd = sigma) #' y <- f + noise #' sigma^2 #' GVN(y, A, L) #' @references #' von Neumann, J. (1941). Distribution of the ratio of the mean square successive difference to the variance. \emph{Ann. Math. Statistics}, 35(3), 433--451. #' #' de Loynes, B., Navarro, F., Olivier, B. (2019). Data-driven Thresholding in Denoising with Spectral Graph Wavelet Transform. arXiv preprint arXiv:1906.01882. GVN <- function(y, A, L) { sig <- 0.5 * sum(A * outer(y, y, "-")^2)/sum(diag(L)) return(sig) }
dd8df6c4d5742a2146b7416cfdaca749da281e55
4697a51bdf1a57dae9559774b2b20624257881bf
/lib/helpers.R
df36bb2ae31486a36bb32410f0b1e310c143eeeb
[]
no_license
Castdeath97/future-learn-analysis
f24eaf5f10e7c8ab25f6191a3886843a9aee4f44
1f3508d0ec97faa6df0a5f1b4b84c521ea05fa2a
refs/heads/master
2021-10-26T17:32:06.990862
2021-10-07T13:17:40
2021-10-07T13:17:40
156,971,824
0
0
null
null
null
null
UTF-8
R
false
false
4,966
r
helpers.R
## @knitr archetypes-clean idIndex = 1 responseIndex = 3 archetypesClean = function(df){ # Remove fields that won't be used (id, responded_at) df = df[-responseIndex] df = df[-idIndex] # fix id format df$learner_id = as.character(df$learner_id) return(df) } ## @knitr questions-clean clozeIndex = 8 qTypeIndex = 3 questionsClean = function(df){ # Remove empty cloze response field df = df[-clozeIndex] # Remove question type field (doesn't change) df = df[-qTypeIndex] # Remove redudant quiz_number field df = df[-stepFieldIndex] # Remove rows with id empty fields df = drop_na(df, learner_id) # fix date format df$submitted_at = as.Date(df$submitted_at) # fix 'correct' field format df$correct = as.logical(df$correct) # fix id format df$learner_id = as.character(df$learner_id) return(df) } ## @knitr steps-clean stepFieldIndex = 2 stepsClean = function(df){ # Remove redudant step field df = df[-2] # Replace empty strings with NA to stop date formatting issues df$last_completed_at[df$last_completed_at == ''] = NA # fix date format df$first_visited_at = as.Date(df$first_visited_at) df$last_completed_at = as.Date(df$last_completed_at) # fix id format df$learner_id = as.character(df$learner_id) return(df) } ## @knitr enrol-clean otherFieldsIndexes = 2:12 enrolClean = function(df){ # Remove unimportant fields df = df[-otherFieldsIndexes] # Replace '--' with NA with not detected df$detected_country = factor(df$detected_country, levels=c(levels(df$detected_country), 'Not Detected')) df$detected_country[as.character(df$detected_country) == '--'] = 'Not Detected' # Drop unused levels (-- dropped) df = droplevels(df) # fix id format df$learner_id = as.character(df$learner_id) return(df) } ## @knitr generic-agg # aggregate function used to aggregate both tables # takes function to carry aggregation by week on a field agg = function(df, func){ # add fields for completed steps/marks in all weeks df = left_join(func(df, 1), func(df, 2), by = 'learner_id') %>% left_join(., func(df, 3), by = 'learner_id') # replace any NAs (dropped off) with 0s df[is.na(df)] = 0 return(df) } ## @knitr steps-agg # steps aggregate just calls the general aggregates and passes # the function it needs to aggregate steps comppleted by week stepsAgg = function(df){ agg(df, stepsWeekComp) } # function used to aggregate amount of steps completed each week (not na) stepsWeekComp = function(df, week){ # subset and aggregate (count completed (not NA)) weekDf = subset(df, week_number == week) comps = aggregate(weekDf$last_completed_at, list(learner_id= weekDf$learner_id), function(x) sum(!is.na(x))) # rename default x for completed tasks colnames(comps) = c(colnames(comps)[1], paste('week', week, '_completed_steps', sep = '')) return(comps) } ## @knitr questions-agg # question aggregate just calls the general aggregates and passes # the function it needs to aggregate marks (# of correct questions) by week # and number of tries questionsAgg = function(df){ agg(df, questionWeekMarks) } # function used to aggregate amount of marks (# of correct questions) # earned each week (not na) and attempts questionWeekMarks = function(df, week){ # subset and aggregate (count marks by summing (1 is true) and length for attempts) weekDf = subset(df, week_number == week) marks = aggregate(weekDf$correct, list(learner_id= weekDf$learner_id), function(x) c(sum = sum(x), n = length(x))) # unpack the vector x and rename marks[paste('week', week, '_total_marks', sep = '')] = marks[,2][,1] marks[paste('week', week, '_total_attempts', sep = '')] = marks[,2][,2] # remove vector and top row marks = marks[-2] marks = marks[-1,] return(marks) } ## @knitr merge1 mergeDfs = function(archetypesDf,questionsAggDf, stepsAggDf){ # join by learner id progressByArchetypeDf = left_join(stepsAggDf, questionsAggDf, by = 'learner_id') # replace nas with 0 for incompleted items progressByArchetypeDf[is.na(progressByArchetypeDf)] = 0 # join by learner id for last df progressByArchetypeDf = left_join(progressByArchetypeDf, archetypesDf, by = 'learner_id') # remove NAs for archetype by replacing with unspecified progressByArchetypeDf$archetype = fct_explicit_na(progressByArchetypeDf$archetype, 'Unspecified') return(progressByArchetypeDf) } ## @knitr merge2 countryMergeDfs = function(progressByArchetypeDf, countryDf){ # join by learner id progressByArchetypeDf = left_join(progressByArchetypeDf, countryDf, by = 'learner_id') # Remove rows with empty fields (single user) progressByArchetypeDf = drop_na(progressByArchetypeDf) return(progressByArchetypeDf) }
f7a6e2412e0f1c4844100ce20bebd53c0c611a58
2f18e19c490e350fc4a0f93579dfb8fffa2813f9
/SuddenlyExpandingPopulation/Simulated_densities_of_T_Total.R
67e46b2f841faf09b28a1490208ebbbfd649e469
[]
no_license
JetteS/Inhomogeneous_phase-type_distributions_in_population_genetics-
276f574506a1f78558b3a7a095b7a9ee5a7168fe
ce38663bc84b9e5f618beb9c4a26a30f27cdd979
refs/heads/main
2023-02-16T18:20:51.427009
2021-01-09T16:50:21
2021-01-09T16:50:21
313,293,604
0
0
null
null
null
null
UTF-8
R
false
false
7,533
r
Simulated_densities_of_T_Total.R
## Creating plots of the simulated density of T_Total ## under a suddenly expanding population growth model ################################################## ## Simulating the time to the most recent ## common ancestor and the total branch length ## under a model with variable population size ################################################## ## Name : simT ## ## Author: Jette Steinbach ## ## Purpose : Simulating the time to the most ## recent common ancestor and the total ## branch length. ## ## Input: ## - n : a natural number representing the sample ## size. Must be greater than one. ## Defaults to 10. ## - out : One of the following ## - 'all' ## - 'htimes' ## - 'wtimes' ## For further information see Output below. ## - LambdaInv: A function that ## represents the inverse of the ## integrated intensity ## g^{-1}(t) = int_0^t lambda(u) du. ## - ... Arguments for the function LambdaInv ## ## Output: ## - A vector holding the following numbers: ## - If out = 'all', the vector includes the ## holding times T_2,...,T_n as well as the ## time to the most recent common ancestor ## and the total branch length. That is: ## res = (T_2,...,T_n, T_MRCA, T_Total). ## - If out = 'htimes' the vector includes the ## holding times T_2,...,T_n. That is: ## res = (T_2,...,T_n). ## - If out = 'wtimes' the vector holds the ## time to the most recent common ancestor ## and the total branch length. That is: ## res = (T_MRCA, T_Total). simT <- function(n=10, out, LambdaInv,...){ ## Checking whether n is a positive natural number: if(n <=1 | abs(n - round(n)) > .Machine$double.eps^0.5) stop("The sample size must be a natural number greater than 1.") ## Checking whether out is one of 'all','htimes' and 'wtimes'. if(sum(out==c('all','htimes','wtimes'))==0) stop("out must be either 'all', 'htimes' or 'wtimes.") ## For a sample size of n=2, all vectors are simply numbers if(n==2){ ## Generating one independent and identically distributed random variable ## having the uniform distribution on (0,1): U <- runif(n=1) ## Defining the vector holding the single waiting time T_2 Tvec <- -log(U) ## In this case, s_2 = t_2 and hence, ## t_2^v = Lambda^(-1)(t_2) TVvec <- LambdaInv(Tvec,...) }else{ ## For a sample of size n>2, all parts are vectors ## Generating independent and identically distributed random variables ## having the uniform distribution on (0,1): U <- runif(n=(n-1)) ## Defining the vector holding the waiting times ## generated by t_j = -2*log(U_j)/(j*(j-1)) for j=2,3,...,n Tvec <- -2*log(U)/((2:n)*(1:(n-1))) names(Tvec) <- paste0("T_",2:n) ## Forming s_n = t_n and s_j = t_n +...+ t_j for j=2,3,...,n-1 Svec <- cumsum(rev(Tvec)) names(Svec) <- paste0("S_",n:2) ## Computing t_n^v = Lambda^(-1)(s_n) ## and t_j^v = Lambda^(-1)(s_j)- Lambda^(-1)(s_(j+1)) ## for j=2,3,...,n-1 TVvec <- LambdaInv(Svec,...) - c(0,LambdaInv(Svec,...)[-(n-1)]) } if(out=="all"){ res <- c(rev(TVvec), sum(TVvec), sum((n:2)*TVvec)) names(res) <- c(paste0("T_",2:n),"T_MRCA","T_Total") }else if(out == "htimes"){ res <- rev(TVvec) names(res) <- paste0("T_",2:n) }else{ res <- c(sum(TVvec), sum((n:2)*TVvec)) names(res) <- c("T_MRCA","T_Total") } return(res) } ################################################## ## Suddenly expanding population ################################################## ################################################## ## The inverse of the integrated intensity under ## a model with a suddenly expanding population ################################################## ## Name : LambdaInvSEP ## ## Author: Jette Steinbach ## ## Purpose : Compute the value of the inverse of ## the integrated intensity ## Lambda(t) = int_0^t lambda(u) du. ## ## Input: ## - t : a vector holding the time points measured ## in units of N generations at which ## the function should be evaluated. ## - a : a number between 0 and 1 that represents ## the factor by which the population size ## decreases. ## - b : The generation scaled in units of N ## generations where the expansion occurred. ## Output: ## - The value(s) of the the inverse of the integrated ## intensity evaluated at the point(s) (in) t. LambdaInvSEP <- function(t, a, b){ ## Checking whether t is a positive real vector if(sum(t <= 0)>0) stop("All time points in t must be positive real numbers.") ## Checking whether a is a real number between 0 and 1 if(a <= 0) stop("The factor a must be strictly positive.") if(a > 1) stop("The factor a must be less than or equal to one.") ## Checking whether b is a positive real number if(b <= 0) stop("b must be a positive real number.") ## Defining the vector holding the results res <- replicate(n=length(t), NA) ## Computing the inverse of the integrated intensity ## for all values of t for (i in 1:length(t)) { res[i] <- ifelse(t[i] <= b, t[i], a*t[i]-a*b+b) } return(res) } ################################################## ## Plotting the simulated density of the total ## branch length under a model with a suddenly ## expanding population size ################################################## ## Name : plot_simfTotal ## ## Author: Jette Steinbach ## ## Purpose : Plotting the simulated probability ## density function of the total branch ## length under a model with a suddenly ## expanding population size. ## ## Input: ## - n : a natural number representing the ## sample size. Must be greater ## than one. ## - a : a number between 0 and 1 that represents ## the factor by which the population size ## decreases. Defaults to 1. ## - b : A real number that represents the ## generation scaled in units of N ## generations where the expansions occurred. ## Output: ## - A ggplot of the simulated probability density ## function of the total branch length. ## ## Remark: Requires the package gglplot2 plot_simfTotal <- function(n, a, b){ ## Simulating the waiting time T_Total once Dx <- data.frame(TTotal = simT(n=n, out = 'wtimes', LambdaInv = LambdaInvSEP, a=a, b=b)[2]) ## and 10000 times more for(i in 1:10000){ Dx <- rbind(Dx, simT(n=n, out = 'wtimes', LambdaInv = LambdaInvSEP, a=a, b=b)[2]) } ## Creating a simple ggplot p <- ggplot(Dx, aes(x=TTotal)) + ggtitle(expression(paste("Probability density function for ", tau["Total"])), subtitle=paste("n =",n,", b =",b, "and a =", a)) + xlab("x") + ylab(expression(paste(f[tau["Total"]], "(x)"))) + theme_minimal() + geom_density(color = "red") + geom_histogram(aes(y=..density..), bins = 60, alpha=0.5) + ylim(0,1) + xlim(0,15) print(p) } ## Plotting the simulated density for n=2,5,10,15 and a=b=1 plot_simfTotal(n=2,a=1,b=1) plot_simfTotal(n=5,a=1,b=1) plot_simfTotal(n=10,a=1,b=1) plot_simfTotal(n=15,a=1,b=1) ## plotting the simulated density for n=2,10, a=0.2,0.8 and b=1,3. plot_simfTotal(n=2,a=0.2,b=1) plot_simfTotal(n=10,a=0.2,b=1) plot_simfTotal(n=2,a=0.2,b=3) plot_simfTotal(n=10,a=0.2,b=3) plot_simfTotal(n=2,a=0.8,b=1) plot_simfTotal(n=10,a=0.8,b=1) plot_simfTotal(n=2,a=0.8,b=3) plot_simfTotal(n=10,a=0.8,b=3)
0668cffc350c5d1d3527bcb45ff6f0ff61e546f5
570e3adb41c325d7b3357b27fb39c7ea2b346f60
/Plot1.R
b721a06f5342b4b44afc3987991ae0b4ab9430ac
[]
no_license
kathy0305/ExData_Project1
89e79a75d0b9b82616108f3917d0d50d0fd5a7ac
f9bf09e94c3be4f55dd310f92a86b4b445d75e02
refs/heads/master
2020-12-31T04:17:40.199973
2016-05-13T19:13:26
2016-05-13T19:13:26
58,765,762
0
0
null
null
null
null
UTF-8
R
false
false
2,182
r
Plot1.R
## Assignment: Course Project 1 ## Plot1.R ## Checking if the file has laready been downloaded, if it hasn't then create a directory if(!file.exists('Week1Project.zip')){ dir.create('Week1Project') ## extracting data set from website fileUrl<-"http://archive.ics.uci.edu/ml/machine-learning-databases/00235/household_power_consumption.zip" download.file(fileUrl,destfile = "./Week1Project/Data.zip") } setwd("./DataScientist/expData/Week1Project")##set working directory unzippedData <-unzip("Data.zip")##unzip file list.files()## double check to see if the file did indeed download and unzipped ## keep track of when the data got downloaded dateDownLoaded <- date() dateDownLoaded ## read only data needed (DN=DataNeeded) ## using function 'grep' which searches for matches to argument pattern ## also replace missing values from symbol ? to NA DN <- read.table(text = grep("^[1,2]/2/2007", readLines(unzippedData), value = TRUE),na.strings = "?", sep = ";", header = FALSE) head(DN) ## get an idea of what the data looks like ##Renaming Columns (it looks like grep is not reading the headers correctly) names(DN) <- c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity", "Sub_metering_1", "Sub_metering_2", "Sub_metering_3") ## check to see if only the 1/2/2007 and 2/2/2007 got subsetted table(DN$Date) ## Assignment asking to use 'strptime()' function to format Data and Time ##You may find it useful to convert the Date and Time variables to Date/Time classes ## in R using the strptime() and as.Date() functions. ## Combine the Date and Time in one column and format ## ?strptime DN$DateTime <- strptime(paste(DN$Date, DN$Time, sep=" "), format="%d/%m/%Y %H:%M:%S") # Open png graphic device png("plot1.png", width=480, height=480) ## Using Base hist function ## fill color red ## x-axis label "Global Active Power (kilowatts)" ## default y-axes label 'frequency' ## Main title "Global Active Power" hist(DN$Global_active_power, col = "red", main = "Global Active Power", xlab = "Global Active Power (kilowatts)") # Turn off png graphic device dev.off()
c872bd9829746f81a7a9e8a52b918b2b1130a80a
5027d65a10985981f7e275b0c9da8e68329b87b5
/scripts/plot_PS.R
7084b3459180980d575cb1d30f2cfd2084ffe348
[]
no_license
DPCscience/GenomicPrediction_2018
3f52a7247dd4153591d327d2ff52ea94841434b1
507bf5e8ddad6dccec56b6e73910a52017772e79
refs/heads/master
2021-09-10T21:40:55.990635
2018-04-02T18:37:57
2018-04-02T18:37:57
null
0
0
null
null
null
null
UTF-8
R
false
false
1,203
r
plot_PS.R
### Comparison of model performace across the Grid Search ids <- c('rice_DP_Spindel','sorgh_DP_Fernan','soy_NAM_xavier','spruce_Dial_beaulieu','swgrs_DP_Lipka') setwd('/Volumes/azodichr/03_GenomicSelection/') cls <- c(ID="character", MSE="numeric",Model="character",Trait="character",params="character") data <- read.csv('parameter_search_results.csv', colClasses=cls, stringsAsFactors=FALSE) data$MSE <- abs(data$MSE) # Aggregate by parameter/model data_ag <- aggregate(MSE ~ ID + Model + Trait + params, data, mean) # Remove weird strings in parameter lines data_ag <- separate(data_ag, params, c("Feat1", "Feat2", 'Feat3', 'Feat4'), ",", fill='right') data_ag <- as.data.frame(lapply(data_ag, gsub, pattern = "\\'[A-z]+\\'\\:", replacement = "")) data_ag <- as.data.frame(lapply(data_ag, gsub, pattern = "\\{", replacement = "")) data_ag <- as.data.frame(lapply(data_ag, gsub, pattern = "}", replacement = "")) data_ag <- as.data.frame(lapply(data_ag, gsub, pattern = " ", replacement = "")) library(ggplot2) ggplot(data_ag, aes(Feat1, Feat2)) + geom_tile(aes(fill=as.numeric(MSE)), colour='white') + #scale_fill_gradient(limits=c(0,0.5), low='white',high='firebrick')+ theme_minimal(10)
7c36ac38c98d39e6381278fadaada1c51947feeb
563c6cb8816345083ec54fffef8e10148d3642e9
/run_analysis.R
feb507ce04b6e69a91c9239dfd77baf7b4694eaa
[]
no_license
rtomasc/GettingCleaningCourseProject
fddda9541ab3da11a801979888fce24f5de3fa78
d70da385cdcd3a75b4568ccc30fbf4c1fa815e32
refs/heads/master
2021-01-10T04:29:10.104014
2015-12-27T23:02:50
2015-12-27T23:02:50
46,667,885
0
0
null
null
null
null
UTF-8
R
false
false
5,779
r
run_analysis.R
#PART 0. Downloading the zip file, loading libraries and getting data FileUrl<-"https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" download.file(FileUrl, destfile="Dataset.zip") downloaded<-date() # Look at the file names in Dataset.zip. Get the file names to extract them. unzip("Dataset.zip", files=NULL,list=TRUE ) unzip("Dataset.zip", files="UCI HAR Dataset/test/X_test.txt") unzip("Dataset.zip", files="UCI HAR Dataset/train/X_train.txt") unzip("Dataset.zip", files="UCI HAR Dataset/test/Y_test.txt") unzip("Dataset.zip", files="UCI HAR Dataset/train/Y_train.txt") unzip("Dataset.zip", files="UCI HAR Dataset/activity_labels.txt") unzip("Dataset.zip", files="UCI HAR Dataset/test/subject_test.txt") unzip("Dataset.zip", files="UCI HAR Dataset/features.txt") unzip("Dataset.zip", files="UCI HAR Dataset/train/subject_train.txt") #Loading libraries library(data.table) library(dplyr) #Reading variable names for features(measurements) and activity labels featureNames <- read.table("UCI HAR Dataset/features.txt") activityLabels <- read.table("UCI HAR Dataset/activity_labels.txt", header = FALSE) #Reading 2 datasets: train (21 subjects) and test (9 subjects). #Each dataset is splitted into subject, activity and features (measurements), same length each #Reading train data subjectTrain <- read.table("UCI HAR Dataset/train/subject_train.txt", header = FALSE) activityTrain <- read.table("UCI HAR Dataset/train/y_train.txt", header = FALSE) featuresTrain <- read.table("UCI HAR Dataset/train/X_train.txt", header = FALSE) #Read test data subjectTest <- read.table("UCI HAR Dataset/test/subject_test.txt", header = FALSE) activityTest <- read.table("UCI HAR Dataset/test/y_test.txt", header = FALSE) featuresTest <- read.table("UCI HAR Dataset/test/X_test.txt", header = FALSE) #PART 1 - Merge the training and the test sets to create one data set for each: subject, activity and features #Get featureNames as column names for features, and adding the 3 datasets in one dataset (completeData) subject <- rbind(subjectTrain, subjectTest) activity <- rbind(activityTrain, activityTest) features <- rbind(featuresTrain, featuresTest) #Name the column names from the features file in variable featureNames colnames(features) <- t(featureNames[2]) #Add activity and subject as a column to features colnames(activity) <- "Activity" colnames(subject) <- "Subject" completeData <- cbind(features,activity,subject) #PART 2 - Extracts only the column numbers of the mean or std of each measurement("mean" and "std" in variable names). #Adds Activity and Subject columns columnsWithMeanSTD <- grep(".*Mean.*|.*Std.*", names(completeData), ignore.case=TRUE) #Look at the number of variables in completeData dim(completeData) #building a vector with the required columns numbers, adding Activity and Subject columns (the last 2 columns) requiredColumns <- c(columnsWithMeanSTD, 562, 563) #extracting the required columns extractedData <- completeData[,requiredColumns] #Look at the number of variables in extractedData dim(extractedData) #PART 3 - Renaming variable Activity with activity names from activityLabels dataset (6 activities) extractedData$Activity <- as.character(extractedData$Activity) for (i in 1:6){ extractedData$Activity[extractedData$Activity == i] <- as.character(activityLabels[i,2]) } #Set the activity variable in the data as a factor extractedData$Activity <- as.factor(extractedData$Activity) #PART 4 - Appropriately labelling the data set with more descriptive variable names. #Look at variable names names(extractedData) #Acc to be replaced with Accelerometer #Gyro to be replaced with Gyroscope #BodyBody to be replaced with Body #Mag to be replaced with Magnitude #Character 'f' to be replaced with Frequency #Character 't' to be replaced with Time #-mean() to be replaced with Mean #-std() to be replaced with STD #-freq() to be replaced with Frequency #-angle to be replaced with Angle #gravity to be replaced with Gravity names(extractedData)<-gsub("Acc", "Accelerometer", names(extractedData)) names(extractedData)<-gsub("Gyro", "Gyroscope", names(extractedData)) names(extractedData)<-gsub("BodyBody", "Body", names(extractedData)) names(extractedData)<-gsub("Mag", "Magnitude", names(extractedData)) names(extractedData)<-gsub("^t", "Time", names(extractedData)) names(extractedData)<-gsub("^f", "Frequency", names(extractedData)) names(extractedData)<-gsub("tBody", "TimeBody", names(extractedData)) names(extractedData)<-gsub("-mean()", "Mean", names(extractedData), ignore.case = TRUE) names(extractedData)<-gsub("-std()", "STD", names(extractedData), ignore.case = TRUE) names(extractedData)<-gsub("-freq()", "Frequency", names(extractedData), ignore.case = TRUE) names(extractedData)<-gsub("angle", "Angle", names(extractedData)) names(extractedData)<-gsub("gravity", "Gravity", names(extractedData)) #Look at new resulting variable names names(extractedData) #PART 5 - From the data set in step 4, creates a second, independent tidy data set with the average of #each variable for each activity and each subject. #Set the subject variable in the data as a factor. Activity is already a factor (PART 3) extractedData$Subject <- as.factor(extractedData$Subject) extractedData <- data.table(extractedData) #Create tidyData as a set with average for each activity and subject tidyData <- aggregate(. ~Subject + Activity, extractedData, mean) #Order tidayData according to subject and activity tidyData <- tidyData[order(tidyData$Subject,tidyData$Activity),] #Writing tidyData into a text file write.table(tidyData, file = "Tidy.txt", row.names = FALSE) #Making a txt with variable names. to be used in the CodeBook write.table(tidyData_variables, file = "CodeBook.txt", row.names = FALSE)
5de1eb315522ba5a1fa36a1e1f3328b45bf9e61b
29585dff702209dd446c0ab52ceea046c58e384e
/ParamHelpers/R/OptPath_getter.R
1e6eec00950b480f8758232d7fd0363d09e4b392
[]
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
8,250
r
OptPath_getter.R
#' Get the length of the optimization path. #' #' Dependent parameters whose requirements are not satisfied are represented by a scalar #' NA in the output. #' #' @template arg_op #' @return [\code{integer(1)}] #' @export #' @family optpath getOptPathLength = function(op) { UseMethod("getOptPathLength") } #' Get an element from the optimization path. #' #' Dependent parameters whose requirements are not satisfied are represented by a scalar NA #' in the elements of \code{x} of the return value. #' #' @template arg_op #' @param index [\code{integer(1)}]\cr #' Index of element. #' @return List with elements \code{x} [named \code{list}], \code{y} [named \code{numeric}], #' \code{dob} [\code{integer(1)}], \code{eol} [\code{integer(1)}]. #' The elements \code{error.message} [\code{character(1)}], #' \code{exec.time} [\code{numeric(1)}] and \code{extra} [named \code{list}] are #' there if the respective options in \code{\link{OptPath}} are enabled. #' @rdname getOptPathEl #' @export #' @family optpath getOptPathEl = function(op, index) { UseMethod("getOptPathEl") } #' Get data.frame of input points (X-space) referring to the param set from the optimization path. #' #' @template arg_op #' @template arg_opgetter_dob #' @template arg_opgetter_eol #' @return [\code{data.frame}]. #' @export #' @family optpath getOptPathX = function(op, dob, eol) { UseMethod("getOptPathX") } #' Get y-vector or y-matrix from the optimization path. #' #' @template arg_op #' @param names [\code{character}]\cr #' Names of performance measure. #' Default is all performance measures in path. #' @template arg_opgetter_dob #' @template arg_opgetter_eol #' @param drop [\code{logical(1)}]\cr #' Return vector instead of matrix when only one y-column was selected? #' Default is \code{TRUE}. #' @return [\code{numeric} | \code{matrix}]. The columns of the matrix are always named. #' @export #' @family optpath getOptPathY = function(op, names, dob, eol, drop = TRUE) { UseMethod("getOptPathY") } #' Get date-of-birth vector from the optimization path. #' #' @template arg_op #' @template arg_opgetter_dob #' @template arg_opgetter_eol #' @return [\code{integer}]. #' @export #' @family optpath getOptPathDOB = function(op, dob, eol) { UseMethod("getOptPathDOB") } #' Get end-of-life vector from the optimization path. #' #' @template arg_op #' @template arg_opgetter_dob #' @template arg_opgetter_eol #' @return [\code{integer}]. #' @export #' @family optpath getOptPathEOL = function(op, dob, eol) { UseMethod("getOptPathEOL") } #' Get error-message vector from the optimization path. #' #' @template arg_op #' @template arg_opgetter_dob #' @template arg_opgetter_eol #' @return [\code{character}]. #' @export #' @family optpath getOptPathErrorMessages = function(op, dob, eol) { UseMethod("getOptPathErrorMessages") } #' Get exec-time vector from the optimization path. #' #' @template arg_op #' @template arg_opgetter_dob #' @template arg_opgetter_eol #' @return [\code{numeric}]. #' @export #' @family optpath getOptPathExecTimes = function(op, dob, eol) { UseMethod("getOptPathExecTimes") } #' Get column from the optimization path. #' #' @template arg_op #' @param name [\code{character(1)}]\cr #' Name of the column. #' @template arg_opgetter_dob #' @template arg_opgetter_eol #' @return Single column as a vector. #' @export #' @family optpath getOptPathCol = function(op, name, dob, eol) { UseMethod("getOptPathCol") } #' Get columns from the optimization path. #' #' @template arg_op #' @param names [\code{character}]\cr #' Names of the columns. #' @template arg_opgetter_dob #' @template arg_opgetter_eol #' @inheritParams as.data.frame.OptPathDF #' @return [\code{data.frame}]. #' @export #' @family optpath getOptPathCols = function(op, names, dob, eol, row.names = NULL) { UseMethod("getOptPathCols") } #' Get index of the best element from optimization path. #' #' @template arg_op #' @param y.name [\code{character(1)}]\cr #' Name of target value to decide which element is best. #' Default is \code{y.names[1]}. #' @template arg_opgetter_dob #' @template arg_opgetter_eol #' @param ties [\code{character(1)}]\cr #' How should ties be broken when more than one optimal element is found? #' \dQuote{all}: return all indices, #' \dQuote{first}: return first optimal element in path, #' \dQuote{last}: return last optimal element in path, #' \dQuote{random}: return random optimal element in path. #' Default is \dQuote{last}. #' @return [\code{integer}] #' Index or indices into path. See \code{ties}. #' @export #' @family optpath #' @examples #' ps = makeParamSet(makeNumericParam("x")) #' op = makeOptPathDF(par.set = ps, y.names = "y", minimize = TRUE) #' addOptPathEl(op, x = list(x = 1), y = 5) #' addOptPathEl(op, x = list(x = 2), y = 3) #' addOptPathEl(op, x = list(x = 3), y = 9) #' addOptPathEl(op, x = list(x = 4), y = 3) #' as.data.frame(op) #' getOptPathBestIndex(op) #' getOptPathBestIndex(op, ties = "first") getOptPathBestIndex = function(op, y.name = op$y.names[1], dob = op$env$dob, eol = op$env$eol, ties = "last") { assertClass(op, "OptPath") assertChoice(y.name, choices = op$y.names) dob = asInteger(dob, any.missing = TRUE) eol = asInteger(eol, any.missing = TRUE) assertChoice(ties, c("all", "first", "last", "random")) life.inds = which(op$env$dob %in% dob & op$env$eol %in% eol) if (length(life.inds) == 0) stop("No element found which matches dob and eol restrictions!") y = getOptPathY(op, y.name)[life.inds] if (all(is.na(y))) { best.inds = life.inds } else { if (op$minimize[y.name]) best.inds = which(min(y, na.rm = TRUE) == y) else best.inds = which(max(y, na.rm = TRUE) == y) best.inds = life.inds[best.inds] } if (length(best.inds) > 1) { if (ties == "all") return(best.inds) else if (ties == "first") return(best.inds[1]) else if (ties == "last") return(best.inds[length(best.inds)]) else if (ties == "random") return(best.inds[sample(length(best.inds), 1)]) } else { return(best.inds) } } #' Get indices of pareto front of optimization path. #' #' @template arg_op #' @param y.names [\code{character}]\cr #' Names of performance measures to construct pareto front for. #' Default is all performance measures. #' @template arg_opgetter_dob #' @template arg_opgetter_eol #' @param index [\code{logical(1)}]\cr #' Return indices into path of front or y-matrix of nondominated points? #' Default is \code{FALSE}. #' @return [\code{matrix} | \code{integer}]. Either matrix (with named columns) of points of front #' in objective space or indices into path for front. #' @export #' @family optpath #' @examples #' ps = makeParamSet(makeNumericParam("x")) #' op = makeOptPathDF(par.set = ps, y.names = c("y1", "y2"), minimize = c(TRUE, TRUE)) #' addOptPathEl(op, x = list(x = 1), y = c(5, 3)) #' addOptPathEl(op, x = list(x = 2), y = c(2, 4)) #' addOptPathEl(op, x = list(x = 3), y = c(9, 4)) #' addOptPathEl(op, x = list(x = 4), y = c(4, 9)) #' as.data.frame(op) #' getOptPathParetoFront(op) #' getOptPathParetoFront(op, index = TRUE) getOptPathParetoFront = function(op, y.names = op$y.names, dob = op$env$dob, eol = op$env$eol, index = FALSE) { assertClass(op, "OptPath") assertCharacter(y.names, min.len = 2) assertSubset(y.names, op$y.names, empty.ok = FALSE) dob = asInteger(dob, any.missing = TRUE) eol = asInteger(eol, any.missing = TRUE) assertFlag(index, na.ok = TRUE) requirePackages("emoa", default.method = "load") life.inds = which(op$env$dob %in% dob & op$env$eol %in% eol) if (length(life.inds) == 0) stop("No element found which matches dob and eol restrictions!") y = getOptPathY(op, y.names, drop = FALSE)[life.inds, , drop = FALSE] # multiply columns with -1 if maximize k = ifelse(op$minimize, 1, -1) y2 = t(y) * k # is_dominated has kind of buggy behavoiur if y2 is a row # (it hinks, we have a 1-dimensional optimization prob und returns the min index) # so we have to treat this case manually if (nrow(y2) == 1) nondom = 1 else nondom = which(!emoa::is_dominated(y2)) if (index) return(life.inds[nondom]) else return(y[nondom, , drop = FALSE]) }
a965be02387d68721ca7be86329bd3f425f15834
c944ff7ec610960d106391311ceb27869c979741
/station_density_walking.R
e3f5e09cba87b1a9c64c7aa6d579cc79a51f27e2
[]
no_license
sjrodahl/BDA17-Bike-Share-Analysis
924686722d4528ef2ced7ba6c646f60225791b3a
4f53c7c9be3023ce69dafbbc056f5727379c0d51
refs/heads/master
2021-01-20T12:44:53.686341
2017-06-13T05:33:58
2017-06-13T05:33:58
90,402,869
0
0
null
2017-06-13T05:33:59
2017-05-05T17:56:15
R
UTF-8
R
false
false
1,789
r
station_density_walking.R
#Station density - stations closer than a five minute walk to the next one setwd("D:/Sondre/Dokumenter/UCSD/IRGN452 BigDataAnalytics/Project/BDA17-Bike-Share-Analysis/") stations <- read.csv("data/station.csv" , stringsAsFactors=FALSE) distance.matrix<-read.csv('gmapsWalkTimeMatrix.csv') distance.matrix[distance.matrix==0] <- 10000 limit = 300 columnMins <- apply(distance.matrix, 2, min) min.df <- as.data.frame(columnMins) min.df <- min.df[-c(1,2),,drop=FALSE] row.names(min.df) <- substr(rownames(min.df), 6, nchar(rownames(min.df))) #Remove "Time." from rownames min.df$columnMins <- as.numeric(as.character(min.df$columnMins)) min.df$close<- min.df$columnMins< limit st_coords_split <- strsplit(rownames(min.df), "[.][.]") # Split coordinates #Only need latitude to uniqely match with station min.df$lat <- lapply(st_coords_split, `[[`, 1) min.df.mergeable <- min.df[c("lat", "close", "columnMins")] stations <- merge(stations, min.df.mergeable, by="lat") #-------Plot lat<-c(47.58, 47.68) lon<-c(-122.25, -122.38) seattle_impr<-get_map(location = c(lon = mean(lon), lat = mean(lat)), zoom = 13, maptype = "satellite", source = "google") map_fromPoints<-ggmap(seattle_impr) + geom_point(data = stations, aes(x = long,y = lat, color = ifelse(columnMins<=300, "green", ifelse(columnMins<=600, "yellow", "red"))), size=5) + labs(title = "Stations and their walking distance to nearest neighbor\n", color = "Nearest neighboring station is:\n")+ scale_color_manual(labels = c("<= 5 minutes away", "> 10 minutes away"," > 5 minutes away"), values=c("green" ,"red", "yellow"))+ theme(axis.title = element_text(size=18), axis.text = element_text(size=14, face="bold"), title = element_text(size=22), legend.text = element_text(size=14)) map_fromPoints
03f8fd923e23343a9174ec1d9964780dbbad1a98
b2f61fde194bfcb362b2266da124138efd27d867
/code/dcnf-ankit-optimized/Results/QBFLIB-2018/A1/Database/Cashmore-Fox-Giunchiglia/Planning-CTE/pipesnotankage04_6/pipesnotankage04_6.R
b4fd2e50e7deea7b984e4c994c586a9ee893fe7d
[]
no_license
arey0pushpa/dcnf-autarky
e95fddba85c035e8b229f5fe9ac540b692a4d5c0
a6c9a52236af11d7f7e165a4b25b32c538da1c98
refs/heads/master
2021-06-09T00:56:32.937250
2021-02-19T15:15:23
2021-02-19T15:15:23
136,440,042
0
0
null
null
null
null
UTF-8
R
false
false
69
r
pipesnotankage04_6.R
c17a968585a5d9c0c35855d2b0671a55 pipesnotankage04_6.qdimacs 839 21727
e63e4ae47da8de1a00c6a4713d4b59adf3c93175
79f9f86aa6cc9fdee3aa152c326a08b08c4b9533
/man/prefs_reset_to_defaults.Rd
377d1a33c0585dcc9ecf151e375ef7484f4f694f
[]
no_license
charliejhadley/rstudioprefswitcher
bb888a96e6fb7ec51834dc2e8a3fde26f5264cca
ee10a3f3cbc2665e1a15be2270cff0a9c3af1239
refs/heads/master
2023-04-13T16:06:35.066160
2021-04-16T09:38:06
2021-04-16T09:38:06
331,698,487
2
0
null
null
null
null
UTF-8
R
false
true
472
rd
prefs_reset_to_defaults.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/set_prefs.R \name{prefs_reset_to_defaults} \alias{prefs_reset_to_defaults} \title{Restore default preferences} \usage{ prefs_reset_to_defaults(improve_code_reproducibility = TRUE) } \description{ \code{prefs_reset_to_defaults()} resets RStudio preferences to defaults. You are \strong{strongly} recommend to run \code{prefs_improve_reproducibility()} after running prefs_reset_to_defaults(). }
957dbc7fa0fbf2c48601a29c8e57b0f8e69360d3
9279ca3701e7a6ae465c3e482f8deae70fb2daa5
/variableDistributions_WK3.R
25bf0363ee05171d32c6fccc711778c11515f83d
[]
no_license
zliu008/dataManageVisualization
4fb16ba88b54c251338d70e6b505f0c008ad8a56
89716bc0801fdedb9649b677d6d011bcf253a92e
refs/heads/master
2021-01-10T01:51:05.014230
2015-10-23T00:09:26
2015-10-23T00:09:26
43,625,093
0
0
null
null
null
null
UTF-8
R
false
false
4,099
r
variableDistributions_WK3.R
rm(list=ls(all=TRUE)) #function to calculate distribution caculateDist <- function(data_in, varName) { freq <- data.frame(table((data_in), exclude = NULL)); colnames(freq)[1] = varName; freq$Perc <- freq$Freq/sum(freq$Freq); print(sprintf("the distribution of %s:", varName)); print(freq); freq; } nesar_pds <- read.csv('nesarc_pds.csv'); age_group <-rep('middle', dim(nesar_pds)[1]); age_group[nesar_pds[,'AGE'] < 30] <- 'young'; age_group[nesar_pds[,'AGE'] >= 60] <- 'old'; freq_agegroup <- caculateDist(age_group, 'AgeGroup'); #recode NA, this NA is not a missing data nesar_pds$S4AQ55[is.na(nesar_pds$S4AQ55)] <- 0; #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ55[nesar_pds$S4AQ55 == 9] <- NA; #recode NA, this NA is not a missing data nesar_pds$S4AQ56[is.na(nesar_pds$S4AQ56)] <- 0; #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ56[nesar_pds$S4AQ56 == 9] <- NA; #recode NA, this NA is not a missing data nesar_pds$S4AQ57[is.na(nesar_pds$S4AQ57)] <- 0; #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ57[nesar_pds$S4AQ57 == 9] <- NA; # NA is missing data #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ4A8[nesar_pds$S4AQ4A8 == 9] <- NA; # NA is missing data #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ4A6[nesar_pds$S4AQ4A6 == 9] <- NA; # NA is missing data #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ4A5[nesar_pds$S4AQ4A5 == 9] <- NA; # NA is missing data #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ4A9[nesar_pds$S4AQ4A9 == 9] <- NA; # NA is missing data #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ4A14[nesar_pds$S4AQ4A14 == 9] <- NA; # NA is missing data #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ4A15[nesar_pds$S4AQ4A15 == 9] <- NA; #recode NA, this NA is not a missing data nesar_pds$S4AQ51[is.na(nesar_pds$S4AQ51)] <- 0; #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ51[nesar_pds$S4AQ51 == 9] <- NA; #recode number 9, it is unknow, which is missing data nesar_pds$S4BQ1[nesar_pds$S4BQ1 == 9] <- NA; #recode number 9, it is unknow, which is missing data nesar_pds$S4BQ2[nesar_pds$S4BQ2 == 9] <- NA; #NA is missing data, NA in S4AQ6A meaning no major depression #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ6A[nesar_pds$S4AQ6A == 99] <- NA; #NA is missing data, NA in S4AQ7 meaning no major depression #recode number 9, it is unknow, which is missing data nesar_pds$S4AQ7[nesar_pds$S4AQ7 == 99] <- NA; ##caculate distribution percentage freq_S4AQ1 <- caculateDist(nesar_pds[,'S4AQ1'], 'S4AQ1'); freq_S4AQ2 <- caculateDist(nesar_pds[,'S4AQ2'], 'S4AQ2'); freq_S4AQ56 <- caculateDist(nesar_pds[,'S4AQ56'], 'S4AQ56'); freq_S4AQ57 <- caculateDist(nesar_pds[,'S4AQ57'], 'S4AQ57'); freq_S4AQ55 <- caculateDist(nesar_pds[,'S4AQ55'], 'S4AQ55'); freq_S4AQ54 <- caculateDist(nesar_pds[,'S4AQ54'], 'S4AQ54'); freq_S4AQ4A8 <- caculateDist(nesar_pds[,'S4AQ4A8'], 'S4AQ4A8'); freq_S4AQ4A6 <- caculateDist(nesar_pds[,'S4AQ4A6'], 'S4AQ4A6'); freq_S4AQ4A5 <- caculateDist(nesar_pds[,'S4AQ4A5'], 'S4AQ4A5'); freq_S4AQ4A9 <- caculateDist(nesar_pds[,'S4AQ4A9'], 'S4AQ4A9'); freq_S4AQ4A14 <- caculateDist(nesar_pds[,'S4AQ4A14'], 'S4AQ4A14'); freq_S4AQ4A15 <- caculateDist(nesar_pds[,'S4AQ4A15'], 'S4AQ4A15'); freq_S4AQ51 <- caculateDist(nesar_pds[,'S4AQ51'], 'S4AQ51'); freq_S4BQ1 <- caculateDist(nesar_pds[,'S4BQ1'], 'S4BQ1'); freq_S4BQ2 <- caculateDist(nesar_pds[,'S4BQ2'], 'S4BQ2'); nesar_pds$S4AQ6A_GRP <-rep('middle', dim(nesar_pds)[1]); nesar_pds$S4AQ6A_GRP[nesar_pds[,'S4AQ6A'] < 30] <- 'young'; nesar_pds$S4AQ6A_GRP[nesar_pds[,'S4AQ6A'] >= 60] <- 'old'; freq_S4AQ6A <- caculateDist(nesar_pds[,'S4AQ6A_GRP'], 'S4AQ6A_GRP'); #group number of epsode nesar_pds$S4AQ7_GRP[nesar_pds$S4AQ7 < 5] <- 'Low'; nesar_pds$S4AQ7_GRP[nesar_pds$S4AQ7 >= 5 & nesar_pds$S4AQ7 < 20] <- 'Moderate'; nesar_pds$S4AQ7_GRP[nesar_pds$S4AQ7 >= 20] <- 'High'; freq_S4AQ7 <- caculateDist(nesar_pds[,'S4AQ7_GRP'], 'S4AQ7_GRP');
be321676a1c3a7ae5b3650615f65f75b7d05e960
2f66f60715bf67758d1f93b650886500b04ed431
/man/cyan2yellow.Rd
76cf2e3b11a40e4ac9f363867cc7fc4d6127384a
[]
no_license
SymbolixAU/colourvalues
6e2e32b29c3ce2a0a0699e36e86cb6dc77ccf5db
dfc75685389ebcfcbac15dccbbd0c024c2854117
refs/heads/master
2023-04-11T13:42:57.481895
2023-04-08T22:43:28
2023-04-08T22:43:28
147,190,723
34
9
null
2022-12-30T02:33:38
2018-09-03T10:44:56
C++
UTF-8
R
false
true
226
rd
cyan2yellow.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/palettes.R \name{cyan2yellow} \alias{cyan2yellow} \title{Cyan2yellow} \usage{ cyan2yellow() } \description{ Data Frame of the cyan2yellow palette }
1be1ecaf861f1c44e7c27e6dd9d002d56641ca92
e462ad72e1db20ece2432b27e266a8dee927bf7f
/讨论班/分位数回归/ADMMRQ.r
880e4303ce3212e27decf82504f53677e9018453
[]
no_license
dujiangbjut/dujiangbjut.github.io
1c4ca37dd8f9b7c0d63cff600a679f2ba2a13ee8
6a9ce1bebd054023bd6e4c431f2bdf291093569c
refs/heads/master
2020-04-19T10:18:32.461941
2019-09-07T14:12:03
2019-09-07T14:12:03
168,131,265
0
0
null
null
null
null
UTF-8
R
false
false
1,066
r
ADMMRQ.r
ADMMRQ <- function(X,y,tau,iter=200,esp=1e-03){ n=length(y) e.new=e.old=rep(0,n) X=as.matrix(X) p=ncol(X) beta.new=beta.old=rep(0,p) u.new=u.old=rep(0,n) step=0 error=1 while(step<iter&error>esp){ beta.old=beta.new e.old=e.new u.old=u.new step=step+1 c=y-X%*%beta.old+u.old/1.2 c1=c-(2*tau-1)/1.2 e.new=pmax(c1-1/1.2,0)-pmax(-c1-1/1.2,0) beta.new=solve(t(X)%*%X)%*%t(X)%*%(y-e.new+u.old/1.2) temp=y-e.new-X%*%beta.new u.new=u.old+temp*1.2 temp1=y-e.new-X%*%beta.new temp2=1.2*t(X)%*%(e.new-e.old) error1=max(sqrt(sum((X%*%beta.new)^2)),sqrt(sum(e.new^2)),sqrt(sum(y^2))) error2=sqrt(p)*0.01+esp*sqrt(sum((X%*%beta.new)^2)) if(sqrt(sum(temp1^2))<sqrt(n)*0.01+esp*error1&sqrt(sum(temp2^2))<error2) step=iter+1 error=sqrt(sum((beta.new-beta.old)^2)) } e.hat=y-X%*%beta.new loss=sum(e.hat*(tau-1*(e.hat<0))) tmp.out = list(beta.hat=beta.new, loss=loss,ind=step) return(tmp.out) }
8111ebac8eb6a8fae9f0c41aa1b19681fc356059
62cfdb440c9f81b63514c9e545add414dc4d5f63
/man/qat_plot_roc_rule_dynamic_2d.Rd
de0569163f6d029d860bf68c1ac4bd436f44cdc8
[]
no_license
cran/qat
7155052a40947f6e45ba216e8fd64a9da2926be4
92975a7e642997eac7b514210423eba2e099680c
refs/heads/master
2020-04-15T16:53:45.041112
2016-07-24T01:26:59
2016-07-24T01:26:59
17,698,828
0
0
null
null
null
null
UTF-8
R
false
false
2,700
rd
qat_plot_roc_rule_dynamic_2d.Rd
\name{qat_plot_roc_rule_dynamic_2d} \alias{qat_plot_roc_rule_dynamic_2d} %- Also NEED an '\alias' for EACH other topic documented here. \title{Plot a dynamic ROC rule result} \description{ A plot of the result of a dynamic ROC rule check will be produced. } \usage{ qat_plot_roc_rule_dynamic_2d(flagvector, filename, measurement_vector = NULL, max_upward_vector = NULL, max_downward_vector = NULL, upward_vector_name = NULL, downward_vector_name = NULL, measurement_name = "", directoryname = "", plotstyle = NULL) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{flagvector}{The resulting flagvector of qat\_analyse\_roc\_rule\_dynamic\_2d} \item{filename}{Name of the file without extension.} \item{measurement_vector}{The measurement vector, which should be plotted} \item{max_upward_vector}{The vector (2d array) with the upward values.} \item{max_downward_vector}{The vector (2d array) with the downward values.} \item{upward_vector_name}{Name of the vector of the upward values. } \item{downward_vector_name}{Name of the vector of the downward values. } \item{measurement_name}{Name of the measurement.} \item{directoryname}{Directory, where the resulted file should be stored.} \item{plotstyle}{A list with a qat color scheme.} } \details{ A plot will be produced, which base on the resulting flagvector of qat\_analyse\_roc\_rule\_dynamic\_2d. Additional information on the parameters, which were used while performing the test, will be added to the plot. When no plotstyle is defined the standard-colorscheme will be used. The resulting plot will be stored in the folder, which is defined by directory under the given filename, with the extension png. } \value{ No return value. } \author{Andre Duesterhus} \seealso{\code{\link{qat_plot_roc_rule_dynamic_1d}}, \code{\link{qat_analyse_roc_rule_dynamic_2d}}, \code{\link{qat_plot_roc_rule_static_2d}}} \examples{ vec <- array(rnorm(500), c(25,20)) min_vector <- array(rnorm(500)+2, c(25,20)) max_vector <- array(rnorm(500)+2, c(25,20)) result <- qat_analyse_roc_rule_dynamic_2d(vec, min_vector, max_vector, upward_vector_name="upward vector", downward_vector_name="downward vector") # this example produce a file exampleplot_roc_dyn.png in the current directory qat_plot_roc_rule_dynamic_2d(result$flagvector, "exampleplot_roc_dyn", measurement_vector=vec, max_upward_vector=result$max_upward_vector, max_downward_vector=result$max_downward_vector, upward_vector_name=result$upward_vector_name, downward_vector_name=result$downward_vector_name, measurement_name="Result of Check") } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ts}
c698dd575392abe5da295a989a4c965a26faa256
382df78024f588acea08039a0b0a9e24f297b6a3
/r/math/Pi.R
9c351ab133daaa8d23ff33c150cd852013cde2f9
[]
no_license
id774/sandbox
c365e013654790bfa3cda137b0a64d009866d19b
aef67399893988628e0a18d53e71e2038992b158
refs/heads/master
2023-08-03T05:04:20.111543
2023-07-31T14:01:55
2023-07-31T14:01:55
863,038
4
1
null
2020-03-05T06:18:03
2010-08-26T01:05:11
TeX
UTF-8
R
false
false
64
r
Pi.R
s <- 10000000 x <- runif(s) y <- runif(s) sum(x^2+y^2 <= 1)*4/s
c2caf6918238f15fda90158a45d7682db05142af
51fb651cdd636bf2b0f08c77ab6aa9d1341920a3
/R/ahn_gen.R
c64149fd73acb4ca50195bb77ee6aa32c1a25fad
[]
no_license
ecopeng/AnimalHabitatNetwork
4ee45cce56c298d5b47d926c932a3ca41e464a12
ff4fc3a80477a222742222b1c5615b5db4b2699a
refs/heads/master
2023-02-03T03:49:42.038460
2020-12-22T10:20:51
2020-12-22T10:20:51
272,998,264
0
0
null
null
null
null
UTF-8
R
false
false
5,296
r
ahn_gen.R
#' @title Generate networks characterising habitat physical configurations #' @description Generate undirected networks (weighted or unweighted, connected or disconnected) characterising the physical attributes and spatial organizations (or distributions) of habitat components (i.e. habitat configurations). #' #' @param N The number of nodes #' @param L A side length of the rectangle landscape within which nodes are anchored #' @param mu the critical \code{Dij} (i.e. Euclidean distance between node \code{i} and \code{j}) at which the link removing probability curve \code{P(Dij, mu, lamda)} transits from concave to convex (see \code{\link{ahn_prob}}) #' @param lamda the steepness of the link removing probability curve \code{P(Dij, mu, lamda)}, see \code{\link{ahn_prob}} #' @param Connected \code{TRUE} for connected while \code{FALSE} ignores whether the networks are connected or not #' @param Weighted \code{TRUE} for weighted while \code{FALSE} for unweighted networks #' @param eta mediates the weight, i.e. \code{(Dij)^-eta}, of the link rewiring node \code{i} from one network component and node \code{j} from another network component (\code{i} and \code{j} are with an Euclidean distance of \code{Dij}) when the network becomes disconnected after removing links from the initial complete network with the probability \code{P(Dij, mu, lamda) = [1 + exp(-lamda(Dij - mu))]^-1} when both \code{Connected = TRUE} and \code{Weighted = TRUE} #' @param A The area of the rectangle landscape within which the network is defined #' @param X A vector of \code{X} coordinates for the \code{N} nodes (sampled from \code{[0, L]} uniformly at random if \code{NULL}) #' @param Y A vector of \code{Y} coordinates for the \code{N} nodes (sampled from \code{[0, A/L]} uniformly at random if \code{NULL}) #' @param U A vector with \code{N} elements specifying node attributes (qualitative or quantitive), by default \code{NULL} #' @param V A vector with \code{N} elements specifying node attributes (qualitative or quantitive), by default \code{NULL} #' #' @importFrom stats runif dist rnorm #' @import igraph #' @export #' @return Return an animal habitat network (an \code{igraph} object) #' @examples #' # generate a connected and weighted network #' ahn_gen(N = 10, L = 5, mu = 1, lamda = 5) #' #'\donttest{ #' #' N <- 10 #' x <- runif(N, 0, 5) #' ql <- sample(LETTERS, N, replace = TRUE) #' qn <- sample(1:20, N, replace = TRUE) #' #' # specify the X coordinates, node attributes U and V for a connected and unweighted network #' ahn_gen(N, L = 5, mu = 1, lamda = 5, Weighted = FALSE, X = x, U = ql, V = qn) #' #' # specify the Y coordinates, node attributes U and V for a weighted network, no matter if the #' # network will be connected or not #' ahn_gen(N, L = 5, mu = 1, lamda = 5, Weighted = TRUE, Connected = FALSE, Y = x, U = ql, V = qn) #' #'} #' ahn_gen <- function(N, L, mu, lamda, Connected = TRUE, Weighted = TRUE, eta = 1, A = 25, X = NULL, Y = NULL, U = NULL, V = NULL){ ifelse(is.null(X), x <- runif(N, 0, L), ifelse(max(X) > L || min(X) < 0 || length(X) != N, stop('Wrong X coordinate(s)!'), x <- X)) ifelse(is.null(Y), y <- runif(N, 0, A/L), ifelse(max(Y) > A/L || min(Y) < 0 || length(Y) != N, stop('Wrong Y coordinate(s)!'), y <- Y)) xy_coords <- data.frame(x = x, y = y) dm <- as.matrix(dist(xy_coords), method = 'euclidean', diag = FALSE) dm_0 <- 1/dm dm_0[is.infinite(dm_0)] <- 0 ahn_wei_matrix <- dm_0 ahn_wei_matrix[lower.tri(ahn_wei_matrix, diag = TRUE)] <- NA tr <- which(!is.na(ahn_wei_matrix)) prob <- 1/(1 + exp(-lamda*(dm[tr] - mu))) for(u in 1:length(tr)){ if(sample(c(1, 0), size = 1, prob = c(prob[u], 1 - prob[u]))){ ahn_wei_matrix[tr][u] <- 0 } } ahn_wei_matrix[lower.tri(ahn_wei_matrix)] <- t(ahn_wei_matrix)[lower.tri(ahn_wei_matrix)] if(Weighted){ ahn <- graph_from_adjacency_matrix(ahn_wei_matrix, mode = 'undirected', diag = FALSE, weighted = TRUE) } else{ ahn_wei_matrix[ahn_wei_matrix > 0] <- 1 ahn <- graph_from_adjacency_matrix(ahn_wei_matrix, mode = 'undirected', diag = FALSE, weighted = NULL) } if(!is.connected(ahn) && Connected){ memb <- unname(components(ahn)$membership) ncomp <- max(memb) while(ncomp > 1){ r_memb <- sample(memb, 1) temp <- dm_0[which(memb == r_memb), which(memb != r_memb), drop = FALSE] rn <- as.numeric(rownames(temp)[which(temp == max(temp), arr.ind = T)[1]]) cn <- as.numeric(colnames(temp)[which(temp == max(temp), arr.ind = T)[2]]) if(Weighted){ ahn_wei_matrix[rn, cn] <- (dm_0[rn, cn])^eta ahn_wei_matrix[cn, rn] <- (dm_0[rn, cn])^eta ahn <- graph_from_adjacency_matrix(ahn_wei_matrix, mode = 'undirected', diag = FALSE, weighted = TRUE) } else{ ahn_wei_matrix[rn, cn] <- 1 ahn_wei_matrix[cn, rn] <- 1 ahn_wei_matrix[ahn_wei_matrix > 0] <- 1 ahn <- graph_from_adjacency_matrix(ahn_wei_matrix, mode = 'undirected', diag = FALSE, weighted = NULL) } memb <- unname(components(ahn)$membership) ncomp <- max(memb) } } if(!is.null(U)){vertex_attr(ahn, name = 'U') <- U} if(!is.null(V)){vertex_attr(ahn, name = 'V') <- V} vertex_attr(ahn, name = 'X') <- xy_coords$x vertex_attr(ahn, name = 'Y') <- xy_coords$y return(ahn) }
473919ffbcd2258f11093304ff4b9cb9883814b3
95bb91fd4c03527735c4eb4ac273f17ace035042
/R/formatting.R
bb6c9392dfb8f351aeeb253df155ebfa2ce4b041
[ "MIT" ]
permissive
garborg/clean.dw
f69344d82e5486bb5f2d1defc8b3d5aae2d6a86a
bba685ad7f94b93d1847b91f620a9a5fd777aa6e
refs/heads/master
2021-01-06T20:38:30.506900
2014-05-02T21:56:33
2014-05-02T21:56:33
12,885,336
1
0
null
2014-05-02T21:56:33
2013-09-17T03:25:20
R
UTF-8
R
false
false
567
r
formatting.R
options(scipen=20) enquote = function(names) { if (length(names)) { ifelse(nzchar(names), paste0('"', names, '"'), "") } else names } enquoteNames = function(x) { names(x) = enquote(names(x)) x } chrEscape = function(chr) { if (length(chr)) { paste0("'", gsub("'", "''", chr), "'") } else chr } tf = function(table, field) { paste0(table, '.', field) } indent = function() { ' ' } indentWith = function(v, sep) { if (lv <- length(v)) paste0(indent(), v, c(rep_len(sep, lv-1), '')) }
2e85ceadc25a610fbca401c6c609e603744a4e7f
3bf3c24531fdf87ca1d5e03fb0a591d650f062b5
/man/ad_setup.Rd
4acd27b9aa7596a0dee86c0dc752b249a19a18c6
[]
no_license
hiendn/autodiffr
c8eba7519a8cee22d6c53fabcef53bc23b3038a9
d59407ce1289358afc4fadb1501ad743f5280e28
refs/heads/master
2020-06-19T17:19:43.480408
2018-12-18T23:41:57
2018-12-18T23:41:57
null
0
0
null
null
null
null
UTF-8
R
false
true
931
rd
ad_setup.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/autodiff.R \name{ad_setup} \alias{ad_setup} \title{Do initial setup for package autodiffr.} \usage{ ad_setup(JULIA_HOME = NULL, reverse = TRUE, forward = TRUE, verbose = TRUE, ...) } \arguments{ \item{JULIA_HOME}{the file folder which contains julia binary, if not set, it will try to look at global option JULIA_HOME, if the global option is not set, it will then look at the environmental variable JULIA_HOME, if still not found, julia in path will be used.} \item{reverse}{whether to use load reverse mode automatic differentiation.} \item{forward}{whether to use forward mode automatic differentiation.} \item{verbose}{whether to print package startup messages.} \item{...}{arguments passed to \code{JuliaCall::julia_setup}.} } \description{ \code{ad_setup} does the initial setup for package autodiffr. } \examples{ \dontrun{ ad_setup() } }
9e9bb32e15010f9469836a2f755101b6c349efd5
8124be31adfe738983227380f28b6694b62efdea
/man/data2HTML.Rd
6984c87421482f90fb74eac509394c5bdf6033f2
[]
no_license
guhjy/rrtable
7a1b849bca2a9157972add2507ae5ee4ed849698
587eeee021768a2dc34639dd8c422b3c2c622c21
refs/heads/master
2020-04-08T19:49:43.445657
2018-10-16T04:26:30
2018-10-16T04:26:30
null
0
0
null
null
null
null
UTF-8
R
false
true
1,051
rd
data2HTML.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data2HTML.R \name{data2HTML} \alias{data2HTML} \title{Make a HTML5 file with a data.frame} \usage{ data2HTML(data, preprocessing = "", path = NULL, filename = "report.HTML", rawDataName = NULL, rawDataFile = "rawData.RDS", vanilla = FALSE, echo = TRUE, showself = FALSE) } \arguments{ \item{data}{A data.frame} \item{preprocessing}{A character string of R code} \item{path}{A name of destination file path} \item{filename}{A name of destination file} \item{rawDataName}{The name of the rawData} \item{rawDataFile}{The name of the rawData file which the data are to be read from.} \item{vanilla}{logical. Whether or not make vanilla table} \item{echo}{Logical. Whether or not show R code of plot and table} \item{showself}{Logical. Whether or not show R code for the paragraph} } \description{ Make a HTML5 file with a data.frame } \examples{ \donttest{ library(moonBook) library(ztable) library(rrtable) library(ggplot2) data2HTML(sampleData2,path="tmp") } }
2749d6f5d4a2a3a7170bf1c3a0447a8289d583a2
66332bb30c8d14f824af71a9d418c5d6345f58d1
/source/get.R
508fcd28addd774bc40462aa3f72d1a4a204c93f
[]
no_license
moggces/ActivityProfilingGUI
f2c2f073733e6c3feba6679e8620e81cf4d78c1e
f2bb6533cceba979e31aa91a3a42cfe538c9052e
refs/heads/master
2020-04-15T23:48:14.361354
2017-10-06T15:50:04
2017-10-06T15:50:04
17,751,883
1
0
null
2017-03-27T15:21:38
2014-03-14T16:08:17
R
UTF-8
R
false
false
14,497
r
get.R
# specific to activity file generated from KNIME get_property_name <- function (master) { col_list <- strsplit(colnames(master), '.', fixed=TRUE) #unique(unlist(lapply(col_list, function (x) x[[length(x)]]))) # get the unique assay name names <- lapply(col_list, function (x) { if (length(x) == 3) { return(paste(x[[1]], '.', x[[2]], sep="")) } else {return(x[[1]])} } ) names <- unique(unlist(names)) return(names) } # a wrapper for join, it can detect, CAS, GSID automatically get_lookup_list <- function (input, master) { #result <- subset(master, select=c(CAS, Chemical.Name, StructureID)) #result <- merge(input,result, by='CAS', all.x=TRUE) result <- join(input, master) return(result) } # filter the matrix by chemical input get_input_chemical_mat <- function (input, full) { partial <- list() for (name in names(full)) { if ((name == 'struct') ) { # for the ones that are removed due to purity issue partial[[name]] <- full[[name]][as.character(rownames(full[[name]])) %in% as.character(input[['GSID']]),] # CAS here if (! is.null(partial[['npod']])) { partial[[name]] <- partial[[name]][as.character(rownames(partial[[name]])) %in% as.character(rownames(partial[['npod']])),] } else if (! is.null(partial[['nwauc.logit']])) { partial[[name]] <- partial[[name]][as.character(rownames(partial[[name]])) %in% as.character(rownames(partial[['nwauc.logit']])),] } else if (! is.null(partial[['nec50']])) { partial[[name]] <- partial[[name]][as.character(rownames(partial[[name]])) %in% as.character(rownames(partial[['nec50']])),] } } else { partial[[name]] <- full[[name]][as.character(rownames(full[[name]])) %in% as.character(input[['GSID']]),] # CAS here } } #print(rownames(partial[['npod']])) return(partial) } # filter the matrix by assays regular expression get_assay_mat <- function (partial, regSel, invSel=FALSE) { for (name in names(partial)) { if (name != 'struct' ) { partial[[name]] <- partial[[name]][,grep(regSel, colnames(partial[[name]]), value = TRUE, invert = invSel)] } } return(partial) } # its linked with nwauc.logit matrix results. if active and high CV -> mark get_cv_mark_mat <- function(cv, nwauc) { cv_mark <- cv cv_mark[is.na(cv_mark) ] <- -0.1 cv_mark[cv_mark > 1.4 & nwauc > 0.0001 ] <- "#" cv_mark[cv_mark != "#"] <- '' return(cv_mark) } # dependent on conversion # d: is the distance matrix # input: chemical identification (GSID + Cluster) # master: all mapping info # dmat get_heatmap_annotation <- function (d, input, master, input_chemical_name=NULL, cutoff=0.7, method="average", dmat, actType='') { chemical_name_ref <- input_chemical_name # chemical structure clustering hc <- hclust(d, method=method) group <- cutree(hc, h=cutoff) group_cp <- group group_t <- sort(table(group), decreasing=TRUE) for (i in 1:length(group_t)) { if (group_t[i] == 1) { group_cp[group == names(group_t)[i]] <- 0 } else { group_cp[group == names(group_t)[i]] <- i } } #print(str_c("get:line100", names(group_cp))) # create annotations: chemClust annotation <- data.frame(chemClust = as.factor(group_cp)) rownames(annotation) <- names(group_cp) #print("get:line104") #print(annotation) # create annoations: userClust annotation2 <- data.frame(userClust = as.factor(input[['Cluster']])) if (nrow(annotation2) > 0) { # can get the chemical name outside this function # do not need this because there is input name chemical name #rownames(annotation2) <- as.character(input[['GSID']]) #if (is.null(chemical_name_ref)) chemical_name_ref <- conversion(master, inp='GSID', out='Chemical.Name') if (is.null(chemical_name_ref)) { chemical_name_ref <- make.unique(input[['Chemical.Name']]) rownames(annotation2) <- chemical_name_ref #print(str_c("get:line115", chemical_name_ref)) } else { rownames(annotation2) <- input[['Chemical.Name']] rownames(annotation2) <- chemical_name_ref[as.character(rownames(annotation2))] } annotation <- merge(annotation, annotation2, by="row.names") #print("get:line122") #print(annotation) rownames(annotation) <- annotation$Row.names annotation <- annotation[,-which(colnames(annotation) == 'Row.names')] } # create annotations: toxScore annotation3 <- data.frame() if (actType == 'nwauc.logit' ) { annotation3 <- data.frame(toxScore = rowSums(abs(dmat[[actType]]) )) } else if (actType == 'npod' | actType == 'nec50' ) { if ( ! is.null(dmat[['nwauc.logit']])) { annotation3 <- data.frame(toxScore = unlist(lapply(1:nrow(dmat[[actType]]), function (x) sum(abs(dmat[[actType]][x,])*dmat[['nwauc.logit']][x,]) ))) } else { annotation3 <- data.frame(toxScore = rowSums(abs(dmat[[actType]]) )) } } if (nrow(annotation3) > 0) { rownames(annotation3) <- rownames(dmat[[1]]) annotation <- merge(annotation, annotation3, by="row.names") rownames(annotation) <- annotation$Row.names annotation <- annotation[,-which(colnames(annotation) == 'Row.names')] } return(annotation) } # rainbow color to generate unique colors # toxScore is a continuous color get_heatmap_annotation_color <- function(annotation, actType='') { user <- rainbow(length(unique(annotation[['userClust']]))) names(user) <- sort(unique(annotation[['userClust']])) # for the CAS not avaiable, more levels than values chem <- rainbow(length(unique(annotation[['chemClust']]))) names(chem) <- sort(unique(annotation[['chemClust']])) if (actType != '') #if (! is.null(actType)) { tox <- c("#F7F4F9", "#E7E1EF", "#D4B9DA", "#C994C7", "#DF65B0", "#E7298A", "#CE1256", "#980043", "#67001F") #PuRd return(list(userClust=user, chemClust=chem, toxScore=tox)) } else { return(list(userClust=user, chemClust=chem)) } } get_output_df <- function (paras, id_data, isUpload=FALSE, actwithflag=FALSE) { act <- paras[['act']] annotation <- paras[['annotation']] label <- paras[['label']] cv <- paras[['cv']] # the reverse act flag won't show up (but will show up if not removing inconclusive) # the high_source_variation will only show up if you include the acts # not removing inconclusive could be confusing in the output result <- inner_join(act %>% rownames_to_column("Chemical.Name"), annotation %>% rownames_to_column("Chemical.Name")) if (isUpload) { if(!is.null(id_data$input_Chemical.Name)) { id_data[, "Chemical.Name"] <- id_data$input_Chemical.Name } #else { id_data <- master} } else if (actwithflag ) { result <- act %>% rownames_to_column("Chemical.Name") %>% gather(call_name, act, -Chemical.Name) %>% inner_join( label %>% rownames_to_column("Chemical.Name") %>% gather(call_name, label, -Chemical.Name)) %>% #label df inner_join( cv %>% rownames_to_column("Chemical.Name") %>% gather(call_name, cv, -Chemical.Name)) %>% mutate(label = ifelse(label == 'b_autofluor', 'autofluorescent', ifelse(label == 'c_contradict', 'not_supported_by_ch2', ifelse(label == 'd_cytotoxic', 'cytotoxicity', ifelse(label == 'e_weaknoisy', 'weaknoisy_in_rep', label))))) %>% mutate(comb_data = ifelse( label != 'a_normal', str_c(round(act,4), " (", label, ")"), ifelse( label == "", str_c(round(act,4), " (not_tested)"), ifelse( cv != '', str_c(round(act,4), " (high_source_variation)"), round(act,4))))) %>% #merge act & label select( -label, -act, -cv) %>% spread(call_name, comb_data) %>% inner_join(annotation %>% rownames_to_column("Chemical.Name")) # add the annotation } result[,"Chemical.Name_original"] <- result$Chemical.Name result[,"Chemical.Name_original"] <- sub("\\.[0-9]+$", "", result$Chemical.Name_original) result <- left_join(result, subset(id_data, select=c(CAS, Chemical.Name)), by=c("Chemical.Name_original" = "Chemical.Name")) # join by Chemical.Name result <- result[, c("CAS", grep("CAS", colnames(result), invert=TRUE, value=TRUE))] return(result) } get_pod_boxplot <- function (pod, fontsize, sortby, dcols, global_para) { # order the chemical.name h <- hclust(dcols, method='average') pod[, 'Chemical.Name'] <- ordered(pod$Chemical.Name, levels=h$label[h$order]) if (sortby == 'toxscore') pod[, 'Chemical.Name'] <- ordered(pod$Chemical.Name, levels=pod$Chemical.Name[order(pod$toxScore)]) # melt the data and exclude the all inactives pod_m <- melt(pod, id.vars = c( 'CAS', 'Chemical.Name', 'chemClust', 'userClust', 'toxScore'), value.name = "pod_value", variable.name = 'pathway') pod_m <- subset(pod_m, pod_value > 1) # Chemical.Name is a factor. So if completely inactve. it won't be removed mat <- pod_m #create conversion #let <- conversion(global_para, inp='common_name', out='letters') let <- conversion(global_para, inp='protocol_call_db.name', out='_letters4boxplot') let2 <- paste(let, names(let), sep="=") # color legend names(let2) <- names(let) #add a new column mat[, 'path_abb'] <- let[as.character(mat$pathway)] p <- ggplot(data=mat, aes(x=Chemical.Name, y=pod_value*-1+6)) + geom_boxplot(outlier.shape = NA) + geom_text(aes(label=path_abb, color=pathway), size=7, alpha=0.7, position="jitter") + scale_color_discrete("",labels=let2) + scale_x_discrete("", drop=FALSE) + # keep the no activity ones theme(text=element_text(size=fontsize), axis.text.x = element_text( angle=90, color="black")) + scale_y_continuous(expression(paste("concentration ", "(", mu, "M", ")", sep="")), breaks=seq(-10+6, -3+6, by=1), limits=c(-10+6, -3+6), labels = math_format(10^.x)) + #theme_bw(base_size = fontsize) + annotation_logticks(sides = "l") return(p) } get_published_data_only_commonname <- function (dd, assay_dd) { id_cols <- c('CAS','Chemical.Name','chemClust','userClust','toxScore') ok_assays <- unlist(subset(assay_dd, ! is.na(`PubChem AID`), select="common_name")) result <- dd[, colnames(dd) %in% c(id_cols, ok_assays)] return(result) } get_clust_assay_enrichment <- function (partial_act, full_act, annotation, calZscore=FALSE) { pp <- partial_act %>% add_rownames() %>% left_join(select(add_rownames(annotation), -toxScore)) %>% mutate(allClust = "all") %>% gather(assay, act, -matches('rowname|Clust'), na.rm = TRUE) %>% gather(clust_group, clust, matches('Clust')) %>% group_by(assay, clust_group, clust) %>% filter(clust != 'unassigned') %>% #summarize(n=sum(act != 0.0001), n_p=sum(act > 0.0001), n_mean=mean(act), n_std=sd(act)) summarize(n=sum(act != 0.0001), n_p=sum(act > 0.0001)) ff_long <- full_act %>% select(one_of(colnames(partial_act))) %>% gather(assay, act, na.rm = TRUE) %>% group_by(assay) ff <- ff_long %>% summarise(N=sum(act != 0.0001), N_P=sum(act > 0.0001)) if (calZscore) { zz <- bind_rows(lapply(1:2000, function (x) pp %>% filter(n_p > 1) %>% left_join(ff_long, by="assay") %>% group_by(assay, clust_group, clust) %>% sample_frac(1) %>% slice(1:unique(n)) %>% group_by(assay, clust_group, clust) %>% summarize(ns_p=sum(act > 0.0001)))) %>% group_by(assay, clust_group, clust) %>% summarize(ns_mean=mean(ns_p), ns_std=sd(ns_p)) result <- pp %>% filter(n_p > 1) %>% left_join(zz) %>% left_join(ff) result <- result %>% rowwise() %>% mutate(pvalue = get_fisher_pvalue(n, n_p, N_P, N)$p.value, zscore = (n_p-ns_mean)/ns_std) } else { result <- pp %>% filter(n_p > 1) %>% left_join(ff) if (nrow(result) > 0) { result <- result %>% rowwise() %>% mutate(pvalue = get_fisher_pvalue(n, n_p, N_P, N)$p.value) } } return(result) } get_fisher_pvalue <- function (n, n_p, N_P, N) { conti <- matrix ( c( n_p-1, n-n_p, N_P-n_p, N-n-(N_P-n_p)), nrow=2, dimnames = list(active = c('In', 'notIn'), clust = c('In', 'notIn'))) fish <- fisher.test( conti , alternative="greater") return(fish) } get_source_data_long <- function(source_acts, chem_id_master, filtered_act) { chem_id_filtered <- chem_id_master %>% select(CAS, Chemical.Name, Tox21.ID, Purity_Rating_T0, Purity_Rating_T4, Purity_Rating_Comb) %>% unnest(Tox21.ID = str_split(Tox21.ID, "\\|"), Purity_Rating_T0 = str_split(Purity_Rating_T0, "\\|"), Purity_Rating_T4 = str_split(Purity_Rating_T4, "\\|"), Purity_Rating_Comb = str_split(Purity_Rating_Comb, "\\|")) %>% filter(Chemical.Name %in% rownames(filtered_act)) # filter by the filtered act Chemical.Name # the activity type to retrieve value_type <- c('hitcall', 'label', 'nwauc', 'npod', 'nec50', 'ncmax', 'nwauc.logit', 'wauc_fold_change' ) source_acts <- source_acts[value_type] acts_collect <- lapply(names(source_acts), function (x){ result <- source_acts[[x]] %>% rownames_to_column("Tox21AgencyID") %>% separate(Tox21AgencyID, c("Tox21.ID", "Library"), sep="@") %>% filter(Tox21.ID %in% chem_id_filtered$Tox21.ID) %>% gather_("call_name", x, grep("Tox21.ID|Library", colnames(.), value=TRUE, invert=TRUE)) %>% filter(call_name %in% colnames(filtered_act)) return(result) }) acts_collect <- left_join(chem_id_filtered, Reduce("full_join", acts_collect)) %>% mutate(label = ifelse(label == 'b_autofluor', 'autofluorescent', ifelse(label == 'c_contradict', 'not_supported_by_ch2', ifelse(label == 'd_cytotoxic', 'cytotoxicity', ifelse(label == 'e_weaknoisy', 'weaknoisy_in_rep', ifelse(label == 'a_normal', '', ifelse(label == '', 'not_tested', label))))))) %>% rename(flag = label, efficacy = ncmax, POD=npod, EC50=nec50, wAUC=nwauc, wAUC.logit=nwauc.logit, wAUC.fold.change = wauc_fold_change) return(acts_collect) }
53fd0350f89cb1c6a03fb4ce4baf7f8c407272a3
40962c524801fb9738e3b450dbb8129bb54924e1
/Day - 1/Assignment/Q2 - UserInput.R
36edb2808efbb9da098ea49c577a1751118cee21
[]
no_license
klmsathish/R_Programming
628febe334d5d388c3dc51560d53f223585a0843
93450028134d4a9834740922ff55737276f62961
refs/heads/master
2023-01-14T12:08:59.068741
2020-11-15T13:23:31
2020-11-15T13:23:31
309,288,498
1
0
null
null
null
null
UTF-8
R
false
false
270
r
Q2 - UserInput.R
#UserInput Id = readline("Enter your UserID:") #Prompts user for input(id) Branch = readline(prompt="Enter you Branch/Group:") #Prompts user for input(branch) cat("Your UserID is",Id,"and you belong to",Branch,"group") #Displaying Values
112a58fb89bdf1037197144d51edca7fb80b92ff
b32a5bca6aeac9ec9c0761079164540b21103dfa
/visualization-project-shiny.R
a53004252a0fc8b8c4ef79b921db911878765340
[]
no_license
chelseypaulsen/Fall2Orange2
5533f479bf91c1262bc0b6b8d8b696d5c61c7b30
f807c5ca9d548b72c75a3d791dd67c69bfb8e8f3
refs/heads/master
2020-03-30T20:38:44.468347
2018-10-25T04:53:41
2018-10-25T04:53:41
151,597,178
0
0
null
null
null
null
UTF-8
R
false
false
24,257
r
visualization-project-shiny.R
rm(list=ls()) library(shiny) library(ggplot2) #install.packages(c('maps','mapproj','caschrono')) library(maps) library(mapproj) library(tidyverse) library(readxl) library(zoo) library(forecast) library(haven) library(fma) library(expsmooth) library(lmtest) library(seasonal) library(lubridate) library(tseries) library(foreign) library(caschrono) library(TSA) library(quantmod) library(imputeTS) library(dplyr) #install.packages('rlang') #install.packages(c('stringi')) library(rlang) #install.packages('shinydashboard') library(shinydashboard) #install.packages(c('shiny','ggplot2','dplyr','tidyverse','readxl','forecast','haven','fma','expsmooth','lubridate','caschrono','imputeTS')) # Set up the working directory and initialize the well list data.dir <- 'C:/Users/johnb/OneDrive/Documents/MSA/Fall 2/Well Data/' #data.dir <- 'C:/Users/Steven/Documents/MSA/Analytics Foundations/Forecasting/data/Well Data/' wells <- c('G-852','F-45','F-179','F-319','G-561_T','G-580A','G-860','G-1220_T', 'G-1260_T','G-2147_T','G-2866_T','G-3549','PB-1680_T') rainlist <- c('G852_RAIN','F45_RAIN','F179_RAIN','F319_RAIN','G561_T_RAIN','G580A_RAIN','G860_RAIN','G1220_T_RAIN', 'G1260_T_RAIN','G2147_T_RAIN','G2866_T_RAIN','G3549_RAIN','PB1680_T_RAIN') welllist <- c('G852','F45','F179','F319','G561_T','G580A','G860','G1220_T', 'G1260_T','G2147_T','G2866_T','G3549','PB1680_T') # Create a sequence of dates and convert to dataframe to find missing dates in well data start <- ymd_h("2007/10/01 00", tz='UTC') end <- ymd_h("2018/06/12 23", tz='UTC') hourseq <- seq(start,end+(168*3600), by='hours') full_df <- data.frame(datetime=hourseq) hourseqdf <- as.data.frame(hourseq) names(hourseqdf) <- c('datetime') end_df = data.frame(names = wells, ends = c('','3/26/2018 10','6/4/2018 10','4/9/2018 12','6/12/2018 23','4/9/2018 11','6/4/2018 12','','6/8/2018 11','6/8/2018 09', '6/8/2018 09','6/12/2018 23','2/8/2018 09'), starts = c('10/1/2007 00','10/1/2007 01','10/1/2007 01','10/1/2007 01','10/5/2007 00','10/1/2007 00','10/1/2007 01', '10/1/2007 00','10/1/2007 01','10/10/2007 00','10/1/2007 01','10/1/2007 01','10/1/2007 01'), stringsAsFactors = F) # pred_model5 <- function(final_well, well.2){ # # TODO, incoporate and check that this function works in the for loop # # # this function takes in a dataframe of well datetimes,well data, and rain data # # it returns the original dataframe w/ new cols for forecast and confidence intervals # # it also depends on startwell and endwell vectors # # returned df also has new names # # #splitting newly assembled well data for clean model generation # if (well.2 == 'G-852' | well.2 == 'G-1220_T'){end_dt <- max(well_df_clean$datetime) # } # # else{end_dt <- mdy_h(endwell)} # train <- final_well %>% # filter(datetime >= mdy_h(startwell) & datetime <= end_dt) # # Generating model on training data # yearly <- 24*365.25 # x.reg <- train$RAIN_FT # seasons <- msts(train$filled, start=1, seasonal.periods = c(yearly)) # model5 <- Arima(seasons,order=c(2,0,2), xreg=cbind(fourier(seasons,K=1),x.reg)) # # # forecasting across last 168 days # rain.ts <- read.zoo(train$RAIN_FT) # rain.impute <- na.approx(rain.ts) # rain.model <- auto.arima(rain.impute) # rain.preds <- forecast(rain.model, h=168) # newx <- rain.preds$mean # using actual rainfall data, because our rain model is really bad # final.pred=forecast(model5,xreg=cbind(fourier(seasons,K=1),newx),h=168) # # # building df from results # df_results <- as.data.frame(cbind( # final.pred$mean, # final.pred$upper[,1], # final.pred$upper[,2], # final.pred$lower[,1], # final.pred$lower[,2])) # colnames(df_results) <- c('Forecast', 'Upper80', 'Upper95', 'Low80', 'Low95') #probably an unnecessary line # df_results$datetime <- test$datetime # final_well <- final_well %>% # left_join(df_results, by="datetime") # # # Rename the column to the appropriate names # well2 <- gsub('-','',well) # names <- c('','_RAIN', '_Forecast', '_Up80', '_Up95', '_Lo80', '_Lo95') # uniq_names <- paste(well2,names,sep="") # colnames(final_well) <- c("datetime", uniq_names) # # # return(final_well) # } # Read the excel files in and clean them for (well in wells){ if (well == 'G-852'){ df <- read_excel(paste(data.dir,well,'.xlsx',sep=''),sheet='Well', col_names=c('date','time','tz_code','well_ft', 'Code','Corrected'),skip=1) } else{ df <- read_excel(paste(data.dir,well,'.xlsx',sep=''),sheet='Well') } well_df <- data.frame(df) print(well) startwell <- (end_df %>% filter(names==well) %>% select(starts)) endwell <- (end_df %>% filter(names==well) %>% select(ends)) well_df_clean <- mutate(well_df, time=hour(time)) # adds date to datetime well_df_clean$datetime <- as.POSIXct(paste(well_df_clean$date,well_df_clean$time), format='%Y-%m-%d %H',tz='UTC') if ((endwell) != ''){ well_df_clean <- well_df_clean %>% # summarizes to hourly data and group_by(datetime) %>% # averages Corrected values when multiple rows have same datetime summarise(well_ft=mean(Corrected)) %>% filter(datetime >= mdy_h(startwell) & # filters to dates defined in Simmons instructions datetime <= mdy_h(endwell))} else{ well_df_clean <- well_df_clean %>% group_by(datetime) %>% summarise(well_ft=mean(Corrected)) %>% filter(datetime >= mdy_h(startwell) & datetime <= mdy_h('6/12/2018 23')) } well_df_clean <- well_df_clean %>% select(datetime,well_ft) if(endwell != ''){ hourseq2 <- seq(mdy_h(startwell),mdy_h(endwell), by='hours') } else{ hourseq2 <- seq(mdy_h(startwell),max(well_df_clean$datetime),by='hours') } hourseq2df <- as.data.frame(hourseq2) names(hourseq2df) <- c('datetime') # Join the data onto the date sequence to find missing values full_well_df <- left_join(hourseq2df,well_df_clean,by='datetime') # Create the timeseries object and then impute missing values using imputeTS package startday <- as.numeric(strftime(mdy_h(startwell), format='%j')) timeseries <- ts(full_well_df$well_ft, start=c(2007,startday*24), frequency=(365.25*24)) imputed <- na.seadec(timeseries, algorithm='locf') full_well_df$filled <- imputed final_well <- left_join(hourseqdf,full_well_df, by='datetime') final_well <- final_well %>% select(datetime, filled) ##################### ##### Rain Data ##### ##################### rain <- read_xlsx(paste(data.dir,well,'.xlsx',sep=""),sheet='Rain') rain$date<- as.Date(rain$Date) rain$time<- format(as.POSIXct(rain$Date, "%H:%M:%S")) rain_df <-data.frame(rain) rain_df_clean <- mutate(rain_df, datetime=date(date)) # adds date to datetime hour(rain_df_clean$datetime) <- hour(rain_df_clean$time) # Adds hour to datetime. Removes minutes from all hours rain_df_clean$datetime <- as.POSIXct(rain_df_clean$datetime) # change time type of newly created Datetime if(endwell != ''){ rain_df_clean <- rain_df_clean %>% # summarizes to hourly data and group_by(datetime) %>% # averages Corrected values when multiple rows have same datetime summarise(RAIN_FT=mean(RAIN_FT)) %>% filter(datetime >= mdy_h(startwell) & # filters to dates defined in Simmons instructions datetime <= mdy_h(endwell))} else{ rain_df_clean <- rain_df_clean %>% group_by(datetime) %>% summarise(RAIN_FT=mean(RAIN_FT)) %>% filter(datetime >= mdy_h(startwell)) } final_well <- left_join(final_well, rain_df_clean, by='datetime') ##################### ##### Forecasting #### ##################### # Run function to get forecast # final_well <- pred_model5(rain_n_well) # DISFUNCTIONAL FUNCTION # splitting newly assembled well data for clean model generation if (well == 'G-852' | well == 'G-1220_T'){end_dt <- max(well_df_clean$datetime) } else{end_dt <- mdy_h(endwell)} train <- final_well %>% select(datetime,filled,RAIN_FT) %>% filter(datetime >= mdy_h(startwell) & datetime <= end_dt) # Generating model on training data yearly <- 24*365.25 x.reg <- train$RAIN_FT seasons <- msts(train$filled, start=1, seasonal.periods = c(yearly)) model5 <- Arima(seasons,order=c(2,0,2), xreg=cbind(fourier(seasons,K=1),x.reg)) # forecasting across last 168 days rain.ts <- read.zoo(train %>% select(datetime,RAIN_FT)) rain.impute <- na.approx(rain.ts) rain.model <- auto.arima(rain.impute) autoplot(rain.impute) rain.preds <- forecast(rain.model, h=168) r.f <- rain.preds$mean r.f.df <- as.data.frame(r.f) num <- length(seasons) index <- num-(365.25*24) sine <- fourier(seasons,K=1)[,1] cose <- fourier(seasons,K=1)[,2] final.pred <- forecast(model5,xreg=cbind(sine[index:(index+167)],cose[index:(index+167)],r.f.df$x),h=168) # building df from results df_results <- as.data.frame(cbind( final.pred$mean, final.pred$upper[,1], final.pred$upper[,2], final.pred$lower[,1], final.pred$lower[,2])) colnames(df_results) <- c('Forecast', 'Upper80', 'Upper95', 'Low80', 'Low95') #probably an unnecessary line df_results$datetime <- seq(end_dt+hours(1), end_dt+hours(168), by='1 hour') final_well <- final_well %>% left_join(df_results, by="datetime") # Rename the column to the appropriate names well2 <- gsub('-','',well) names <- c('','_RAIN', '_Forecast', '_Up80', '_Up95', '_Lo80', '_Lo95') uniq_names <- paste(well2,names,sep="") colnames(final_well) <- c("datetime", uniq_names) # Join all the well columns together into one master dataframe full_df <- full_df %>% left_join(final_well, by='datetime') } head(full_df) full_df %>% filter(datetime <= mdy_h('6/13/2018 03') & datetime >= mdy_h('6/12/2018 22')) # to save time on the above steps. Be careful to not save it to the Git repository. That'll eventually take up a lot of space. save(full_df, welllist, file="Well_Viz_Full.RData") # need to add model to this save effort load("C:/Users/johnb/OneDrive/Documents/MSA/Fall 2/Well Data/Well_Viz_Full.RData") load("C:/Users/johnb/OneDrive/Documents/MSA/Fall 2/Well Data/Well_Viz_10_24.RData") full_df %>% select(datetime,G852,G852_Forecast) %>% filter(is.na(!!as.symbol('G852'))) ############################### # Below is the shiny app code # ############################### ui <- dashboardPage( # The UI code dashboardHeader( title='Options'), # Set up the conditional panels that are dependent on the user's first selection dashboardSidebar( sidebarMenu(id='menu1', menuItem('Explore', tabName='explore', icon=icon('compass')), menuItem('Predict', tabName='predict', icon=icon('bullseye') ), # 'Explor' sidebar panels conditionalPanel( #condition = 'input.choice == "Explore"', condition = 'input.menu1 == "explore"', checkboxGroupInput('well_check','Well', choices=welllist,selected='G852'), dateRangeInput('dateRange_Input', 'Date Range', start='2016-01-01', end='2018-01-01', min='2007-10-01', max='2018-06-12'), selectInput('year_Input','Year',unique(year(full_df$datetime)),selected='2009'), selectInput('month_Input','Month',''), selectInput('day_Input','Day','')), # 'Predict' sidebar panels conditionalPanel( #condition = 'input.choice == "Predict"', condition = 'input.menu1 == "predict"', selectInput('well_Input','Well',welllist,selected='G852'), numericInput('range_Input','Hours Predicted (max. 168)',68,0,168,1), radioButtons('decomp_Input','Effects',choices=c('Rain','Seasonal'),selected='Rain'), dateInput('start_date','Initial Plot Date',value='2018-06-01',min='2007-10-01',max='2018-07-01') ) )), dashboardBody( mainPanel( tabItems( tabItem(tabName='explore', fluidRow( box(#title='Timeseries Plot of Selected Well(s)', plotOutput('timeOutput'), width=12), box(#title='Well Elevation on Selected Date', plotOutput('dateOutput'), width=12) ) ), tabItem(tabName='predict', fluidRow( box(#title='Forecast for Selected Well', plotOutput('predictOutput'), width=12), conditionalPanel( condition = 'input.decomp_Input == "Rain"', box(#title='Rain Influence on Predictions', plotOutput('rainefctOutput'),width=12) ), conditionalPanel( condition = 'input.decomp_Input == "Seasonal"', box(#title='Seasonal Influence on Predictions', plotOutput('seasefctOutput'),width=12) ) )) )) # 'Explore' panels # conditionalPanel( # condition = 'input.choice == "Explore"', # h4('Timeseries Plot of Selected Well'), # plotOutput('timeOutput'), # br(), # h4('Well Heights on Selected Date'), # plotOutput('dateOutput')), # br(), # # 'Predict' panels # conditionalPanel( # condition = 'input.choice == "Predict"', # h4('Well Prediction for Selected Well and Hours'), # plotOutput('predictOutput'), # br(), # h4('Rain Measurements'), # plotOutput('rainOutput')), # br())) ) ) # Below is the server code for shiny server <- function(input,output,session){ reactive_data_well <- reactive({ full_df %>% select(datetime,input$well_check) %>% gather(well, depth, -datetime) }) observe({ print(input$well_check) print(names(reactive_data_well())) }) observe({ print(input$well_Input) print(input$range_Input) }) reactive_data_year <- reactive({ full_df %>% filter(year(datetime) == input$year_Input) }) reactive_TS_date <- reactive({ as.POSIXct(input$dateRange_Input) }) # Need observe function to make the dropdown menu option reactive # observe({ # updateDateRangeInput(session,'dateRange_Input', # start=min(reactive_data_well()$datetime), # end=max(reactive_data_well()$datetime)) # }) observe({ updateSelectInput(session,'month_Input', choices=unique(month((reactive_data_year())$datetime))) }) # First allow for month input to not have a value to prevent error # If it has a value, use it observe({ if(input$month_Input == ''){ return() } else{ reactive_data_month <- reactive({(full_df %>% filter(year(datetime) == input$year_Input) %>% filter(month(datetime) == input$month_Input))}) updateSelectInput(session,'day_Input', choices=unique(day((reactive_data_month())$datetime))) } }) # Again use observe to allow the ggplot to have a variable number of lines in it observe({ if(is.null(input$well_check)){ output$timeOutput <- renderPlot({ ggplot(reactive_data_well(), aes(x=datetime)) }) } else{ # Below the plot iterates over however many wells are selected and adds them to the graph alphas <- c(1,0.7,0.5,0.3) if(length(input$well_check) == 1){ a2 <- alphas[1] } else if(length(input$well_check) < 5){ a2 <- alphas[2] } else if(length(input$well_check) < 9){ a2 <- alphas[3] } else{ a2 <- alphas[4] } cbbPalette <- c('G852'='#000000','F45'='#a6cee3','F179'='#1f78b4','F319'='#b2df8a','G561_T'='#33a02c', 'G580A'='#fb9a99','G860'='#e31a1c','G1220_T'='#fdbf6f','G1260_T'='#ff7f00', 'G2147_T'='#cab2d6','G2866_T'='#6a3d9a','G3549'='#ffff99','PB1680_T'='#b15928') output$timeOutput <- renderPlot({ p <- ggplot(reactive_data_well(), aes(x=datetime, y=depth, color=well)) + geom_line(alpha=a2) + xlim(reactive_TS_date()) #TODO attempts at this failed: +geom_vline(xintercept = ) # Need better colors #cbbPalette <- c('#000000','#a6cee3','#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c', # '#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99','#b15928') p <- p + theme(legend.position='right') + labs(y='Well Elevation (ft)', x='Year') + scale_color_manual(values=cbbPalette) + guides(color=guide_legend(title='Well'))+theme_minimal()+ ggtitle("Timeseries Plot of Selected Well(s)")+ theme(axis.title=element_text(size=20),plot.title=element_text(size=28, hjust=0.5), axis.text = element_text(size=12), legend.text=element_text(size=12), legend.title=element_text(size=12)) p })} }) # The bar chart is below, need observe because the inputs are reactive to other inputs observe({ if(input$month_Input == '' | input$day_Input == ''){ return() } else{ reactive_prelim <- reactive({(full_df %>% select(datetime, one_of(welllist)) %>% filter(year(datetime) == input$year_Input,month(datetime) == input$month_Input, day(datetime) == input$day_Input) %>% summarise_all(funs(mean)) %>% select(-datetime) %>% gather(well, depth))}) reactive_data_date <- reactive({new <- reactive_prelim() new$sign <- as.factor(reactive_prelim()$depth > 0) new}) cols = c('TRUE'='#00BFC4','FALSE'='#F8766D') output$dateOutput <- renderPlot({ ggplot(reactive_data_date(), aes(x=well,y=depth,fill=sign)) + geom_col() + labs(x='Well',y='Well Elevation (ft)') + guides(fill=F) + geom_text(aes(label=round(depth, digits=2), vjust = ifelse(depth >= 0, -0.25, 1.25)), size=5) + scale_fill_manual(values=cols)+theme_minimal()+ggtitle("Well Elevation on Selected Date")+ theme(axis.title=element_text(size=20),plot.title=element_text(size=28, hjust=0.5), axis.text = element_text(size=12)) #cale_fill_manual(values=c('red','blue')) }) } }) vars <- c('_Forecast','_Up80','_Up95','_Lo80','_Lo95') reactive_predict <- reactive({full_df %>% select(datetime,input$well_Input,paste(input$well_Input,vars,sep='')) %>% filter(!is.na(!!as.symbol(input$well_Input)) | !is.na(!!as.symbol(paste(input$well_Input,'_Forecast',sep=''))))}) reactive_rain_pred <- reactive({full_df %>% select(datetime,paste(input$well_Input,'_RAIN',sep=''), paste(input$well_Input,'.rain.efct',sep=''), paste(input$well_Input,'.seas.efct',sep=''))}) observe({ # need to use the as.symbol function to make the string into a symbol so the filter function works # reactive_predict <- reactive({full_df %>% select(datetime,input$well_Input,paste(input$well_Input,vars,sep='')) %>% # filter(!is.na(!!as.symbol(input$well_Input)) | !is.na(!!as.symbol(paste(input$well_Input,'_Forecast',sep=''))))}) # # reactive_rain_pred <- reactive({full_df %>% select(datetime,paste(input$well_Input,'_RAIN',sep=''), # paste(input$well_Input,'.rain.efct',sep=''), # paste(input$well_Input,'.seas.efct',sep=''))}) updateDateInput(session,'start_date', min=(max(reactive_predict()$datetime)-years(1)), max=(max(reactive_predict()$datetime)-days(14))) # if(input$start_date == ''){ # return() # } # else{ # https://stackoverflow.com/questions/17148679/construct-a-manual-legend-for-a-complicated-plot output$predictOutput <- renderPlot({ggplot(reactive_predict(), aes_string(x='datetime',y=paste(input$well_Input,'_Forecast',sep=''))) + geom_line(color='#F8766D') + geom_vline(xintercept=max((reactive_predict() %>% filter(!is.na(!!as.symbol(input$well_Input))))$datetime), linetype=2, alpha=0.7) + geom_line(aes_string(y=input$well_Input)) + geom_line(aes_string(y=paste(input$well_Input,'_Up95',sep='')),color='#00BFC4',alpha=0.7) + geom_line(aes_string(y=paste(input$well_Input,'_Lo95',sep='')),color='#00BFC4',alpha=0.7) + scale_x_datetime(limits=c(as.POSIXct(ymd(input$start_date)),(max(reactive_predict()$datetime) - hours(168-input$range_Input)))) + #scale_y_continuous(limits=c(min(reactive_predict() %>% select(input$well_Input)) - 1, max(reactive_predict() %>% select(input$well_Input)) + 1)) + geom_line(aes_string(y=paste(input$well_Input,'_Up80',sep='')),color='#00BFC4',linetype=2) + geom_line(aes_string(y=paste(input$well_Input,'_Lo80',sep='')),color='#00BFC4',linetype=2) + labs(x='Time',y='Well Elevation (ft)')+ggtitle("Forecast for Selected Well")+theme_minimal()+ guides(color = guide_legend(order = 1), lines = guide_legend(order = 2)) + theme(axis.title=element_text(size=20), plot.title=element_text(size=28, hjust=0.5), axis.text = element_text(size=12), plot.margin = unit(c(5,40,5,5),'points')) }) # if(input$start_date == ''){ # return() # } # else{ output$rainefctOutput <- renderPlot({ ggplot(reactive_rain_pred(), aes(x=datetime)) + geom_line(aes_string(y=paste(input$well_Input,'.rain.efct',sep='')), linetype=5) + geom_vline(xintercept=max((reactive_predict() %>% filter(!is.na(!!as.symbol(input$well_Input))))$datetime), linetype=2, alpha=0.7) + geom_histogram(stat='identity',aes_string(y=paste(input$well_Input,'_RAIN*12',sep='')),fill='#00BFC4') + scale_x_datetime(limits=c(as.POSIXct(ymd(input$start_date)),(max(reactive_predict()$datetime) - hours(168-input$range_Input)))) + scale_y_continuous(sec.axis = sec_axis(~.*12, name = "Rainfall (in)")) + labs(x='Time',y='Rain Effect (ft)')+ theme_minimal()+ggtitle("Rain Influence")+ theme(axis.title=element_text(size=20), plot.title=element_text(size=28, hjust=0.5), axis.text = element_text(size=12), axis.title.y.right = element_text(color = '#00BFC4'), axis.text.y.right = element_text(color ='#00BFC4', margin = margin(t = 0, r = 0, b = 0, l = 10)), plot.margin = unit(c(5,5,5,5),'points') ) }) output$seasefctOutput <- renderPlot({ ggplot(reactive_rain_pred(), aes(x=datetime)) + geom_line(aes_string(y=paste(input$well_Input,'.seas.efct',sep=''))) + geom_vline(xintercept=max((reactive_predict() %>% filter(!is.na(!!as.symbol(input$well_Input))))$datetime), linetype=2, alpha=0.7) + scale_x_datetime(limits=c(as.POSIXct(ymd(input$start_date)),(max(reactive_predict()$datetime) - hours(168-input$range_Input)))) + labs(x='Time',y='Seasonal Effect (ft)')+theme_minimal()+ggtitle('Seasonal Influence on Predictions')+ theme(axis.title=element_text(size=20), plot.title=element_text(size=28, hjust=0.5), axis.text = element_text(size=12), plot.margin = unit(c(5,40,5,5),'points')) }) }) } # Call the app shinyApp(ui=ui, server=server, options=list(height=1080))
4ed7443a61480e153b81d20832617c75ce2987b3
e54a704f3197440a47f987a4e080716e8db55cc7
/tests/testthat/test-RE-stan_data.R
560a898fba345acfc22d115580d66e2e4330327e
[]
no_license
dimbage/epidemia
ccb2b13c25b0dcb8a4857590cf6dc6d2494af3b2
c68720cabbc3856fa903038f603e9af6f6afa799
refs/heads/master
2023-07-13T08:51:39.922234
2021-06-23T10:59:35
2021-06-23T10:59:35
null
0
0
null
null
null
null
UTF-8
R
false
false
3,090
r
test-RE-stan_data.R
context("Random effects stan data") load(file = "../data/NYWA.RData") args <- list() args$data <- NYWA$data args$inf <- epiinf(gen=NYWA$si) expect_warning(args$obs <- epiobs(deaths ~ 1, i2o = NYWA$inf2death * 0.02)) args$chains <- 0 test_that("Correct dimensions and values for quantities t, p, q and l in the stan data", { # check terms for random effects are null if there are none args$rt <- epirt( formula = R(code, date) ~ 1 + av_mobility ) sdat <- do.call("epim", args=args) expect_equal(sdat$t, 0) expect_equal(sdat$q, 0) expect_equal(sdat$len_theta_L,0) expect_equal(length(sdat$p),0) expect_equal(length(sdat$l),0) # check quantities for a simple random effects term args$rt <- epirt( formula = R(code, date) ~ 1 + (av_mobility | code) ) sdat <- do.call("epim", args=args) expect_equal(sdat$t, 1) expect_equal(sdat$q, sum(sdat$p * sdat$l)) expect_equal(as.numeric(sdat$p), 2) expect_equal(as.numeric(sdat$l), 3) expect_equal(sdat$len_theta_L, sum(factorial(sdat$p + 1)/2)) # Setting with no intercept args$rt <- epirt( formula = R(code, date) ~ (0 + av_mobility | code) ) sdat <- do.call("epim", args=args) expect_equal(sdat$t, 1) expect_equal(sdat$q, sum(sdat$p * sdat$l)) expect_equal(as.numeric(sdat$p), 1) expect_equal(as.numeric(sdat$l), 3) expect_equal(sdat$len_theta_L, sum(factorial(sdat$p + 1)/2)) # Multiple terms args$rt <- epirt( formula = R(code, date) ~ (av_mobility | code) + (0 + residential | code) ) sdat <- do.call("epim", args=args) expect_equal(sdat$t, 2) expect_equal(sdat$q, sum(sdat$p * sdat$l)) expect_equal(as.numeric(sdat$p), c(2,1)) expect_equal(as.numeric(sdat$l), c(3,3)) expect_equal(sdat$len_theta_L,sum(factorial(sdat$p + 1)/2)) }) test_that("CSR matrix vectors for random slope model", { # test CSR storage vectors on intercept example args$rt <- epirt( formula = R(code, date) ~ (1 | code) ) sdat <- do.call("epim", args = args) len <- nrow(args$data) colidx <- 1 - (args$data$code == "NY") expect_equal(sdat$w, rep(1,len)) expect_equal(sdat$v, colidx) # each row has a single entry expect_equal(sdat$u, 0:len) expect_equal(sdat$num_non_zero, len) # check empty if there are no random effect terms args$rt <- epirt( formula = R(code, date) ~ 1 ) sdat <- do.call("epim", args = args) expect_equal(length(sdat$w), 0) expect_equal(length(sdat$v), 0) expect_equal(length(sdat$u), 0) expect_equal(sdat$num_non_zero, 0) }) test_that("Correct usage of special_case flag in stan data", { # Only FE args$rt <- epirt( formula = R(code, date) ~ 1 ) sdat <- do.call("epim", args=args) expect_equal(sdat$special_case, 0) # Only random intercept (special case == TRUE) args$rt <- epirt( formula = R(code, date) ~ (1 | code) ) sdat <- do.call("epim", args=args) expect_true(sdat$special_case) # Random slopes (special_case == FALSE) args$rt <- epirt( formula = R(code, date) ~ (av_mobility | code) ) sdat <- do.call("epim", args=args) expect_false(sdat$special_case) })
6254930780e33489118c6548709de47705a7aaca
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/pmxTools/examples/calc_sd_2cmt_linear_oral_1_lag.Rd.R
7a65f618132392e356e05ed6782b799fb1f06bce
[]
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
370
r
calc_sd_2cmt_linear_oral_1_lag.Rd.R
library(pmxTools) ### Name: calc_sd_2cmt_linear_oral_1_lag ### Title: Calculate C(t) for a 2-compartment linear model after a single ### first-order oral dose with a lag time ### Aliases: calc_sd_2cmt_linear_oral_1_lag ### ** Examples Ctrough <- calc_sd_2cmt_linear_oral_1_lag(t = 11.75, CL = 7.5, V1 = 20, V2 = 30, Q = 0.5, dose = 1000, ka = 1, tlag = 2)
440ac7a6cd985447816c5de8fec889be81ee6d08
f30cc1c33978ca5a708a7e0a493403ea88550160
/R/neuronlist_interactive_3d.R
be1488ecb8e9b486c865769c0d07514d2a5cfdae
[]
no_license
natverse/nat
044384a04a17fd0c9d895e14979ce43e43a283ba
1d161fa463086a2d03e7db3d2a55cf4d653dcc1b
refs/heads/master
2023-08-30T21:34:36.623787
2023-08-25T07:23:44
2023-08-26T19:02:50
15,578,625
35
10
null
2023-01-28T19:03:03
2014-01-02T07:54:01
R
UTF-8
R
false
false
8,757
r
neuronlist_interactive_3d.R
#' Find neurons within a 3D selection box (usually drawn in rgl window) #' #' @details Uses \code{\link{subset.neuronlist}}, so can work on dotprops or #' neuron lists. #' @param sel3dfun A \code{\link{select3d}} style function to indicate if points #' are within region #' @param indices Names of neurons to search (defaults to all neurons in list) #' @param db \code{neuronlist} to search. Can also be a character vector naming #' the neuronlist. Defaults to \code{options('nat.default.neuronlist')}. #' @param threshold More than this many points must be present in region #' @param invert Whether to return neurons outside the selection box (default #' \code{FALSE}) #' @param rval What to return (character vector, default='names') #' #' @return Character vector of names of selected neurons, neuronlist, or #' data.frame of attached metadata according to the value of \code{rval}. #' @export #' @seealso \code{\link{select3d}, \link{find.soma}, \link{subset.neuronlist}} #' @examples #' \dontrun{ #' plot3d(kcs20) #' # draw a 3D selection e.g. around tip of vertical lobe when ready #' find.neuron(db=kcs20) #' # would return 9 neurons #' # make a standalone selection function #' vertical_lobe=select3d() #' find.neuron(vertical_lobe, db=kcs20) #' # use base::Negate function to invert the selection function #' # i.e. choose neurons that do not overlap the selection region #' find.neuron(Negate(vertical_lobe), db=kcs20) #' } find.neuron<-function(sel3dfun=select3d(), indices=names(db), db=getOption("nat.default.neuronlist"), threshold=0, invert=FALSE, rval=c("names",'data.frame',"neuronlist")){ if(is.null(db)) stop("Please pass a neuronlist in argument db or set options", "(nat.default.neuronlist='myfavneuronlist'). See ?nat for details.") if(is.character(db)) db=get(db) if(!missing(sel3dfun) && !is.function(sel3dfun)) stop("Please provide a selection function!") selfun=function(x){ pointsinside=sel3dfun(na.omit(xyzmatrix(x))) sum(pointsinside, na.rm=T)>threshold } if(invert) selfun=Negate(selfun) rval=match.arg(rval) subset(db, subset=indices, filterfun=selfun, rval=rval) } #' Find neurons with soma inside 3D selection box (usually drawn in rgl window) #' #' @details Can work on \code{neuronlist}s containing \code{neuron} objects #' \emph{or} \code{neuronlist}s whose attached data.frame contains soma #' positions specified in columns called X,Y,Z . #' @inheritParams find.neuron #' @return Character vector of names of selected neurons #' @export #' @seealso \code{\link{select3d}, \link{subset.neuronlist}, \link{find.neuron}} find.soma <- function (sel3dfun = select3d(), indices = names(db), db = getOption("nat.default.neuronlist"), invert=FALSE, rval=c("names", "neuronlist", "data.frame")) { if (is.null(db)) stop("Please pass a neuronlist in argument db or set options", "(nat.default.neuronlist='myfavneuronlist'). See ?nat for details.") if (is.character(db)) db = get(db) df=attr(db, 'df') rval=match.arg(rval) if(all(c("X","Y","Z") %in% colnames(df))){ # assume these represent soma position somapos=df[indices,c("X","Y","Z")] sel_neurons=indices[sel3dfun(somapos)] if(invert) sel_neurons=setdiff(indices, sel_neurons) if(rval=='names') sel_neurons else subset(db, indices=sel_neurons, rval=rval) } else { selfun = function(x) { somapos=x$d[x$StartPoint, c("X","Y","Z")] isTRUE(sel3dfun(somapos)) } if(invert) selfun=Negate(selfun) subset(db, subset = indices, filterfun = selfun, rval = rval) } } #' Scan through a set of neurons, individually plotting each one in 3D #' #' Can also choose to select specific neurons along the way and navigate #' forwards and backwards. #' #' @param neurons a \code{neuronlist} object or a character vector of names of #' neurons to plot from the neuronlist specified by \code{db}. #' @inheritParams plot3d.character #' @param col the color with which to plot the neurons (default \code{'red'}). #' @param Verbose logical indicating that info about each selected neuron should #' be printed (default \code{TRUE}). #' @param Wait logical indicating that there should be a pause between each #' displayed neuron. #' @param sleep time to pause between each displayed neuron when #' \code{Wait=TRUE}. #' @param extrafun an optional function called when each neuron is plotted, with #' two arguments: the current neuron name and the current \code{selected} #' neurons. #' @param selected_file an optional path to a \code{yaml} file that already #' contains a selection. #' @param selected_col the color in which selected neurons (such as those #' specified in \code{selected_file}) should be plotted. #' @param yaml a logical indicating that selections should be saved to disk in #' (human-readable) \code{yaml} rather than (machine-readable) \code{rda} #' format. #' @param ... extra arguments to pass to \code{\link{plot3d}}. #' #' @return A character vector of names of any selected neurons, of length 0 if #' none selected. #' @importFrom yaml yaml.load_file as.yaml #' @seealso \code{\link{plot3d.character}}, \code{\link{plot3d.neuronlist}} #' @export #' @examples #' \dontrun{ #' # scan a neuronlist #' nlscan(kcs20) #' #' # using neuron names #' nlscan(names(kcs20), db=kcs20) #' # equivalently using a default neuron list #' options(nat.default.neuronlist='kcs20') #' nlscan(names(kcs20)) #' } #' # scan without waiting #' nlscan(kcs20[1:4], Wait=FALSE, sleep=0) #' \dontrun{ #' # could select e.g. the gamma neurons with unbranched axons #' gammas=nlscan(kcs20) #' nclear3d() #' plot3d(kcs20[gammas]) #' #' # plot surface model of brain first #' # nb depends on package only available on github #' devtools::install_github(username = "natverse/nat.flybrains") #' library(nat.flybrains) #' plot3d(FCWB) #' # could select e.g. the gamma neurons with unbranched axons #' gammas=nlscan(kcs20) #' #' nclear3d() #' plot3d(kcs20[gammas]) #' } nlscan <- function(neurons, db=NULL, col='red', Verbose=T, Wait=T, sleep=0.1, extrafun=NULL, selected_file=NULL, selected_col='green', yaml=TRUE, ..., plotengine = "rgl") { if(!isTRUE(plotengine=="rgl")) stop("nlscan only supports the rgl plotengine at present!") if(is.neuronlist(neurons)) { db=neurons neurons=names(db) } frames <- length(neurons) if(length(col)==1) col <- rep(col,frames) selected <- character() i <- 1 if(!is.null(selected_file) && file.exists(selected_file)) { selected <- yaml.load_file(selected_file) if(!all(names(selected) %in% neurons)) stop("Mismatch between selection file and neurons.") } savetodisk <- function(selected, selected_file) { if(is.null(selected_file)) selected_file <- file.choose(new=TRUE) if(yaml){ if(!grepl("\\.yaml$",selected_file)) selected_file <- paste(selected_file,sep="",".yaml") message("Saving selection to disk as ", selected_file, ".") writeLines(as.yaml(selected), con=selected_file) } else { if(!grepl("\\.rda$", selected_file)) selected_file <- paste(selected_file, sep="", ".rda") save(selected, file=selected_file) message("Saving selection to disk as ", selected_file) } selected_file } chc <- NULL while(TRUE){ if(i > length(neurons) || i < 1) break n <- neurons[i] cat("Current neuron:", n, "(", i, "/", length(neurons), ")\n") pl <- plot3d(n, db=db, plotengine = plotengine, col=substitute(ifelse(n %in% selected, selected_col, col[i])), ..., SUBSTITUTE=FALSE) # call user supplied function more_rgl_ids <- list() if(!is.null(extrafun)) more_rgl_ids <- extrafun(n, selected=selected) if(Wait){ chc <- readline("Return to continue, b to go back, s to select, d [save to disk], t to stop, c to cancel (without returning a selection): ") if(chc=="c" || chc=='t'){ sapply(pl, pop3d, type='shape') sapply(more_rgl_ids, pop3d, type='shape') break } if(chc=="s") { if(n %in% selected) { message("Deselected: ", n) selected <- setdiff(selected, n) } else selected <- union(selected, n) } if(chc=="b") i <- i-1 else if (chc=='d') savetodisk(selected, selected_file) else i <- i+1 } else { Sys.sleep(sleep) i <- i+1 } sapply(pl, pop3d, type='shape') sapply(more_rgl_ids, pop3d, type='shape') } if(is.null(chc) || chc=='c') return(NULL) if(!is.null(selected_file)) savetodisk(selected, selected_file) selected }
486ae5a58b059238b5689733158f2627f6da5f7d
01f3d2abd6a99a98d3a26441c6508e8994f310d8
/Project.r
848aaa79f1f61680f1d37249409d8f3420cc8fe6
[]
no_license
gauthamsaimr/TimeSeriesAnalysisPanelData
1b453d06b3d0d75b98f1d305df7b3ea0767cf153
83a094fb270cade8b3664cfcc2a78d9f11df77ba
refs/heads/master
2020-06-04T03:18:32.071659
2019-06-14T01:22:22
2019-06-14T01:22:22
191,852,443
1
0
null
null
null
null
UTF-8
R
false
false
9,419
r
Project.r
library(haven) library(data.table) library(ggplot2) library(broom) library(forecast) library(plm) library(margins) library(sandwich) library(lmtest) library(tseries) library(DBI) library(RSQLite) library(tidyverse) library(car) library(TSA) library(deeplr) library(dplyr) library(partykit) mydata<- read_dta("Guns.dta") summary(mydata) qplot(mydata$incarc_rate, geom = 'histogram', binwidth = 2) + xlab('Incarc rate') qplot(mydata$density, geom = 'histogram', binwidth = 1) + xlab('density') ## this tells us that incarc_rate and density are highly skewed and we need to make Log transformations on it corr<-cor(mydata) #we can see that there is high correaltion between pb1064 and pw1064 library(ggcorrplot) ggcorrplot(corr) summary(lm(log(vio)~shall,data = mydata)) coeftest(lm(log(vio)~shall,data=mydata),vcovHC) # rsquare is just 0.08 which is very low #Regression without control variables|^ # we can see that there is 44% reduce in violent crime rates after issuing shall laws # now lets see Regression with Control Variables|> summary(lm(log(vio)~shall+log(incarc_rate)+pop+avginc+log(density)+pb1064+pw1064+pm1029, data=mydata)) coeftest(lm(log(vio)~shall+log(incarc_rate)+pop+avginc+log(density)+pb1064+pw1064+pm1029, data=mydata),vcovHC) # rsquare is 0.6713 # We can see that still there is a large effect with a small drop in the coefficient, which is 28.26% reduce in violent crime rate after issuing shall laws. #correlation cor(mydata$pb1064,mydata$pw1064) #These are highly correlated (-0.98) #Pooled regression data frame gunsvio<-pdata.frame(mydata, index = c("stateid","year")) #violence as Dependent #pooled without Cluster Robust SE vio_polled<-plm(log(vio)~shall+log(incarc_rate)+pb1064+pm1029+pop+avginc+log(density)+pw1064,data=gunsvio, model="pooling") summary(vio_polled) # we see that pb1064 is highly correlated with pw1064 as we saw before so we are removing pw1064 # pooled with cluster Robust and no pb1064 # reason being the OLS estimates of the model are still unbiased and linear but no longer the best and the standard errors are incorrect which makes the confidence intervals and hypothesis tests misleading. vio_polled1<-plm(log(vio)~shall+log(incarc_rate)+pm1029+pop+avginc+log(density)+pb1064,data=gunsvio, model="pooling") summary(vio_polled1) coeftest(vio_polled1,vcovHC) ##We notice that pw1064 is highly insignificant. ##we corrected the OLS standard errors, but these estimates are still not the best as the model is inefficient. ##This could be because of the omitted variable bias. So, we next wanted to implement a fixed effects model which is immune to omitted variable bias from variables that are constant over time and vary between states and not within states. For example, the attitude of the people committing crime or quality of police cannot be quantified using a pooled OLS model where as it won't introduce any bias in a fixed effects model. #Fixed effects without robust SE vio_fixed1<-plm(log(vio)~shall+log(incarc_rate)+pop+avginc+log(density)+pw1064+pb1064+pm1029 ,data=gunsvio, model="within") summary(vio_fixed1) #we see that avginc is insignificant and we check on Ftest Hnull <- c("avginc=0") linearHypothesis(vio_fixed1,Hnull) #this shows that avginc is insignificant and we can drop vio_fixed2<-plm(log(vio)~shall+log(incarc_rate)+pop+log(density)+pw1064++pb1064+pm1029 ,data=gunsvio, model="within") summary(vio_fixed2) # do the interpretations #We are not planning to use Cluster Robust Standard errors for Entity Fixed effects because fixed effects controls for omitted variable bias because of variables that are constant over time and change with states. #Still there can be omitted variables which can possibly vary over time but are constant across states. We then implemented used entity fixed and time fixed effects model to address the bias from such omitted variables. #fixed effects with time vio_fixed3 <- plm(log(vio)~shall+log(incarc_rate)+pop+avginc+log(density)+pb1064+pm1029+pw1064+factor(year)-1, data=gunsvio, model="within") summary(vio_fixed3) Hnull <- c("pb1064=0","pop=0","avginc=0","pw1064=0") linearHypothesis(vio_fixed3,Hnull) vio_fixed4 <- plm(log(vio)~log(incarc_rate)+pm1029+log(density)+shall+factor(year)-1, data=gunsvio, model="within") summary(vio_fixed4) #{r murder} mydata<- read_dta("Guns.dta") summary(mydata) summary(lm(log(mur)~shall,data = mydata)) coeftest(lm(log(mur)~shall,data=mydata),vcovHC) # rsquare is just 0.08 which is very low with 47% decrease in violent crime and is highly significant summary(lm(log(mur)~shall+log(incarc_rate)+pop+avginc+log(density)+pb1064+pw1064+pm1029, data=mydata)) coeftest(lm(log(mur)~shall+log(incarc_rate)+pop+avginc+log(density)+pb1064+pw1064+pm1029, data=mydata),vcovHC) # r square is 0.64 and the coefficient has reduced to 21% and still significant ## pooled ols without cluster Robust SE gunsmur<-pdata.frame(mydata, index = c("stateid","year")) mur_pooled<-plm(log(mur)~shall+log(incarc_rate)+pb1064+pm1029+pop+avginc+log(density)+pw1064,data=gunsmur, model="pooling") summary(mur_pooled) ##We have observed that "pw1064" is insignificant and it might be because of high correlation with "pb1064", which has been observed earlier. Therefore, removing "pw1064" and executing pooled model. ##pooled ols without pw1064 mur_pooled<-plm(log(mur)~shall+log(incarc_rate)+pb1064+pm1029+pop+avginc+log(density),data=gunsmur, model="pooling") summary(mur_pooled) # there is a decrease n murder rate ##lets check for CLuster Robust coeftest(mur_pooled,vcovHC) ## now we see that pb1064 is insignificant ##Using the robust standard errors, we corrected the OLS standard errors but these estimates are still not the best as the model is inefficient. This could be because of the omitted variable bias. So, we next wanted to implement a fixed effects model which is immune to omitted variable bias from variables that are constant over time and vary between states and not within states ##state fixed entity effect mur_fixed<-plm(log(mur)~shall+log(incarc_rate)+pb1064+pm1029+pop+avginc+log(density),data=gunsmur, model="within") summary(mur_fixed) ##Pm1029 and pop are insignificant. Hnull <- c("pm1029=0","pop=0") linearHypothesis(mur_fixed,Hnull) #drop these 2 mur_fixed1<-plm(log(mur)~shall+log(incarc_rate)+pb1064+avginc+log(density),data=gunsmur, model="within") summary(mur_fixed1) #interpret ## Fixed Time effect mur_fixed2<-plm(log(mur)~shall+log(incarc_rate)+pb1064+pm1029+avginc+log(density)+factor(year)-1,data=gunsmur, model="within") summary(mur_fixed2) #shall is insignificant ##We further wanted to address any bias from unobserved omitted variables. So, we decided to try and implement Random effects model. But we saw that the data is not collected using random sampling. So, we should not implement Random effects model. \ #---------------robbery--------- mydata<- read_dta("Guns.dta") summary(mydata) summary(lm(log(rob)~shall,data = mydata)) coeftest(lm(log(rob)~shall,data=mydata),vcovHC) # rsquare is just 0.12 which is very low with 77% decrease in robbery crime and is highly significant summary(lm(log(rob)~shall+log(incarc_rate)+pop+avginc+log(density)+pb1064+pw1064+pm1029, data=mydata)) coeftest(lm(log(rob)~shall+log(incarc_rate)+pop+avginc+log(density)+pb1064+pw1064+pm1029, data=mydata),vcovHC) # rsquare is 0.6899 with a decrease of 41% in robbery crime and is highly significant ##pooled ols without Robust SE gunsrob<-pdata.frame(mydata, index = c("stateid","year")) rob_pooled<-plm(log(rob)~shall+log(incarc_rate)+pb1064+pm1029+pop+avginc+log(density)+pw1064,data=gunsrob, model="pooling") summary(rob_pooled) #We have observed that "pw1064" is insignificant and it might be because of high correlation with "pb1064", which has been observed earlier. Therefore, removing "pw1064" and executing pooled model. rob_pooled1<-plm(log(rob)~shall+log(incarc_rate)+pb1064+pm1029+pop+avginc+log(density),data=gunsrob, model="pooling") summary(rob_pooled1) ##heterosckedasticity coeftest(rob_pooled1,vcovHC) ##Only "pb1064" becomes insignificant at p value of 0.1 #Using the robust standard errors, we corrected the OLS standard errors but these estimates are still not the best as the model is inefficient. This could be because of the omitted variable bias. So, we next wanted to implement a fixed effects model which is immune to omitted variable bias from variables that are constant over time and vary between states and not within states. #state Fixed entity effect rob_fixed<-plm(log(rob)~shall+log(incarc_rate)+pb1064+pm1029+pop+avginc+log(density),data=gunsrob, model="within") summary(rob_fixed) #after testing for all insignificant variables on Ftest we remove them rob_fixed1<-plm(log(rob)~shall+log(incarc_rate)+pb1064,data=gunsrob, model="within") summary(rob_fixed1) ##After controlling for entity fixed effects, the direction of impact of log (incarceration_rate) has changed in comparison to the pooled model. Controlling for omitted variables bias has led to this change. ##fixed time and entity rob_fixed2<-plm(log(rob)~shall+log(incarc_rate)+pb1064+pm1029+avginc+log(density)+factor(year)-1,data=gunsrob, model="within") summary(rob_fixed2) #shall variable is insignificant #analysis on murder rate
2ae390c37aa9798c221c6971d85c73aea786e4db
bf8802140cc5e08b9e0a9abcb060f2e15eb83b55
/man/cvglasso.Rd
2edbbd6f2095553001f72326739c702ee35d6a82
[]
no_license
cran/robustcov
b2415fa2d141a74ef54d49471dd26983f6276b46
35d25b8a3df67f09172ee1dbb74ffa1a3a0af669
refs/heads/master
2023-07-08T16:52:39.466320
2021-08-04T09:00:05
2021-08-04T09:00:05
392,744,128
0
0
null
null
null
null
UTF-8
R
false
true
1,035
rd
cvglasso.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/glasso_CV.R \name{cvglasso} \alias{cvglasso} \title{Cross validation to chose tuning parameter of glasso} \usage{ cvglasso( data, k = 10, covest = cov, rhos = seq(0.1, 1, 0.1), evaluation = negLLrobOmega, ... ) } \arguments{ \item{data}{The full dataset, should be a matrix or a data.frame, row as sample} \item{k}{number of folds} \item{covest}{a *function* or name of a function (string) that takes a matrix to estimate covariance} \item{rhos}{a vector of tuning parameter to be tested} \item{evaluation}{a *function* or name of a function (string) that takes only two arguments, the estimated covariance and the test covariance, when NULL, we use negative log likelihood on test sets} \item{...}{extra arguments send to glasso} } \value{ a matrix with k rows, each row is the evaluation loss of that fold } \description{ This routine use k fold cross validation to chose tuning parameter } \examples{ cvglasso(matrix(rnorm(100),20,5)) }
254f0ae649cd1c98d1dc54b97372a965bd7a7334
9b62eff47bbe5b29e362778d855bd7eac1ee7595
/man/launch_shinytmb.Rd
e442c979c2e755dfd88ab066fe31aa45f133a2a7
[]
no_license
jmannseth/adnuts
2876ff9d3993b68235de3d2b01e136160e1b4610
055fa3e5899c0d521607c0aa05a3d673e2af8cd1
refs/heads/master
2021-06-21T03:33:59.678604
2017-08-18T21:26:48
2017-08-18T21:26:48
null
0
0
null
null
null
null
UTF-8
R
false
true
465
rd
launch_shinytmb.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/helper.R \name{launch_shinytmb} \alias{launch_shinytmb} \title{A high level wrapper to launch shinystan for a TMB fit.} \usage{ launch_shinytmb(fit) } \arguments{ \item{fit}{A named list returned by \code{sample_tmb}.} } \description{ A high level wrapper to launch shinystan for a TMB fit. } \details{ This function simply calls \code{launch_shinystan(as.shinystan.tmb(tmb.fit))}. }
a07c60aa60b6a23a55f6b7ee9b9fca472ed20891
538e7a274b5e7442b61d03df954e1355d2ebe683
/R/CI_script_transform.R
2af996a40697fffb6227e7156b1ef2957a35e763
[]
no_license
WilliamsPaleoLab/Farley_Optimizing_Computing_SDMs
7fdbe26c620dcadc136f01e4826234ffabd27e38
0613a8d2274078d9c7de422c0cdb0441bf11db9e
refs/heads/master
2021-06-18T20:47:28.320997
2017-05-12T17:50:32
2017-05-12T17:50:32
58,968,939
0
0
null
null
null
null
UTF-8
R
false
false
5,325
r
CI_script_transform.R
library(plyr) con <- dbConnect(dbDriver("MySQL"), host='104.154.235.236', password = 'Thesis-Scripting123!', dbname='timeSDM', username='Scripting') ## get results from database r <- dbGetQuery(con, "Select * From Experiments Inner Join Results on Results.experimentID = Experiments.experimentID WHERE experimentStatus = 'DONE' AND cores < 8 AND model = 'GBM-BRT' OR model='GAM' OR model = 'MARS';") ## separate models r.brt <- r[which(r$model == 'GBM-BRT'), ] r.gam <- r[which(r$model == 'GAM'), ] r.mars <- r[which(r$model == 'MARS'), ] f <- as.formula(log(totalTime) ~ cores + GBMemory + (cores * GBMemory) + trainingExamples + spatialResolution) ## build testing and training set r.brt.testingInd <- sample(nrow(r.brt), 100) r.brt.testing <- r.brt[r.brt.testingInd, ] r.brt.training <- r.brt[-r.brt.testingInd, ] r.gam.testingInd <- sample(nrow(r.gam), 100) r.gam.testing <- r.gam[r.gam.testingInd, ] r.gam.training <- r.gam[-r.gam.testingInd, ] r.mars.testingInd <- sample(nrow(r.mars), 100) r.mars.testing <- r.mars[r.mars.testingInd, ] r.mars.training <- r.mars[-r.mars.testingInd, ] ## build the GBM models library(gbm) r.brt.brt <- gbm(f, data=r.brt.training, n.trees = 15000, bag.fraction = 0.75) r.gam.brt <- gbm(f, data=r.gam.training, n.trees = 15000, bag.fraction = 0.75) r.mars.brt <- gbm(f, data=r.mars.training, n.trees = 15000, bag.fraction = 0.75) ## predict the results # find best iteration r.brt.brt.bestIter <- gbm.perf(r.brt.brt) r.gam.brt.bestIter <- gbm.perf(r.gam.brt) r.mars.brt.bestIter <- gbm.perf(r.mars.brt) r.brt.brt.predict = predict(r.brt.brt, r.brt.testing, n.trees = r.brt.brt.bestIter) r.gam.brt.predict = predict(r.gam.brt, r.gam.testing, n.trees = r.gam.brt.bestIter) r.mars.brt.predict = predict(r.mars.brt, r.mars.testing, n.trees = r.mars.brt.bestIter) ## evaluate the prediction cor(r.brt.brt.predict, log(r.brt.testing$totalTime)) cor(r.gam.brt.predict, log(r.gam.testing$totalTime)) cor(r.mars.brt.predict, log(r.mars.testing$totalTime)) r.brt.brt.delta <- r.brt.brt.predict - log(r.brt.testing$totalTime) r.gam.brt.delta <- r.gam.brt.predict - log(r.gam.testing$totalTime) r.mars.brt.delta <- r.mars.brt.predict - log(r.mars.testing$totalTime) mean(r.brt.brt.delta) mean(r.gam.brt.delta) mean(r.mars.brt.delta) sd(r.brt.brt.delta) sd(r.gam.brt.delta) sd(r.mars.brt.delta) plot(r.brt.brt.predict ~ log(r.brt.testing$totalTime), main='Performance Model (GBM)', xlab='log(Observed Execution Time) [Seconds]', ylab='Predicted Execution Time [Seconds]', pch=3, col='darkgreen') points(r.gam.brt.predict ~ log(r.gam.testing$totalTime), pch=3, col='darkred') points(r.mars.brt.predict ~ log(r.mars.testing$totalTime), pch=3, col='dodgerblue') legend('bottomright', c('GBM-BRT', 'GAM', 'MARS'), col=c('darkgreen', 'darkred', 'dodgerblue'), pch=3) abline(0, 1) ## Build the linear models r.brt.lm <- lm(f, data=r.brt.training) r.gam.lm <- lm(f, data=r.gam.training) r.mars.lm <- lm(f, data=r.mars.training) ## predict r.brt.lm.predict = predict(r.brt.lm, r.brt.testing) r.gam.lm.predict = predict(r.gam.lm, r.gam.testing) r.mars.lm.predict = predict(r.mars.lm, r.mars.testing) ## evaluate the prediction cor(r.brt.lm.predict, log(r.brt.testing$totalTime)) cor(r.gam.lm.predict, log(r.gam.testing$totalTime)) cor(r.mars.lm.predict, log(r.mars.testing$totalTime)) r.brt.lm.delta <- r.brt.lm.predict - log(r.brt.testing$totalTime) r.gam.lm.delta <- r.gam.lm.predict - log(r.gam.testing$totalTime) r.mars.lm.delta <- r.mars.brt.predict - log(r.mars.testing$totalTime) mean(r.brt.lm.delta) mean(r.gam.lm.delta) mean(r.mars.lm.delta) sd(r.brt.lm.delta) sd(r.gam.lm.delta) sd(r.mars.lm.delta) plot(r.brt.lm.predict ~ log(r.brt.testing$totalTime), main='Performance Model (Linear Model)', xlab='log(Observed Execution Time) [Seconds]', ylab='Predicted Execution Time [Seconds]', pch=3, col='darkgreen') points(r.gam.lm.predict ~ log(r.gam.testing$totalTime), pch=3, col='darkred') points(r.mars.lm.predict ~ log(r.mars.testing$totalTime), pch=3, col='dodgerblue') legend('bottomright', c('GBM-BRT', 'GAM', 'MARS'), col=c('darkgreen', 'darkred', 'dodgerblue'), pch=3) abline(0, 1) ## build accuracy prediction a <- dbGetQuery(con, "Select * From Experiments Inner Join Results on Results.experimentID = Experiments.experimentID WHERE experimentStatus = 'DONE' and experimentCategory = 'nSensitivity';") a.testingInd = sample(nrow(a), 75) a.testing <- a[a.testingInd, ] a.training <- a[-a.testingInd, ] a.gbm <- gbm(testingAUC ~ trainingExamples, data=a.training, n.trees = 15000) a.gbm.bestIter <- gbm.perf(a.gbm) a.gbm.predict <- predict(a.gbm, a.testing, n.trees = a.gbm.bestIter) cor(a.gbm.predict, a.testing$testingAUC) a.gbm.delta <- a.gbm.predict - a.testing$testingAUC mean(a.gbm.delta) a.s <- ddply(a, .(cores, GBMemory, trainingExamples, taxon, cellID, spatialResolution),summarise, var = var(testingAUC), sd=sd(testingAUC), mean=mean(testingAUC), median=median(testingAUC)) plot(a.gbm, n.trees=a.gbm.bestIter, main='AUC Accuracy of GBM-BRT SDM', xlim=c(0, 10000)) points(a.training$testingAUC ~ a.training$trainingExamples, col=rgb(0.5, 0.5, 0, 0.5)) #points(a.s$median ~ a.s$trainingExamples, col=rgb(0.5, 0.5, 0, 1)) legend('bottomright', c('Observed Values', 'Predictive Model'), col=c(rgb(0.5, 0.5, 0), 'black'), lty=c(NA, 1), pch=c(1, NA))
8fee2ebed7a3fde56c2128d9e702db09d45fd52e
bb3fd8e814b3210022371974c95684066034ec39
/man/slide2.Rd
953808050518272a24646247ada7e2070fd0a955
[]
no_license
xtmgah/tsibble
34f9990f5db6c39552e446ebee7b399d05fa12b2
1c5ec296036d86cae1a4c24bc01fa9e676cd63ed
refs/heads/master
2020-03-23T00:40:20.332753
2018-07-13T13:06:38
2018-07-13T13:06:38
null
0
0
null
null
null
null
UTF-8
R
false
true
3,917
rd
slide2.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/slide.R \name{slide2} \alias{slide2} \alias{slide2} \alias{slide2_dfr} \alias{slide2_dfc} \alias{pslide} \alias{pslide} \alias{pslide_dfr} \alias{pslide_dfc} \title{Sliding window calculation over multiple inputs simultaneously} \usage{ slide2(.x, .y, .f, ..., .size = 1, .fill = NA, .partial = FALSE) slide2_dfr(.x, .y, .f, ..., .size = 1, .fill = NA, .partial = FALSE, .id = NULL) slide2_dfc(.x, .y, .f, ..., .size = 1, .fill = NA, .partial = FALSE) pslide(.l, .f, ..., .size = 1, .fill = NA, .partial = FALSE) pslide_dfr(.l, .f, ..., .size = 1, .fill = NA, .partial = FALSE, .id = NULL) pslide_dfc(.l, .f, ..., .size = 1, .fill = NA, .partial = FALSE) } \arguments{ \item{.x, .y}{Objects to slide over simultaneously.} \item{.f}{A function, formula, or atomic vector. If a \strong{function}, it is used as is. If a \strong{formula}, e.g. \code{~ .x + 2}, it is converted to a function. There are three ways to refer to the arguments: \itemize{ \item For a single argument function, use \code{.} \item For a two argument function, use \code{.x} and \code{.y} \item For more arguments, use \code{..1}, \code{..2}, \code{..3} etc } This syntax allows you to create very compact anonymous functions. If \strong{character vector}, \strong{numeric vector}, or \strong{list}, it is converted to an extractor function. Character vectors index by name and numeric vectors index by position; use a list to index by position and name at different levels. Within a list, wrap strings in \code{\link[=get-attr]{get-attr()}} to extract named attributes. If a component is not present, the value of \code{.default} will be returned.} \item{...}{Additional arguments passed on to \code{.f}.} \item{.size}{An integer for window size. If positive, moving forward from left to right; if negative, moving backward (from right to left).} \item{.fill}{A single value or data frame to replace \code{NA}.} \item{.partial}{if \code{TRUE}, partial sliding.} \item{.id}{If not \code{NULL} a variable with this name will be created giving either the name or the index of the data frame.} \item{.l}{A list of lists. The length of \code{.l} determines the number of arguments that \code{.f} will be called with. List names will be used if present.} } \description{ Rolling window with overlapping observations: \itemize{ \item \code{slide2()} and \code{pslide()} always returns a list. \item \code{slide2_lgl()}, \code{slide2_int()}, \code{slide2_dbl()}, \code{slide2_chr()} use the same arguments as \code{slide2()}, but return vectors of the corresponding type. \item \code{slide2_dfr()} \code{slide2_dfc()} return data frames using row-binding & column-binding. } } \examples{ .x <- 1:5 .y <- 6:10 .z <- 11:15 .lst <- list(x = .x, y = .y, z = .z) .df <- as.data.frame(.lst) slide2(.x, .y, sum, .size = 2) slide2(.lst, .lst, ~ ., .size = 2) slide2(.df, .df, ~ ., .size = 2) pslide(.lst, ~ ., size = 1) pslide(list(.lst, .lst), ~ ., .size = 2) ## window over 2 months pedestrian \%>\% filter(Sensor == "Southern Cross Station") \%>\% index_by(yrmth = yearmonth(Date_Time)) \%>\% nest(-yrmth) \%>\% mutate(ma = slide_dbl(data, ~ mean(do.call(rbind, .)$Count), .size = 2)) # row-oriented workflow \dontrun{ my_diag <- function(...) { data <- list(...) fit <- lm(data$Count ~ data$Time) tibble::tibble(fitted = fitted(fit), resid = residuals(fit)) } pedestrian \%>\% filter(Date <= as.Date("2015-01-31")) \%>\% nest(-Sensor) \%>\% mutate(diag = purrr::map(data, ~ pslide_dfr(., my_diag, .size = 48))) } } \seealso{ \itemize{ \item \link{slide} \item \link{tile2} for tiling window without overlapping observations \item \link{stretch2} for expanding more observations } } \alias{slide2_lgl} \alias{slide2_chr} \alias{slide2_int} \alias{slide2_dbl} \alias{pslide_lgl} \alias{pslide_chr} \alias{pslide_int} \alias{pslide_dbl}
71ffa13e50e7599dbd37d0e8ea2f5b0474792412
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/flux/examples/plot.reco.Rd.R
b6b22eac0898e96bd7b000a297a8220e26abe86a
[]
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
173
r
plot.reco.Rd.R
library(flux) ### Name: plot.reco ### Title: Plot diagnostic plots for Reco models. ### Aliases: plot.reco ### Keywords: hplot ### ** Examples ## see examples at gpp
525010b2e0ac02ed11cca4340dd52417a339d99e
510e69ed40a0db235877d7f5e531ddbd2e118af6
/Copy_MySQL_2_CBIPMySQL.R
61db7a2bde4c9310945d97661417f95504d2d36b
[]
no_license
predsci/Climate_Data-BSVE
fd2afcf2c6f79cdc9d0527f7a49db742d2d7b0e0
656050ad249849c0a34bdfc42c7102c71364a259
refs/heads/master
2020-04-17T09:20:34.404417
2019-06-24T18:33:46
2019-06-24T18:33:46
166,454,178
0
0
null
null
null
null
UTF-8
R
false
false
17,164
r
Copy_MySQL_2_CBIPMySQL.R
rm(list=ls()) # require(DICE) require(dplyr) require(lubridate) require(RMySQL) # require(RPostgreSQL) # load functions for opening connections # source("~/Dropbox/MyLEPR/SQL/BSVE/containers/docker-NOAA_proc/source/NOAA_Funs.R") source("/home/source/NOAA_Funs.R") MySQLdb = OpenCon("predsci") # CBIP_db = OpenCon("dcs_aws") CBIP_db = OpenCon("cbip") updt_dep_table <- function(table_name=NULL, ref_cols=NULL, data_cols=NULL, table_data=NULL, table_data2=NULL, P_SQLdb=NULL) { # determine rows of table_data that are not in table_data2 append_rows = anti_join(x=table_data, y=table_data2, by=ref_cols) if (nrow(append_rows)>0) { # append to database dbWriteTable(CBIP_db, name=table_name, value=append_rows, row.names=FALSE, overwrite=F, append=T) } # determine rows that overlap (and keep data cols from table_data) update_rows = semi_join(x=table_data, y=table_data2, by=ref_cols) # map overlap rows outer_mat = matrix(TRUE, nrow=nrow(update_rows), ncol=nrow(table_data2)) for (var in ref_cols) { outer_mat = outer_mat & outer(update_rows[[var]], table_data2[[var]], "==") } match_ind = which(outer_mat, arr.ind=T) # test rows for equality for (ii in 1:nrow(match_ind)) { is_equal = update_rows[match_ind[ii, 1], data_cols] == table_data2[match_ind[ii, 2], data_cols] if (any(!is_equal)) { write_vars = update_rows[match_ind[ii, 1], data_cols[!is_equal]] char_vars = unlist(lapply(write_vars, FUN=is.character)) write_vars[char_vars] = paste0("'", write_vars[char_vars], "'") set_char = paste0(data_cols[!is_equal], " = ", write_vars) set_char = paste(set_char, collapse=", ") where_vars = update_rows[match_ind[ii, 1], ref_cols] char_vars = unlist(lapply(where_vars, FUN=is.character)) nchar_vars = sum(char_vars) if (nchar_vars>0) { jj = which(char_vars)[1] where_char = paste0(ref_cols[jj], " = '", where_vars[jj], "'") if (nchar_vars>1) { for (jj in which(char_vars)[2:nchar_vars]) { where_char = paste0(where_char, " AND ", ref_cols[jj], " = '", where_vars[jj], "'") } } } nnum_vars = sum(!char_vars) if (nnum_vars>0) { jj = which(!char_vars)[1] if (nchar_vars>0) { where_char = paste0(where_char, " AND ", ref_cols[jj], " = ", where_vars[jj]) } else { where_char = paste0(ref_cols[jj], " = ", where_vars[jj]) } if (nnum_vars>1) { for (jj in which(!char_vars)[2:nnum_vars]) { where_char = paste0(where_char, " AND ", ref_cols[jj], " = ", where_vars[jj]) } } } dbExecute(conn=CBIP_db, statement=paste0("UPDATE ", table_name ," SET ", set_char, " WHERE ", where_char, ";")) } } } table_name = "data_sources" cat("Updating table ", table_name, ". \n", sep="") ref_cols = c("source_key", "cadence", "disease") data_cols = c("source", "source_abbv", "source_desc", "data_cols", "col_names", "col_units", "bsve_use", "countries", "max_lev") table_data = dbReadTable(MySQLdb, table_name) # table_data$bsve_use = as.logical(table_data$bsve_use) # remove Quidel entry table_data = table_data[table_data$source_abbv!="quidel", ] if (!dbExistsTable(CBIP_db, table_name)) { # Create and populate table dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE ",table_name ," ( source_key SMALLINT PRIMARY KEY, cadence SMALLINT NOT NULL, disease VARCHAR(50), source TEXT, source_abbv VARCHAR(50), source_desc VARCHAR(255), data_cols SMALLINT, col_names VARCHAR(255), col_units VARCHAR(255), bsve_use TINYINT, countries VARCHAR(765), max_lev SMALLINT, min_lev SMALLINT );")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { # read existing table table_data2 = dbReadTable(CBIP_db, table_name) # perform table update updt_dep_table(table_name=table_name, ref_cols=ref_cols, data_cols=data_cols, table_data=table_data, table_data2=table_data2, P_SQLdb=CBIP_db) } table_name = "clim_by_disease" cat("Updating table ", table_name, ". \n", sep="") ref_cols = c("disease") data_cols = c("n_clim", "clim_names") table_data = dbReadTable(MySQLdb, table_name) clim_by_disease = table_data if (!dbExistsTable(CBIP_db, table_name)) { # dbExecute(conn=CBIP_db, statement=paste0("DROP TABLE IF EXISTS ", table_name)) dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE ",table_name ," ( disease VARCHAR(15) PRIMARY KEY, n_clim SMALLINT NOT NULL, clim_names VARCHAR(50) );")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { # read existing table table_data2 = dbReadTable(CBIP_db, table_name) # perform table update updt_dep_table(table_name=table_name, ref_cols=ref_cols, data_cols=data_cols, table_data=table_data, table_data2=table_data2, P_SQLdb=CBIP_db) } table_name = "transmission_names" cat("Updating table ", table_name, ". \n", sep="") ref_cols = c("trans_abbv") data_cols = c("trans_desc") table_data = dbReadTable(MySQLdb, table_name) if (!dbExistsTable(CBIP_db, table_name)) { dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE ",table_name ," ( trans_abbv VARCHAR(5) PRIMARY KEY, trans_desc VARCHAR(50) NOT NULL );")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { # read existing table table_data2 = dbReadTable(CBIP_db, table_name) # perform table update updt_dep_table(table_name=table_name, ref_cols=ref_cols, data_cols=data_cols, table_data=table_data, table_data2=table_data2, P_SQLdb=CBIP_db) } table_name = "disease_transmission" cat("Updating table ", table_name, ". \n", sep="") ref_cols = c("dtype_id", "disease_abbv") data_cols = c("disease_desc", "trans_abbv") table_data = dbReadTable(MySQLdb, table_name) diseases = table_data$disease_abbv if (!dbExistsTable(CBIP_db, table_name)) { dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE ",table_name ," ( dtype_id SERIAL, disease_abbv VARCHAR(15) UNIQUE NOT NULL, disease_desc VARCHAR(50) NOT NULL, trans_abbv VARCHAR(5) REFERENCES transmission_names (trans_abbv), ui_name VARCHAR(30), PRIMARY KEY (dtype_id, disease_abbv) );")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { # read existing table table_data2 = dbReadTable(CBIP_db, table_name) # perform table update updt_dep_table(table_name=table_name, ref_cols=ref_cols, data_cols=data_cols, table_data=table_data, table_data2=table_data2, P_SQLdb=CBIP_db) } table_name = "unit_types" cat("Updating table ", table_name, ". \n", sep="") ref_cols = c("unit_key", "unit_type") data_cols = c("factor", "aggregate_method") table_data = dbReadTable(MySQLdb, table_name) if (!dbExistsTable(CBIP_db, table_name)) { dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE ",table_name ," ( unit_key serial PRIMARY KEY, unit_type VARCHAR(50) NOT NULL, factor VARCHAR(200), aggregate_method VARCHAR(25), UNIQUE INDEX (unit_type) );")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { # read existing table table_data2 = dbReadTable(CBIP_db, table_name) # perform table update updt_dep_table(table_name=table_name, ref_cols=ref_cols, data_cols=data_cols, table_data=table_data, table_data2=table_data2, P_SQLdb=CBIP_db) } table_name = "col_units" cat("Updating table ", table_name, ". \n", sep="") ref_cols = c("col_key", "col_unit") data_cols = c("unit_type") table_data = dbReadTable(MySQLdb, table_name) if (!dbExistsTable(CBIP_db, table_name)) { dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE ",table_name ," ( col_key SERIAL PRIMARY KEY, col_unit VARCHAR(50) NOT NULL, unit_type VARCHAR(50) NOT NULL, FOREIGN KEY (unit_type) REFERENCES unit_types(unit_type) );")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { # read existing table table_data2 = dbReadTable(CBIP_db, table_name) # perform table update updt_dep_table(table_name=table_name, ref_cols=ref_cols, data_cols=data_cols, table_data=table_data, table_data2=table_data2, P_SQLdb=CBIP_db) } table_name = "season_se_dates" cat("Updating table ", table_name, ". \n", sep="") ref_cols = c("abbv_1", "abbv_2", "season", "disease", "cadence") data_cols = c("start_date", "end_date") table_data = dbReadTable(MySQLdb, table_name) # names(table_data) = tolower(names(table_data)) if (!dbExistsTable(CBIP_db, table_name)) { dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE ",table_name ," ( ABBV_1 CHAR(2) NOT NULL, ABBV_2 VARCHAR(10) NOT NULL, season SMALLINT NOT NULL, disease VARCHAR(15) REFERENCES disease_transmission (disease_abbv), cadence SMALLINT NOT NULL, start_date DATE NOT NULL, end_date DATE NOT NULL, PRIMARY KEY (ABBV_1, ABBV_2, season, disease, cadence) );")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { # read existing table table_data2 = dbReadTable(CBIP_db, table_name) # perform table update updt_dep_table(table_name=table_name, ref_cols=ref_cols, data_cols=data_cols, table_data=table_data, table_data2=table_data2, P_SQLdb=CBIP_db) } for (disease in diseases) { # update incidence data # The data itself can be updated in weird ways, with cases being added or deleted at various intervals after the initial report. For this reason, we simply truncate and re-write the entire table. table_name = paste0(disease, "_data") cat("Updating table ", table_name, ". \n", sep="") table_data = dbReadTable(MySQLdb, table_name) if (dbExistsTable(conn=CBIP_db, name=table_name)) { dbExecute(conn=CBIP_db, statement=paste0("TRUNCATE TABLE ", table_name)) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { # clim_cols = strsplit(clim_by_disease$clim_names[clim_by_disease$disease==disease], ";")[[1]] data_cols = sum(substr(names(table_data), start=1,stop=4)=="data") dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE ",table_name ," ( master_key CHAR(8) NOT NULL, source_key SMALLINT NOT NULL, date DATE NOT NULL, ", paste0("data", 1:data_cols, " REAL", collapse=", "), ", PRIMARY KEY (master_key, source_key, date) );")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } table_name = paste0(disease, "_lut") table_data = dbReadTable(MySQLdb, table_name) # names(table_data) = tolower(names(table_data)) if (dbExistsTable(conn=CBIP_db, name=table_name)) { dbExecute(conn=CBIP_db, statement=paste0("TRUNCATE TABLE ", table_name)) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { spatial_levels = sum(substr(names(table_data), start=1, stop=4)=="name") dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE ",table_name ," ( identifier VARCHAR(50) PRIMARY KEY, level SMALLINT NOT NULL, ", paste0("NAME_", 1:spatial_levels, " VARCHAR(50) \n", collapse=", "),", ", paste0("ID_", 1:spatial_levels, " REAL \n", collapse=", "),", ", paste0("ABBV_", 1:spatial_levels, " VARCHAR(10) \n", collapse=", "),", inc_key INTEGER NOT NULL, master_key CHAR(8) UNIQUE NOT NULL, gadm_name VARCHAR(50), gadm_lvl SMALLINT, clim_ident VARCHAR(50) NOT NULL, gadm_noaa_sedac_ident VARCHAR(30), gadm_lat REAL, gadm_lon REAL, gadm_area REAL, sedac_lat REAL, sedac_lon REAL, sedac_pop INT );")) # Also create index on master_key. Additional indices.....? dbExecute(conn=CBIP_db, statement=paste0("CREATE UNIQUE INDEX ", disease,"_key_idx ON ",table_name ," (master_key)")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } } # school schedule tables for (cadence in c("daily", "weekly", "monthly")) { table_name = paste0("school_", cadence) cat("Updating table ", table_name, ". \n", sep="") table_data = dbReadTable(MySQLdb, table_name) if (dbExistsTable(conn=CBIP_db, name=table_name)) { dbExecute(conn=CBIP_db, statement=paste0("TRUNCATE TABLE ", table_name)) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE school_weekly ( master_key CHAR(8) NOT NULL, date DATE NOT NULL, school REAL, PRIMARY KEY (master_key, date) );")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } } # population table table_name = "pop_yearly" cat("Updating table ", table_name, ". \n", sep="") ref_cols = c("master_key", "date") data_cols = c("pop") table_data = dbReadTable(MySQLdb, table_name) if (!dbExistsTable(CBIP_db, table_name)) { dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE ",table_name ," ( master_key CHAR(8) NOT NULL, date DATE NOT NULL, pop INT NULL, PRIMARY KEY (master_key, date) );")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { dbExecute(conn=CBIP_db, statement=paste0("TRUNCATE TABLE ", table_name)) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } # season onset table_name = "season_onset" cat("Updating table ", table_name, ". \n", sep="") ref_cols = c("master_key", "year") data_cols = c("onset") table_data = dbReadTable(MySQLdb, table_name) if (!dbExistsTable(CBIP_db, table_name)) { dbExecute(conn=CBIP_db, statement=paste0("CREATE TABLE ",table_name ," ( master_key CHAR(8) NOT NULL, year INT NOT NULL, onset REAL NULL, PRIMARY KEY (master_key, year) );")) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } else { dbExecute(conn=CBIP_db, statement=paste0("TRUNCATE TABLE ", table_name)) dbWriteTable(CBIP_db, name=table_name, value=table_data, row.names=FALSE, overwrite=F, append=T) } dbDisconnect(conn=CBIP_db) dbDisconnect(MySQLdb)
09362ea0de0e86f189b4f02723b5b50897347b61
124e3a9cd70c301798fa4201a6ccd27e3c15e7dc
/Data Cleaning/clean_subnational_ihme.R
9f6c7f79a24c1f1c29b4774ee19c15f0be04f587
[]
no_license
shinnakayama/aquatic_food_justice_model
540b195b6f54dacac51917eb876d7351ebeddaf5
86d3bbc886e6fab3fbaf90880dcb10f0a2027453
refs/heads/master
2023-01-25T03:22:22.722033
2020-12-07T03:00:49
2020-12-07T03:00:49
null
0
0
null
null
null
null
UTF-8
R
false
false
3,591
r
clean_subnational_ihme.R
####################### # Extracting and cleaning harmonized nighttime lights data # Zach Koehn # zkoehn@stanford.edu ####################### library(tidyverse) library(pbapply) library(countrycode) library(raster) library(sf) library(spData) library(exactextractr) library(viridis) library(readxl) library(rnaturalearth) library(rnaturalearthhires) # read in data # data from Table S2 in https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0228912#sec010 directory <- "/Volumes/GoogleDrive/My Drive/BFA_Papers/BFA_Justice/section_model/aquatic_food_justice_model" rasterOptions(progress = 'text',timer=TRUE) #allows for progress timer... helps multitask :) ihme_second_women_15to49 <- read.csv( file.path( directory, "data", "data_raw", "ihme", "educational_attainment", "Data [CSV]", "IHME_LMIC_EDU_2000_2017_SECONDARYPROP_15_49_FEMALE_AD1_Y2019M12D24.CSV" ) ) sub_gis <- ne_states() #subnational polygons ihme_second_men_15to49 <- read.csv( file.path( directory, "data", "data_raw", "ihme", "educational_attainment", "Data [CSV]", "IHME_LMIC_EDU_2000_2017_SECONDARYPROP_15_49_MALE_AD1_Y2019M12D24.CSV" ) ) rast_ihme_second_men_15to49 <- raster( file.path( directory, "data", "data_raw", "ihme", "educational_attainment", "IHME_LMIC_EDU_2000_2017_SECONDARYPROP_1549_MALE_MEAN_Y2019M12D24.TIF" ) ) rast_ihme_second_women_15to49 <- raster( file.path( directory, "data", "data_raw", "ihme", "educational_attainment", "IHME_LMIC_EDU_2000_2017_SECONDARYPROP_1549_FEMALE_MEAN_Y2019M12D24.TIF" ) ) sub_nat_boundaries <- ne_states() sub_nat_boundaries <- st_as_sf(sub_nat_boundaries) extract_subnational_stats <- function(rast_layer,i) { # i=7 # rast_layer=rast subnational_a2_code <- sub_nat_boundaries$iso_3166_2[i] subnational_poly <- st_geometry(sub_nat_boundaries[i,]) subnational_extract <- exact_extract( rast_layer,subnational_poly, c("mean") ) subnational_stats <- cbind(subnational_a2_code,subnational_extract) return(subnational_stats) } beginCluster() education_ratio <- rast_ihme_second_women_15to49/rast_ihme_second_men_15to49 endCluster() beginCluster() education_ratio_subnational_stats <- t( pbsapply(1:dim(sub_nat_boundaries)[1],function(c) extract_subnational_stats(rast_layer=education_ratio,i=c)) ) endCluster() education_ratio_subnational_stats_df <- data.frame(matrix(unlist(education_ratio_subnational_stats), nrow=dim(sub_nat_boundaries)[1], byrow=F),stringsAsFactors=FALSE) names(education_ratio_subnational_stats_df) <- c("iso_3166_2","gender_secondary_education_ratio_mean") beginCluster() women_education_subnational_stats <- t( pbsapply(1:dim(sub_nat_boundaries)[1],function(c) extract_subnational_stats(rast_layer=rast_ihme_second_women_15to49,i=c)) ) endCluster() women_education_subnational_stats_df <- data.frame(matrix(unlist(women_education_subnational_stats), nrow=dim(sub_nat_boundaries)[1], byrow=F),stringsAsFactors=FALSE) names(women_education_subnational_stats_df) <- c("iso_3166_2","women_secondary_education_mean") write.csv( education_ratio_subnational_stats_df, file.path( directory, "data", "data_clean", "clean_subnational", "education_ratio_subnational_mean_2000_2017.csv" ), row.names=FALSE ) write.csv( women_education_subnational_stats_df, file.path( directory, "data", "data_clean", "clean_subnational", "women_education_subnational_mean_2000_2017.csv" ), row.names=FALSE )
39bdc4d6331bc5d46c2ced51b0fbd44f590cf035
1fb22fa3ac1f5a78e0cce797d6d7bdcf78d8236f
/man/plot_adjmatrix.Rd
4b4e18fdc1df3753dbd2252036ed199a0f2163c2
[]
no_license
scramblingbalam/graphclass
2fb0a77d6fa984a9dd6c56b39487ea43a8cbda34
930d2ff47319e5fd5c70c6d73afdea2763eee3ab
refs/heads/master
2021-04-12T04:21:09.096338
2018-02-23T23:01:18
2018-02-23T23:01:18
null
0
0
null
null
null
null
UTF-8
R
false
true
577
rd
plot_adjmatrix.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Plots.R \name{plot_adjmatrix} \alias{plot_adjmatrix} \title{Plot a vectorized adjacency matrix.} \usage{ plot_adjmatrix(beta, type = "intersection") } \arguments{ \item{beta}{Vectorized adjacency matrix. For undirected networks use only upper triangle in column-major order, for directed use both} \item{type}{Either intersection for undirected networks, union for directed.} } \description{ Plot a vectorized adjacency matrix. } \examples{ B = runif(34453) plot_adjmatrix(B) }
aea40445e4ec4dd508273349b5c80bcd8610811e
431719d48e8567140216bdfdcd27c76cc335a490
/man/TagResource.Rd
887428e23b31150bf861c719b6dac20455af2198
[ "BSD-3-Clause" ]
permissive
agaveplatform/r-sdk
4f32526da4889b4c6d72905e188ccdbb3452b840
b09f33d150103e7ef25945e742b8d0e8e9bb640d
refs/heads/master
2018-10-15T08:34:11.607171
2018-09-21T23:40:19
2018-09-21T23:40:19
118,783,778
1
1
null
null
null
null
UTF-8
R
false
true
416
rd
TagResource.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/TagResource.r \docType{data} \name{TagResource} \alias{TagResource} \title{TagResource Class} \format{An object of class \code{R6ClassGenerator} of length 24.} \usage{ TagResource } \description{ Resource to which a tag has been associated } \section{Fields}{ \describe{ \item{\code{id}}{uuid of the API resource} }} \keyword{datasets}
561abbf77b0c3d3a863283db47b1796ab65da59a
9a3ed38b823f090cd9826def42fb77f50c2f8492
/USAspending/cfda_extraction_datatable.r
09f6e7813a0a1b296aaf685e8a59fd1daf6aa17a
[ "MIT" ]
permissive
cenuno/Spatial_Visualizations
fded362213663882103d0dea10ed73ab0fe4231c
7a4776dd5b87449497b7615887c42f05a3d2e694
refs/heads/master
2021-01-02T08:44:56.313875
2017-12-23T03:47:02
2017-12-23T03:47:02
99,060,719
1
1
null
null
null
null
UTF-8
R
false
false
5,106
r
cfda_extraction_datatable.r
# # Author: Cristian Nuno # Date: August 20, 2017 # Purpose: To write an API function with USA Spending data # regarding CFDA inqueries # # # # Example URL: https://api.usaspending.gov/api/v1/references/cfda/ # Summary: Returns information about CFDA programs # require(compiler) # compilePKGS() setCompilerOptions(suppressAll = TRUE ) # enableJIT enables or disables just-in-time (JIT) compilation. # JIT is disabled if the argument is 0. # If level is 1 then larger closures are compiled before their first use. # If level is 2, then some small closures are also compiled before their second use. # If level is 3 then in addition all top level loops are compiled before they are executed. enableJIT(3) # 0 # load necessary packages library( httr ) library( jsonlite ) library( dplyr ) library( DT ) # Create function endpoint_df_extraction <- function( path ) { # Create empty list pages <- list() # Create initial API url url <- modify_url("https://api.usaspending.gov" , path = path , query = list(page = 1 , limit = 400 ) ) # Get API url raw.resp <- GET(url) if (http_type(raw.resp) != "application/json") { stop("API did not return json. Check 'status code = 200'" , call. = FALSE) } this.char.resp <- rawToChar( raw.resp$content) # convert from raw to char # convert JSON object into R object this.clean.resp <- fromJSON(this.char.resp , flatten = TRUE ) # identify a boolean operator # data_api$page_metadata$has_next_page = TRUE this.clean.resp$page_metadata$has_next_page = TRUE # while loop to grab and store data as long as the variable # this.clean.resp$page_metadata$has_next_page == TRUE # Set initial page number page_number <- 1 # while loop with boolean condition while( this.clean.resp$page_metadata$has_next_page == TRUE ) { # identify current page url current.page.url <- this.clean.resp$page_metadata$current # subsitute "&page=XX" with "&page='page_number'" next.page.url <- gsub( pattern = "&page=[[:digit:]]+" , replacement = paste0( "&page=", page_number) , x = current.page.url ) # Get new API url raw.resp <- GET( url = next.page.url ) # Convert raw vector to character vector this.char.resp <- rawToChar( raw.resp$content ) # Convert JSON object into R object this.clean.resp <- fromJSON( this.char.resp , flatten = TRUE ) # For every page number (1, 2, 3...), insert that page's "results" inside the list pages[[ page_number ]] <- this.clean.resp$results # Add to the page number and restart the loop page_number <- page_number + 1 } # once all the pages have been collected, data_api_data <- rbind_pages(pages) # return what we've collected return( data_api_data ) # Turn API errors into R errors if (http_error( raw.resp )) { stop( sprintf( "USASpending.gov API request failed [%s]\n%s\n<%s>", status_code( raw.resp), this.clean.resp$message, this.clean.resp$documentation_url ), call. = FALSE ) } # add some structure stuff structure( list( content = this.clean.resp , path = "/api/v1/references/cfda/" , response = raw.resp ) , class = "usa_spending_api" ) } # end of function # Call function cfda_program_info <- endpoint_df_extraction("/api/v1/references/cfda/") # Waiting...3 seconds! fancy_table <- datatable( data = select( cfda_program_info , program_number , program_title , popular_name , objectives , website_address ) , rownames = FALSE , colnames = c("Program Number" , "Program Title" , "Popular Name" , "Objectives" , "Website Address" ) , caption = "Catalog of Federal Domestic Assistance (CFDA) Programs" , extensions = 'Buttons' , options = list( dom = "Blfrtip" , buttons = list("copy", list( extend = "collection" , buttons = c("csv", "excel", "pdf") , text = "Download" ) ) # end of buttons customization # customize the length menu , lengthMenu = list( c(100, 500, -1) # declare values , c(100, 500, "All") # declare titles ) # end of lengthMenu customization , pageLength = 100 ) # end of options ) # Display fancy table fancy_table
a5ac1487ea95831fbe0ec9498ea97a9f17d6be7e
478e2bacd8621f8846fca224134b8b121ea6f193
/graphics/drawGraph.r
3212fef06d93104c6d11688e914b119d0b58b59f
[]
no_license
krprls/Variant-graph-analysis
aae8c419bfca91a9bb69f2fa21c4764c1ed11c8a
981de650670baf25bea19659b2e5e9b1668bd044
refs/heads/master
2020-06-03T05:53:02.225539
2017-06-01T07:51:12
2017-06-01T07:51:12
null
0
0
null
null
null
null
UTF-8
R
false
false
1,216
r
drawGraph.r
############################################################################## # drawGraph.r # # Analyses for master thesis # ====================================== # # Feeds the edgeList from BuildGraph.java into igraph for visualization ############################################################################### require(igraph) data = read.table("g1edgeList.txt", header = TRUE, sep = " ") edgeList = as.matrix(data) labels = read.table("g1labelList.txt", header = TRUE, sep = " ") g1 = graph_from_edgelist(edgeList, directed = TRUE) V(g1)$label = paste(labels[,1]) V(g1)$name = paste(labels[,1]) pdf("g1.pdf", width = 7, height = 6) plot(g1, vertex.size = 25, edge.arrow.size = .7, vertex.label.cex = 1.8, layout = layout.fruchterman.reingold(g1)) dev.off() data = read.table("g2edgeList.txt", header = TRUE, sep = " ") edgeList = as.matrix(data) labels = read.table("g2labelList.txt", header = TRUE, sep = " ") g2 = graph_from_edgelist(edgeList, directed = TRUE) V(g2)$label = paste(labels[,1]) V(g2)$name = paste(labels[,1]) pdf("g2.pdf", width = 7, height = 6) plot(g2, vertex.size = 25, edge.arrow.size = .7, vertex.label.cex = 1.8, layout = layout.fruchterman.reingold(g2)) dev.off()
510c7fc4e951aff2c10c7800e4276a2b9d12fe47
31fbbb9f41d6540933a9dd69f43a3b7f97577423
/user_jc/overlap_between_disease_sets.R
5f5ddedaac099133c6dd57cbcfc351317ae69a9f
[]
no_license
potentece/ses
ecd75f5705344443d30d2560003ebf57f5416871
3fb7cd5d6c1a8e413f4ebd929b68ceef31b9bc38
refs/heads/master
2022-12-24T02:27:57.515238
2020-10-01T10:05:20
2020-10-01T10:05:20
280,169,302
0
0
null
2020-09-01T11:44:02
2020-07-16T14:02:43
null
UTF-8
R
false
false
2,671
r
overlap_between_disease_sets.R
#' --- #' title: Examples #' output: #' html_document: #' toc: true #' highlight: zenburn #' --- #' <!-- rmarkdown::render("supervised_play/nice_code.R") --> #' <!-- [See here.](http://brooksandrew.github.io/simpleblog/articles/render-reports-directly-from-R-scripts/) --> #' Set global options #+ setup, warning=FALSE, message=FALSE # knitr::opts_chunk$set(echo = FALSE) set.seed(123) library(here) library(tidyverse) library(Biobase) walk(dir(path = here("R"), full.names = TRUE), source) ############################################################ # LOAD DATA, DEFINE VARIABLES, RECODE VARIABLES ############################################################ load_data(reconciled = FALSE) define_treatments_and_controls() sigs = signatures$outcome_set[c(table1, "ctra_mRNA")] get_intersection = function(intersection_order, op = intersect) { # GET ALL INTERSECTIONS OF A GIVEN ORDER # y = combinations of sets # nm = names of such sets # z = intersection of such sets tibble(y = combn(sigs, intersection_order, simplify = FALSE), nm = map(y, names), z = map(y, reduce, op)) %>% arrange(-lengths(z)) %>% filter(lengths(z) > 0) } prettify = . %>% select(-y) %>% knitr::kable() # overlap between the disease sets and the 1k. a = sigs[-3] # less 1k b = sigs[3] # 1k crossing(a,b) %>% pmap_dbl(function(a,b) length(intersect(a,b))/length(a)) %>% enframe(name = "signature", value = "proportion which overlaps with 1k") # how many n-way intersections? map(2:5, compose(prettify, get_intersection)) # Inflammation1k intersects with all other disease sets, by at least one gene (rarely the same gene) map(2:5, get_intersection) %>% map(pluck("nm")) %>% map(unlist) %>% map(table) %>% map(sort) %>% map(enframe) # Only 1 gene belongs to as many as 4 signatures (TCF7). # non-monogomous genes (appearing in at 2 or more signatures) map(2:5, get_intersection) %>% map(pluck, "z") %>% map(unlist) %>% map(unique) %>% lengths() # how many n-way intersections does each gene belong to map(2:5, get_intersection) %>% map(pluck, "z") %>% map(compose(fct_count, factor, unlist)) %>% map(arrange, -n) %>% walk(print, n = Inf) # GOC "genes of co-morbidity". sigs %>% lengths() ns = lengths(sigs) map(2:5, get_intersection) %>% map(transmute, nm, n = lengths(z)) %>% map(unnest_wider, "nm") # size of intersection and the size of the disease sets map(2, get_intersection) %>% map(transmute, nm, n = lengths(z)) %>% map(unnest_wider, "nm") %>% map(mutate, n1 = ns[`...1`], n2 = ns[`...2`]) %>% map(mutate, p1 = n/n1, p2 = n/n2) %>% map(print, n = Inf)
3083de1ff392fb9a7049d66edf09ee1613544a16
df02a3254469994aee94ba9783ae5823a138d6a8
/scRNA_operation.R
ff432147fada5b794c583034ee52aecc0416845f
[]
no_license
liuzhe93/FengLab-PCNSL
57022228e177b018135696d8b44f03027d28240d
77c3eac98be00ed2c5ec804888e2c61d996a8eae
refs/heads/main
2023-07-03T21:24:13.972032
2021-08-07T13:49:00
2021-08-07T13:49:00
386,863,041
0
0
null
null
null
null
UTF-8
R
false
false
63,014
r
scRNA_operation.R
# set workpath and load R packages # conda activate Renv setwd("/ifs1/Grp8/liuzhe/scRNA/") rm(list = ls()) #remotes::install_github("satijalab/seurat", ref = "release/4.0.0") #remotes::install_github("jlmelville/uwot") #install.packages('Seurat') library("Seurat") #install.packages('tidyverse') library("tidyverse") library("Matrix") library("scales") library("cowplot") library("RCurl") options(stringsAsFactors = F) library("scRNAseq") library("scater") # devtools::install_github(repo = "satijalab/seurat", ref = "loom") library("loomR") library("patchwork") library("scuttle") library("dplyr") library("tibble") library("HCAData") library("SingleR") library("org.Hs.eg.db") library("clusterProfiler") library("vroom") library("celldex") library("dittoSeq") set.seed(2020) library("monocle3") suppressPackageStartupMessages(library("SingleCellExperiment")) library("ggplot2"); theme_set(theme_bw()) library("DuoClustering2018") require(scry) library("scran") library("DoubletFinder") ## Pre-process Seurat object (standard) -------------------------------------------------------------------------------------- # load the scRNA-seq data # create each individual Seurat object for every sample # create Seurat object cancer and normal seurat_data<-Read10X(data.dir=paste0("0_counts/","cancer")) #seurat_obj<-CreateSeuratObject(counts=seurat_data,project="cancer") seurat_obj<-CreateSeuratObject(counts=seurat_data,project="cancer") assign("cancer",seurat_obj) cancer<-NormalizeData(cancer) cancer <- FindVariableFeatures(cancer, selection.method = "vst", nfeatures = 3000) cancer <- ScaleData(cancer) cancer <- RunPCA(cancer) cancer <- RunUMAP(cancer, reduction = "pca", dims = 1:21) cancer <- RunTSNE(cancer, reduction = "pca", dims = 1:21) ## Pre-process Seurat object (sctransform) ----------------------------------------------------------------------------------- cancer <- SCTransform(cancer) cancer <- RunPCA(cancer) cancer <- RunUMAP(cancer, reduction = "pca", dims = 1:21) cancer <- RunTSNE(cancer, reduction = "pca", dims = 1:21) ## pK Identification (no ground-truth) --------------------------------------------------------------------------------------- sweep.res.list_brain <- paramSweep_v3(cancer, PCs = 1:21, sct = FALSE) sweep.stats_brain <- summarizeSweep(sweep.res.list_brain, GT = FALSE) head(sweep.stats_brain) bcmvn_brain <- find.pK(sweep.stats_brain) mpK<-as.numeric(as.vector(bcmvn_brain$pK[which.max(bcmvn_brain$BCmetric)])) DoubletRate = ncol(cancer)*8*1e-6 #按每增加1000个细胞,双细胞比率增加千分之8来计算 #Calculate by increasing the ratio of doulets by 0.008 for every additional 1000 cells #DoubletRate = 0.075 ## Homotypic Doublet Proportion Estimate ------------------------------------------------------------------------------------- cancer <- FindNeighbors(cancer, reduction = "pca", dims = 1:21) cancer <- FindClusters(cancer, resolution = 0.6) levels(cancer) cancer <- RunUMAP(cancer, reduction = "pca", dims = 1:21) cancer <- RunTSNE(cancer, reduction = "pca", dims = 1:21) annotations <- cancer@meta.data$seurat_clusters homotypic.prop <- modelHomotypic(annotations) nExp_poi <- round(DoubletRate*nrow(cancer@meta.data)) nExp_poi.adj <- round(nExp_poi*(1-homotypic.prop)) ## Run DoubletFinder with varying classification stringencies ---------------------------------------------------------------- cancer <- doubletFinder_v3(cancer, PCs = 1:21, pN = 0.05, pK = 5e-04, nExp = nExp_poi, reuse.pANN = FALSE, sct = FALSE) cancer <- doubletFinder_v3(cancer, PCs = 1:21, pN = 0.05, pK = 5e-04, nExp = nExp_poi.adj, reuse.pANN = "pANN_0.05_5e-04_9717", sct = FALSE) pdf("test_Double.pdf", width = 10, height = 10) DimPlot(cancer, reduction = "tsne", group.by = "DF.classifications_0.05_5e-04_8535") dev.off() cancer@meta.data$singledouble<-cancer@meta.data$'DF.classifications_0.05_5e-04_8535' cancer.singlet <- subset(cancer, subset = singledouble == "Singlet") cancer$'DF.classifications_0.05_5e-04_8535'<-Idents(cancer) pdf("test_Double.pdf", width = 10, height = 10) DimPlot(cancer, reduction = "tsne", label = TRUE, pt.size=1.5,label.size = 8, group.by = 'DF.classifications_0.05_5e-04_8535') dev.off() cancer_singlet<-cancer.singlet pdf("1_preoperation/figures/pre-operation/cancer.counts.vs.features.pdf") plot(x=cancer_singlet@meta.data$nCount_RNA,y=cancer_singlet@meta.data$nFeature_RNA) dev.off() # check the metadata in the new Seurat objects head(cancer_singlet@meta.data) tail(cancer_singlet@meta.data) # Create .RData object to load at any time save(cancer_singlet, file="1_preoperation/data/cancer.combined.RData") cancer_singlet$log10GenesPerUMI <- log10(cancer_singlet$nFeature_RNA) / log10(cancer_singlet$nCount_RNA) cancer_singlet$mitoRatio <- PercentageFeatureSet(object = cancer_singlet, pattern = "^MT-") cancer_singlet$mitoRatio <- cancer_singlet@meta.data$mitoRatio / 100 cancermetadata <- cancer_singlet@meta.data cancermetadata$cells <- rownames(cancermetadata) cancermetadata <- cancermetadata %>% dplyr::rename(seq_folder = orig.ident, nUMI = nCount_RNA, nGene = nFeature_RNA) cancer_singlet cancer_singlet@meta.data <- cancermetadata counts <- GetAssayData(object = cancer_singlet, slot = "counts") cancer_singlet <- CreateSeuratObject(counts, meta.data = cancer@meta.data) cancer_singlet$label <- "cancer" cancer_norm <- NormalizeData(cancer_singlet, normalization.method = "LogNormalize", scale.factor = 10000) cancer_norm <- FindVariableFeatures(cancer_norm, selection.method = "vst", nfeatures = 3000) pdf("1_preoperation/figures/pre-operation/cancer_Visualize_QC.pdf", width = 12, height = 6) VlnPlot(cancer_singlet, features = c("nFeature_SCT", "nCount_SCT", "mitoRatio"), ncol = 3) dev.off() plot1 <- FeatureScatter(cancer_singlet, feature1 = "nCount_SCT", feature2 = "mitoRatio") plot2 <- FeatureScatter(cancer_singlet, feature1 = "nCount_SCT", feature2 = "nFeature_SCT") pdf("1_preoperation/figures/pre-operation/cancer_FeatureScatter.pdf", width = 12, height = 6) CombinePlots(plots = list(plot1, plot2)) dev.off() top30 <- head(VariableFeatures(cancer_norm), 30) pdf("1_preoperation/figures/pre-operation/cancer_VariableFeatures.pdf", width = 12, height = 6) plot1 <- VariableFeaturePlot(cancer_norm) plot2 <- LabelPoints(plot = plot1, points = top30, repel = TRUE) CombinePlots(plots = list(plot1, plot2)) dev.off() # filter cancer filtered_cancer <- subset(x = cancer_singlet, subset= (nUMI < 20000) & (nGene > 200) & (nGene < 2000) & (log10GenesPerUMI > 0.80) & (mitoRatio < 0.1)) filtered_cancer cancer_singlet[["percent_HBA1"]] <- PercentageFeatureSet(filtered_cancer, features = "HBA1") cancer_singlet[["percent_HBB"]] <- PercentageFeatureSet(filtered_cancer, features = "HBB") cancer_singlet <- subset(x = cancer_singlet, subset= percent_HBA1 < 0.001 | percent_HBB < 0.001) counts <- GetAssayData(object = filtered_cancer, slot = "counts") nonzero <- counts > 0 keep_genes <- Matrix::rowSums(nonzero) >= 20 filtered_counts <- counts[keep_genes, ] filtered_cancer <- CreateSeuratObject(filtered_counts, meta.data = cancer_singlet@meta.data) filtered_cancer$label <- "cancer" save(filtered_cancer, file="1_preoperation/data/filtered_cancer.RData") filtered_cancer_norm<-NormalizeData(filtered_cancer) setwd("/ifs1/Grp8/liuzhe/scRNA/") seurat_data<-Read10X(data.dir=paste0("0_counts/normal/","HFA567_total.filtered_gene_matrices")) seurat_obj<-CreateSeuratObject(counts=seurat_data,project="normal") assign("normal1",seurat_obj) normal1<-NormalizeData(normal1) seurat_data<-Read10X(data.dir=paste0("0_counts/normal/","HFA570_total.filtered_gene_matrices")) seurat_obj<-CreateSeuratObject(counts=seurat_data,project="normal") assign("normal2",seurat_obj) normal2<-NormalizeData(normal2) seurat_data<-Read10X(data.dir=paste0("0_counts/normal/","HFA571_total.filtered_gene_matrices")) seurat_obj<-CreateSeuratObject(counts=seurat_data,project="normal") assign("normal3",seurat_obj) normal3<-NormalizeData(normal3) normal.normalized.combined <- merge(normal1, y = c(normal2, normal3), add.cell.ids = c("N1", "N2", "N3"), project = "normal", merge.data = TRUE) normal<-normal.normalized.combined pdf("1_preoperation/figures/pre-operation/normal.counts.vs.features.pdf") plot(x=normal@meta.data$nCount_RNA,y=normal@meta.data$nFeature_RNA) dev.off() # check the metadata in the new Seurat objects head(normal@meta.data) tail(normal@meta.data) # Create .RData object to load at any time save(normal, file="1_preoperation/data/normal.combined.RData") normal$log10GenesPerUMI <- log10(normal$nFeature_RNA) / log10(normal$nCount_RNA) normal$mitoRatio <- PercentageFeatureSet(object = normal, pattern = "^MT-") normal$mitoRatio <- normal@meta.data$mitoRatio / 100 normalmetadata <- normal@meta.data normalmetadata$cells <- rownames(normalmetadata) normalmetadata <- normalmetadata %>% dplyr::rename(seq_folder = orig.ident, nUMI = nCount_RNA, nGene = nFeature_RNA) normal normal@meta.data <- normalmetadata counts <- GetAssayData(object = normal, slot = "counts") normal <- CreateSeuratObject(counts, meta.data = normal@meta.data) normal$label <- "normal" normal_norm <- NormalizeData(normal, normalization.method = "LogNormalize", scale.factor = 10000) normal_norm <- FindVariableFeatures(normal_norm, selection.method = "vst", nfeatures = 3000) pdf("1_preoperation/figures/pre-operation/normal_Visualize_QC.pdf", width = 12, height = 6) VlnPlot(normal, features = c("nFeature_RNA", "nCount_RNA", "mitoRatio"), ncol = 3) dev.off() plot1 <- FeatureScatter(normal, feature1 = "nCount_RNA", feature2 = "mitoRatio") plot2 <- FeatureScatter(normal, feature1 = "nCount_RNA", feature2 = "nFeature_RNA") pdf("1_preoperation/figures/pre-operation/normal_FeatureScatter.pdf", width = 12, height = 6) CombinePlots(plots = list(plot1, plot2)) dev.off() top30 <- head(VariableFeatures(normal_norm), 30) pdf("1_preoperation/figures/pre-operation/normal_VariableFeatures.pdf", width = 12, height = 6) plot1 <- VariableFeaturePlot(normal_norm) plot2 <- LabelPoints(plot = plot1, points = top30, repel = TRUE) CombinePlots(plots = list(plot1, plot2)) dev.off() # filter normal filtered_normal <- subset(x = normal, subset= (nUMI < 20000) & (nGene > 100) & (nGene < 3000) & (log10GenesPerUMI > 0.80) & (mitoRatio < 0.1)) counts <- GetAssayData(object = filtered_normal, slot = "counts") nonzero <- counts > 0 keep_genes <- Matrix::rowSums(nonzero) >= 20 filtered_counts <- counts[keep_genes, ] filtered_normal <- CreateSeuratObject(filtered_counts, meta.data = normal@meta.data) filtered_normal$label <- "normal" save(filtered_normal, file="1_preoperation/data/filtered_normal.RData") filtered_normal_norm<-NormalizeData(filtered_normal) WBY.anchors <- FindIntegrationAnchors(object.list = list(filtered_cancer_norm, filtered_normal_norm), dims = 1:30) save(WBY.anchors, file="1_preoperation/data/integrated.anchors_seurat20210604.RData") WBY.combined <- IntegrateData(anchorset = WBY.anchors, dims = 1:30) WBY.combined <- FindVariableFeatures(WBY.combined, selection.method = "vst", nfeatures = 3000) save(WBY.combined, file="1_preoperation/data/integrated.combined_seurat20210510.RData") DefaultAssay(WBY.combined) <- "integrated" # Run the standard workflow for visualization and clustering WBY.combined <- ScaleData(WBY.combined, verbose = FALSE, vars.to.regress = c("nUMI", "mitoRatio")) #Scaling is an essential step in the Seurat workflow, but only on genes that will be used as input to PCA. Therefore, the default in ScaleData() is only to perform scaling on the previously identified variable features (2,000 by default). WBY.combined <- ScaleData(WBY.combined) save(WBY.combined, file="1_preoperation/data/WBY.combined_scaled.RData") WBY.combined <- RunPCA(WBY.combined, npcs = 30, verbose = FALSE) print(WBY.combined[["pca"]], dims = 1:5, nfeatures = 5) pdf("1_preoperation/data/VizDimLoadings.pdf") VizDimLoadings(WBY.combined, dims = 1:2, reduction = "pca") dev.off() pdf("1_preoperation/data/DimPlot.pdf") DimPlot(WBY.combined, reduction = "pca") dev.off() pdf("1_preoperation/data/DimHeatmap.pc1.pdf") DimHeatmap(WBY.combined, dims = 1, cells = 500, balanced = TRUE) dev.off() pdf("1_preoperation/data/DimHeatmap.all.pdf") DimHeatmap(WBY.combined, dims = 1:30, cells = 500, balanced = TRUE) dev.off() WBY.combined <- JackStraw(WBY.combined, num.replicate = 100, dims = 30) WBY.combined <- ScoreJackStraw(WBY.combined, dims = 1:30) pdf("1_preoperation/data/Determine_dimensionality.pdf", width = 24, height = 18) p1 <- JackStrawPlot(WBY.combined, dims = 1:30) p2 <- ElbowPlot(WBY.combined,ndims = 30) plot_grid(p1, p2) dev.off() save(WBY.combined, file="1_preoperation/data/integrated.combined_beforepcs.RData") # determine the resolution library(Seurat) library(clustree) WBY.combined <- FindNeighbors(WBY.combined, reduction = "pca", dims = 1:21) WBY.combined <- FindClusters(WBY.combined, resolution = 0.5) WBY.combined <- RunUMAP(WBY.combined, reduction = "pca", dims = 1:21) WBY.combined <- RunTSNE(WBY.combined, reduction = "pca", dims = 1:21) save(WBY.combined, file="1_preoperation/data/integrated.combined_beforepcs.RData") #sce <- as.SingleCellExperiment(WBY.combined) #sce <- FindNeighbors(sce, dims = 1:21) #save(sce, file="1_preoperation/data/integrated.combined.sce_beforepcs.RData") #sce <- FindClusters( # object = sce, # resolution = c(seq(.1,1.6,.2)) #) #pdf("1_preoperation/data/clusters.pdf",width=30,height=15) #clustree(sce@meta.data, prefix = "integrated_snn_res.") #colnames(sce@meta.data) #dev.off() #DefaultAssay(WBY.combined) <- "integrated" # Run the standard workflow for visualization and clustering #WBY.combined<-FindVariableFeatures(WBY.combined, selection.method = "vst", nfeatures = 3000) #WBY.combined <- ScaleData(WBY.combined) #save(WBY.combined, file="1_preoperation/data/WBY.combined_scaled.RData") #WBY.combined <- RunPCA(WBY.combined, npcs = 30, verbose = FALSE) #print(WBY.combined[["pca"]], dims = 1:5, nfeatures = 5) #pdf("1_preoperation/figures/pre-operation/VizDimLoadings.pdf") #VizDimLoadings(WBY.combined, dims = 1:2, reduction = "pca") #dev.off() #pdf("1_preoperation/figures/pre-operation/DimPlot.pdf") #DimPlot(WBY.combined, reduction = "pca") #dev.off() #pdf("1_preoperation/figures/pre-operation/DimHeatmap.pc1.pdf") #DimHeatmap(WBY.combined, dims = 1, cells = 500, balanced = TRUE) #dev.off() #pdf("1_preoperation/figures/pre-operation/DimHeatmap.all.pdf") #DimHeatmap(WBY.combined, dims = 1:30, cells = 500, balanced = TRUE) #dev.off() #WBY.combined <- JackStraw(WBY.combined, num.replicate = 100, dims = 30) #WBY.combined <- ScoreJackStraw(WBY.combined, dims = 1:30) #pdf("1_preoperation/figures/pre-operation/Determine_dimensionality.pdf", width = 24, height = 18) #p1 <- JackStrawPlot(WBY.combined, dims = 1:30) #p2 <- ElbowPlot(WBY.combined,ndims = 30) #plot_grid(p1, p2) #dev.off() #save(WBY.combined, file="1_preoperation/data/integrated.combined_beforepcs.RData") # determine the resolution r=0.7 WBY.combined <- FindClusters(WBY.combined, resolution = r) levels(WBY.combined) save(WBY.combined,file="2_annotation/seurat/WBY.combined.res0.7.RData") WBY.pca21.markers <- FindAllMarkers(object = WBY.combined, only.pos = TRUE, min.pct = 0.25, thresh.use = 0.25) save(WBY.pca21.markers,file="2_annotation/seurat/WBY.pca21.markers.res0.7.RData") top30<-WBY.pca21.markers %>% group_by(cluster) %>% top_n(n=30,wt=avg_log2FC) write.table(top30,"2_annotation/seurat/top30.pca21.markers.csv",sep=",",quote=F) head(Idents(WBY.combined), 5) write.table(WBY.pca21.markers,"2_annotation/seurat/WBY.pca21.markers.csv",sep=",",quote=F) #library(tidyverse) #umap_tx = WBY.combined.pca25@reductions$umap@cell.embeddings %>% as.data.frame() %>% cbind(label = WBY.combined.pca25@meta.data$label) %>% cbind(subpop = WBY.combined.pca25@meta.data$integrated_snn_res.0.5) %>% cbind(indiv = WBY.combined.pca25@meta.data$seq_folder) #write.csv(umap_tx,file="2_scRNA-seq/annotation/Seurat/umap_tx.csv",quote=F) #tsne_tx = WBY.combined.pca25@reductions$tsne@cell.embeddings %>% as.data.frame() %>% cbind(label = WBY.combined.pca25@meta.data$label) %>% cbind(subpop = WBY.combined.pca25@meta.data$integrated_snn_res.0.5) %>% cbind(indiv = WBY.combined.pca25@meta.data$seq_folder) #write.csv(tsne_tx,file="2_scRNA-seq/annotation/Seurat/tsne_tx.csv",quote=F) #umap_tx_ind = WBY.combined.pca25@reductions$umap@cell.embeddings %>% as.data.frame() %>% cbind(tx = WBY.combined.pca25@meta.data$seq_folder) #write.csv(umap_tx_ind,file="annotation/Seurat/umap_tx_ind.csv",quote=F) #ggplot(umap_tx, aes(x=UMAP_1, y=UMAP_2, color=tx)) + geom_point() + #scale_color_manual(values=c("group1_untreated" = "darkblue", # "group1_treated" = "darkred")) #tsne_tx = WBY.combined.pca25@reductions$tsne@cell.embeddings %>% as.data.frame() %>% cbind(tx = WBY.combined.pca25@meta.data$label) #tsne_tx_ind = WBY.combined.pca25@reductions$tsne@cell.embeddings %>% as.data.frame() %>% cbind(tx = WBY.combined.pca25@meta.data$seq_folder) # Visualization pdf(paste0("2_annotation/seurat/umap.pca21.res",r,".splitbyLabel.pdf"),width=20,height=10) DimPlot(WBY.combined, reduction = "umap", label = TRUE, pt.size=1,label.size = 8, split.by = 'label', group.by = 'integrated_snn_res.0.7') dev.off() pdf(paste0("2_annotation/seurat/umap.pca21.res",r,".pdf"),width=10,height=10) DimPlot(WBY.combined, reduction = "umap", label = TRUE, pt.size=1,label.size = 8, group.by = 'integrated_snn_res.0.7') dev.off() pdf(paste0("2_annotation/seurat/tsne.pca21.res",r,".splitbyLabel.pdf"),width=20,height=10) DimPlot(WBY.combined, reduction = "tsne", label = TRUE, pt.size=0.1,label.size = 8, split.by = 'label', group.by = 'integrated_snn_res.0.7') dev.off() pdf(paste0("2_annotation/seurat/tsne.pca21.res",r,".pdf"),width=10,height=10) DimPlot(WBY.combined, reduction = "tsne", label = TRUE, pt.size=0.1,label.size = 8, group.by = 'integrated_snn_res.0.7') dev.off() prop.table(table(Idents(WBY.combined), WBY.combined$label)) allsampleprop.each <-as.data.frame(prop.table(table(Idents(WBY.combined), WBY.combined$label))) prop.table(table(Idents(WBY.combined))) allsampleprop.total <-as.data.frame(prop.table(table(Idents(WBY.combined)))) write.csv(x = allsampleprop.each,file = '2_annotation/seurat/anno.allsample.each.prop.csv',quote = T,row.names = T) write.csv(x = allsampleprop.total,file = '2_annotation/seurat/anno.allsample.total.prop.csv',quote = T,row.names = T) table(Idents(WBY.combined)) pro.total <- table(Idents(WBY.combined),WBY.combined$label) table(Idents(WBY.combined),WBY.combined$label) pro.each <- table(Idents(WBY.combined),WBY.combined$label) write.csv(x =pro.total,file = '2_annotation/seurat/anno.pro.total.csv',quote = T,row.names = T) write.csv(x =pro.each,file = '2_annotation/seurat/anno.pro.each.csv',quote = T,row.names = T) save(WBY.combined,file="2_annotation/seurat/WBY.combined.pca21.res0.7.17clusters.aftercluster.autoSeurat.nolabel.RData") save(WBY.combined,file="2_annotation/seurat/WBY.combined.pca21.aftercluster.autoSeurat.nolabel.RData") # annotation new.cluster.ids<-c("B_cell", "T_cell", "EN", "IN", "IN", "RG", "Macrophage", "EN", "INP", "Dendritic_cell", "ENP", "Astrocyte", "Oligodendrocyte", "Miningeal_cell", "OPC", "EN") names(new.cluster.ids) <- levels(WBY.combined) WBY.combined <- RenameIdents(WBY.combined, new.cluster.ids) WBY.combined$celltype<-Idents(WBY.combined) save(WBY.combined,file="/ifs1/Grp8/liuzhe/scRNA/2_annotation/seurat/WBY.combined.pca21.res0.7.afteranno.RData") WBY.combined.markers <- FindAllMarkers(object = WBY.combined, only.pos = TRUE, min.pct = 0.25, thresh.use = 0.25) write.table(WBY.combined.markers,"2_annotation/seurat/WBY.pca21.markers.csv",sep=",",quote=F) top30<-WBY.combined.markers %>% group_by(cluster) %>% top_n(n=30,wt=avg_log2FC) write.table(top30,"2_annotation/seurat/top30.pca21.markers.csv",sep=",",quote=F) save(WBY.combined.markers,file="/ifs1/Grp8/liuzhe/scRNA/2_annotation/seurat/WBY.combined.pca21.res0.7.marker.afteranno.RData") # calculate the percentage and count the numbers prop.table(table(Idents(WBY.combined), WBY.combined$label)) allsampleprop.each <-as.data.frame(prop.table(table(Idents(WBY.combined), WBY.combined$label))) prop.table(table(Idents(WBY.combined))) allsampleprop.total <-as.data.frame(prop.table(table(Idents(WBY.combined)))) write.csv(x = allsampleprop.each,file = '2_annotation/seurat/anno.allsample.each.prop.csv',quote = T,row.names = T) write.csv(x = allsampleprop.total,file = '2_annotation/seurat/anno.allsample.total.prop.csv',quote = T,row.names = T) table(Idents(WBY.combined)) pro.total <- table(Idents(WBY.combined),WBY.combined$label) table(Idents(WBY.combined),WBY.combined$label) pro.each <- table(Idents(WBY.combined),WBY.combined$label) write.csv(x =pro.total,file = '2_annotation/seurat/anno.pro.total.csv',quote = T,row.names = T) write.csv(x =pro.each,file = '2_annotation/seurat/anno.pro.each.csv',quote = T,row.names = T) # visualization WBY.combined$celltype <- Idents(WBY.combined) pdf(paste0("2_annotation/seurat/umap.pca21.res",r,".splitbyLabel.pdf"),width=20,height=10) DimPlot(WBY.combined, reduction = "umap", label = TRUE, pt.size=1.5,label.size = 8, split.by = 'label', group.by = "celltype") dev.off() pdf(paste0("2_annotation/seurat/umap.pca21.res",r,".pdf"),width=10,height=10) DimPlot(WBY.combined, reduction = "umap", label = TRUE, pt.size=1.5,label.size = 8, group.by = 'celltype') dev.off() pdf(paste0("2_annotation/seurat/tsne.pca21.res",r,".splitbyLabel.pdf"),width=20,height=10) DimPlot(WBY.combined, reduction = "tsne", label = TRUE, pt.size=1,label.size = 8, split.by = 'label', group.by = 'celltype') dev.off() pdf(paste0("2_annotation/seurat/tsne.pca21.res",r,".pdf"),width=10,height=10) DimPlot(WBY.combined, reduction = "tsne", label = TRUE, pt.size=1,label.size = 8, group.by = 'label') dev.off() delta.genes <- c("CD79A","CD37","CCL5","CRIP1","ENC1","EGR1","HBA2","CXCR4","MSMO1","RPS26","LYZ","C1QA","HIST1H4C","TOP2A","CST3","CPVL","EOMES","CORO1C","TTYH1","FGFBP3","PLP1","MBP","TIMP1","IGFBP7","APOD","S100B") pdf("2_annotation/anno/dittoDotPlot.pdf",width=15,height=8) dittoDotPlot(WBY.combined, vars = delta.genes, group.by = "celltype",scale = FALSE) dev.off() pdf("2_annotation/anno/heatmap.top30.pdf",width=24,height=18) DoHeatmap(WBY.combined,features=top30$gene,cells = 1:500, size = 4, angle = 90, disp.min=-2, disp.max=2) + scale_fill_gradientn(colours=c("blue","white","red")) dev.off() library(psych) library(pheatmap) AverageExp<-AverageExpression(WBY.combined,features=unique(top30$gene)) typeof(AverageExp) head(AverageExp$RNA) DefaultAssay(WBY.combined) <- "integrated" pdf("2_annotation/anno/averageExptop30.clusters.pdf") coorda<-corr.test(AverageExp$RNA,AverageExp$RNA,method="spearman") pheatmap(coorda$r,cluster_row = FALSE,cluster_col = FALSE) dev.off() pdf("2_annotation/anno/heatmap.top30.pdf",width=24,height=18) DoHeatmap(WBY.combined,features=top30$gene,cells = 1:500, size = 4, angle = 90, disp.min=-2, disp.max=2) + scale_fill_gradientn(colours=c("blue","white","red")) dev.off() DefaultAssay(WBY.combined) <- "RNA" features.plot <- c("CD37","CD79A","EEF1B2","CCL5","CRIP1","TRAC","ENC1","SLA","NRP1","PLS3","PDE4DIP","MEG3","MSMO1","FDFT1","TSPAN13","LYZ","FTL","FTH1","TOP2A","UBE2C","ZWINT","CST3","SNX3","VIM","EOMES","CORO1C","ADGRG1","PON2","CLU","GFAP","PLP1","CRYAB","CLDN11","MGP","C1S","OLIG1","PLLP","CMTM5") pdf("2_annotation/anno/markergenes.dotplot.pdf",width = 10, height = 8) DotPlot(object = WBY.combined, features = features.plot, cols = c("lightgrey", "red")) dev.off() pdf("2_annotation/anno/markergenes.dotplot.pdf",width = 14, height = 8) DotPlot(object = WBY.combined, features=features.plot,dot.scale = 10,cols = c("gray90", "red")) + RotatedAxis() dev.off() pdf("2_annotation/anno/markergenes.Bcell.pdf", width = 16, height = 8) p1 <- FeaturePlot(WBY.combined, features = c("CD37", "CD79A"), pt.size = 1.5, combine = FALSE, reduction="tsne" ) fix.sc <- scale_color_gradientn( colours = c('lightgrey', 'red'), limits = c(2, 5)) p2 <- lapply(p1, function (x) x + fix.sc) CombinePlots(p2) dev.off() pdf("2_annotation/anno/markergenes.MPC.pdf", width = 16, height = 8) p1 <- FeaturePlot(WBY.combined, features = c("TUBA1B", "HMGB2"), pt.size = 1.5, combine = FALSE, reduction="tsne" ) fix.sc <- scale_color_gradientn( colours = c('lightgrey', 'red'), limits = c(3, 5)) p2 <- lapply(p1, function (x) x + fix.sc) CombinePlots(p2) dev.off() WBY.combined_cancer<-subset(x=WBY.combined,subset = label == "cancer") cellcom <- subset(WBY.combined_cancer, subset = (celltype == "B_cell" | celltype == "T_cell" | celltype == "Macrophage" | celltype == "Dendritic_cell")) write.table(as.matrix(cellcom@assays$RNA@data), 'cellphonedb_count.txt', sep='\t', quote=F) meta_data <- cbind(rownames(cellcom@meta.data), cellcom@meta.data[,'celltype', drop=F]) meta_data <- as.matrix(meta_data) meta_data[is.na(meta_data)] = "Unkown" # ????????в?????NA write.table(meta_data, 'cellphonedb_meta.txt', sep='\t', quote=F, row.names=F) write.table(as.matrix(WBY.combined@assays$RNA@data), '3_cellphone/data/cellphonedb_count.txt', sep='\t', quote=F) meta_data <- cbind(rownames(WBY.combined@meta.data), WBY.combined@meta.data[,'celltype', drop=F]) meta_data <- as.matrix(meta_data) meta_data[is.na(meta_data)] = "Unkown" write.table(meta_data, '3_cellphone/data/cellphonedb_meta.txt', sep='\t', quote=F, row.names=F) require(org.Hs.eg.db) library(topGO) library(DOSE) #devtools::install_github("eliocamp/ggnewscale") library("ggnewscale") x=as.list(org.Hs.egALIAS2EG) geneList<-rep(0,nrow(WBY.combined)) names(geneList)<-row.names(WBY.combined) geneList<-geneList[intersect(names(geneList),names(x))] newwallgenes=names(geneList) for (ii in 1:length(geneList)){ names(geneList)[ii]<-x[[names(geneList)[ii]]][1] } gene_erichment_results=list() for (c1 in as.character(unique(levels(WBY.combined.markers$cluster)))){ print(paste0("RUN ", c1)) testgenes<-subset(WBY.combined.markers,cluster==c1)$gene gene_erichment_results[[c1]]=list() testgeneList=geneList testgeneList[which(newwallgenes %in% testgenes)]= 1 #gene_erichment_results=list() tab1=c() for(ont in c("BP","MF")){ sampleGOdata<-suppressMessages(new("topGOdata",description="Simple session",ontology=ont,allGenes=as.factor(testgeneList), nodeSize=10,annot=annFUN.org,mapping="org.Hs.eg.db",ID="entrez")) resultTopGO.elim<-suppressMessages(runTest(sampleGOdata,algorithm="elim",statistic="Fisher")) resultTopGO.classic<-suppressMessages(runTest(sampleGOdata,algorithm="classic",statistic="Fisher")) tab1<-rbind(tab1,GenTable(sampleGOdata,Fisher.elim=resultTopGO.elim,Fisher.classic=resultTopGO.classic,orderBy="Fisher.elim", topNodes=200)) } gene_erichment_results[[c1]][["topGO"]]=tab1 x<-suppressMessages(enrichDO(gene=names(testgeneList)[testgeneList==1],ont="DO",pvalueCutoff=1,pAdjustMethod="BH",universe=names(testgeneList), minGSSize=5,maxGSSize=500,readable=T)) gene_erichment_results[[c1]][["DO"]]=x dgn<-suppressMessages(enrichDGN(names(testgeneList)[testgeneList==1])) gene_erichment_results[[c1]][["DGN"]]=dgn } save(gene_erichment_results,file="2_annotation/anno/gene_erichment_results.RData") write.csv(gene_erichment_results[["B_cell"]][["topGO"]],"2_annotation/anno/GO_B_cell.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["T_cell"]][["topGO"]],"2_annotation/anno/GO_T_cell.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["EN"]][["topGO"]],"2_annotation/anno/GO_EN.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["IN"]][["topGO"]],"2_annotation/anno/GO_IN.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["RG"]][["topGO"]],"2_annotation/anno/GO_RG.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["Macrophage"]][["topGO"]],"2_annotation/anno/GO_Macrophage.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["INP"]][["topGO"]],"2_annotation/anno/GO_INP.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["Dendritic_cell"]][["topGO"]],"2_annotation/anno/GO_Dendritic_cell.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["ENP"]][["topGO"]],"2_annotation/anno/GO_ENP.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["Astrocyte"]][["topGO"]],"2_annotation/anno/GO_Astrocyte.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["Oligodendrocyte"]][["topGO"]],"2_annotation/anno/GO_Oligodendrocyte.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["Miningeal_cell"]][["topGO"]],"2_annotation/anno/GO_Minigeal_cell.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["OPC"]][["topGO"]],"2_annotation/anno/GO_OPC.GO.csv",quote=F,row.names=F) #Bcell gene_erichment_results[["B_cell"]][["topGO"]][1:5,] pdf("2_annotation/anno/clusterAnalysis_B_cell.1.pdf",width=8,height=10) library(enrichplot) dotplot(gene_erichment_results[["B_cell"]][["DGN"]], showCategory=30) dev.off() WBY.combined$celltype<-Idents(WBY.combined) WBY_cancer<-subset(x=WBY.combined,subset = label == "cancer") B_cell.subset <- subset(WBY_cancer@meta.data, celltype=="B_cell") scRNAsub.Bcell <- subset(WBY_cancer, cells=row.names(B_cell.subset)) scRNAsub.Bcell <- FindVariableFeatures(scRNAsub.Bcell, selection.method = "vst", nfeatures = 2000) scale.genes.Bcell <- rownames(scRNAsub.Bcell) scRNAsub.Bcell <- ScaleData(scRNAsub.Bcell, features = scale.genes.Bcell) scRNAsub.Bcell <- RunPCA(scRNAsub.Bcell, features = VariableFeatures(tme)) pdf("2_annotation/subcluster/Determine.Bcell.pcnumber.pdf") ElbowPlot(scRNAsub.Bcell, ndims=20, reduction="pca") dev.off() pc.num=1:8 scRNAsub.Bcell <- FindNeighbors(scRNAsub.Bcell, dims = pc.num) scRNAsub.Bcell <- FindClusters(scRNAsub.Bcell, resolution = 0.6) table(scRNAsub.Bcell@meta.data$seurat_clusters) metadata <- scRNAsub.Bcell@meta.data cell_cluster <- data.frame(cell_ID=rownames(metadata), cluster_ID=metadata$seurat_clusters) write.csv(cell_cluster,'2_annotation/subcluster/Bcell.cell_cluster.csv',row.names = F) #tSNE scRNAsub.Bcell = RunTSNE(scRNAsub.Bcell, dims = pc.num) embed_tsne <- Embeddings(scRNAsub.Bcell, 'tsne') write.csv(embed_tsne,'2_annotation/subcluster/tme.embed_tsne.csv') pdf("2_annotation/subcluster/tsne_Bcell.pdf") DimPlot(scRNAsub.Bcell, reduction = "tsne", label = TRUE, pt.size=1.5,label.size = 8) dev.off() diff.wilcox = FindAllMarkers(scRNAsub.Bcell) all.markers = diff.wilcox %>% select(gene, everything()) %>% subset(p_val<0.05) top30 = all.markers %>% group_by(cluster) %>% top_n(n = 30, wt = avg_log2FC) write.csv(all.markers, "2_annotation/subcluster/tme.diff_genes_wilcox.csv", row.names = F) write.csv(top30, "2_annotation/subcluster/tme.top30_diff_genes_wilcox.csv", row.names = F) save(scRNAsub.Bcell,file="2_annotation/subcluster/scRNAsub.tme.RData") new.cluster.ids<-c("B_cell-1", "B_cell-2", "B_cell-3", "B_cell-3", "B_cell-1", "B_cell-2", "Plasma_cell") names(new.cluster.ids) <- levels(scRNAsub.tme) scRNAsub.Bcell <- RenameIdents(scRNAsub.Bcell, new.cluster.ids) scRNAsub.Bcell <- RunUMAP(scRNAsub.Bcell, dims = 1:8) scRNAsub.Bcell$celltype<-Idents(scRNAsub.Bcell) save(scRNAsub.Bcell,file="2_annotation/subcluster/scRNAsub.Bcell.afteranno.RData") scRNAsub.Bcell.markers <- FindAllMarkers(object = scRNAsub.Bcell, only.pos = TRUE, min.pct = 0.25, thresh.use = 0.25) write.table(scRNAsub.Bcell.markers,"2_annotation/subcluster/scRNAsub.tme.markers.anno.csv",sep=",",quote=F) save(scRNAsub.Bcell.markers,file="2_annotation/subcluster/scRNAsub.tme.markers.afteranno.RData") pdf("2_annotation/subcluster/tsne.bcell.integrate.pdf", width = 10, height = 10) DimPlot(scRNAsub.Bcell, reduction = "tsne", label = TRUE, pt.size=1.5,label.size = 8, split.by = 'label', group.by = 'celltype') dev.off() top30<-scRNAsub.tme.markers %>% group_by(cluster) %>% top_n(n=30,wt=avg_log2FC) write.table(top30,"2_annotation/subcluster/scRNAsub.tme.top30.anno.csv",sep=",",quote=F) require(org.Hs.eg.db) library(topGO) library(DOSE) #devtools::install_github("eliocamp/ggnewscale") library("ggnewscale") x=as.list(org.Hs.egALIAS2EG) geneList<-rep(0,nrow(scRNAsub.Bcell)) names(geneList)<-row.names(scRNAsub.Bcell) geneList<-geneList[intersect(names(geneList),names(x))] newwallgenes=names(geneList) for (ii in 1:length(geneList)){ names(geneList)[ii]<-x[[names(geneList)[ii]]][1] } gene_erichment_results=list() for (c1 in as.character(unique(levels(scRNAsub.Bcell.markers$cluster)))){ print(paste0("RUN ", c1)) testgenes<-subset(scRNAsub.Bcell.markers,cluster==c1)$gene gene_erichment_results[[c1]]=list() testgeneList=geneList testgeneList[which(newwallgenes %in% testgenes)]= 1 #gene_erichment_results=list() tab1=c() for(ont in c("BP","MF")){ sampleGOdata<-suppressMessages(new("topGOdata",description="Simple session",ontology=ont,allGenes=as.factor(testgeneList), nodeSize=10,annot=annFUN.org,mapping="org.Hs.eg.db",ID="entrez")) resultTopGO.elim<-suppressMessages(runTest(sampleGOdata,algorithm="elim",statistic="Fisher")) resultTopGO.classic<-suppressMessages(runTest(sampleGOdata,algorithm="classic",statistic="Fisher")) tab1<-rbind(tab1,GenTable(sampleGOdata,Fisher.elim=resultTopGO.elim,Fisher.classic=resultTopGO.classic,orderBy="Fisher.elim", topNodes=200)) } gene_erichment_results[[c1]][["topGO"]]=tab1 x<-suppressMessages(enrichDO(gene=names(testgeneList)[testgeneList==1],ont="DO",pvalueCutoff=1,pAdjustMethod="BH",universe=names(testgeneList), minGSSize=5,maxGSSize=500,readable=T)) gene_erichment_results[[c1]][["DO"]]=x dgn<-suppressMessages(enrichDGN(names(testgeneList)[testgeneList==1])) gene_erichment_results[[c1]][["DGN"]]=dgn } save(gene_erichment_results,file="2_annotation/anno/Bcellsub.gene_erichment_results.RData") gene_erichment_results[["B_cell-1"]][["topGO"]][1:5,] write.csv(gene_erichment_results[["B_cell-1"]][["topGO"]],"2_annotation/subcluster/Bcellsub.B_cell-1.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["Plasma_cell"]][["topGO"]],"2_annotation/subcluster/Bcellsub.Plasma_cell.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["B_cell-2"]][["topGO"]],"2_annotation/subcluster/Bcellsub.B_cell-2.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["B_cell-3"]][["topGO"]],"2_annotation/subcluster/Bcellsub.B_cell-3.GO.csv",quote=F,row.names=F) names(new.cluster.ids) <- levels(scRNAsub.Bcell) scRNAsub.Bcell <- RenameIdents(scRNAsub.Bcell, new.cluster.ids) scRNAsub.Bcell <- RunUMAP(scRNAsub.Bcell, dims = 1:8) save(scRNAsub.Bcell,file="data/scRNAsub.Bcell.afteranno.RData") scRNAsub.Bcell.markers <- FindAllMarkers(object = scRNAsub.Bcell, only.pos = TRUE, min.pct = 0.25, thresh.use = 0.25) write.table(scRNAsub.Bcell.markers,"subcluster/scRNAsub.Bcell.markers.anno.csv",sep=",",quote=F) save(scRNAsub.Bcell.markers,file="subcluster/scRNAsub.Bcell.markers.afteranno.RData") pdf("subcluster/scRNAsub.Bcell.integrate.pdf", width = 36, height = 18) p1 <- DimPlot(scRNAsub.Bcell, reduction = "umap", group.by = "label") p2<-DimPlot(scRNAsub.Bcell, reduction = "umap", label = TRUE) plot_grid(p1, p2) dev.off() prop.table(table(Idents(scRNAsub.Bcell), scRNAsub.Bcell$label)) allsampleprop.each <-as.data.frame(prop.table(table(Idents(scRNAsub.Bcell), scRNAsub.Bcell$label))) prop.table(table(Idents(scRNAsub.Bcell))) allsampleprop.total <-as.data.frame(prop.table(table(Idents(scRNAsub.Bcell)))) write.csv(x = allsampleprop.each,file = '2_annotation/subcluster/Bcellprop.each.prop.csv',quote = T,row.names = T) write.csv(x = allsampleprop.total,file = '2_annotation/subcluster/Bcellprop.prop.csv',quote = T,row.names = T) table(Idents(scRNAsub.Bcell)) pro.total <- table(Idents(scRNAsub.Bcell),scRNAsub.tme$label) table(Idents(scRNAsub.tme),scRNAsub.Bcell$label) pro.each <- table(Idents(scRNAsub.Bcell),scRNAsub.Bcell$label) write.csv(x =pro.total,file = '2_annotation/subcluster/Bcellanno.pro.total.csv',quote = T,row.names = T) write.csv(x =pro.each,file = '2_annotation/subcluster/Bcellanno.pro.each.csv',quote = T,row.names = T) pdf("results/pca16res0.3/umap.pca16.res0.3.integrate.pdf", width = 36, height = 18) p1 <- DimPlot(glioma.combined.pca16, reduction = "umap", group.by = "label") p2<-DimPlot(glioma.combined.pca16, reduction = "umap", label = TRUE) plot_grid(p1, p2) Bcell.markers <- FindAllMarkers(object = scRNAsub.Bcell, only.pos = TRUE, min.pct = 0.25, thresh.use = 0.25) save(WBY.pca21.markers,file="2_annotation/seurat/WBY.pca21.markers.res0.7.RData") top30<-WBY.pca21.markers %>% group_by(cluster) %>% top_n(n=30,wt=avg_log2FC) plot1 = DimPlot(scRNAsub.Bcell, reduction = "tsne") ggsave("2_annotation/subcluster/Bcell.tSNE.pdf", plot = plot1, width = 8, height = 7) ggsave("2_annotation/subcluster/Bcell.tSNE.png", plot = plot1, width = 8, height = 7) ###DEGs analysis macrophage.cells <- subset(WBY.combined, idents = "Macrophage") Idents(macrophage.cells) <- "label" avg.macrophage.cells <- as.data.frame(log1p(AverageExpression(macrophage.cells, verbose = FALSE)$RNA)) avg.macrophage.cells$gene <- rownames(avg.macrophage.cells) write.table(avg.macrophage.cells,"2_annotation/DEGs/avg.macrophage.cells.csv",sep=",",quote=F) WBY.combined$celltype.label <- paste(Idents(WBY.combined), WBY.combined$label, sep = "_") WBY.combined$celltype <- Idents(WBY.combined) Idents(WBY.combined) <- "celltype.label" scRNAsub.macrophage.data <- subset(WBY.combined, subset = (celltype.label == "Macrophage_cancer" | celltype.label == "Macrophage_normal")) write.table(GetAssayData(scRNAsub.macrophage.data),"macrophage.data.csv",sep=",",quote=F) immune.response <- FindMarkers(WBY.combined, ident.1 = "Macrophage_cancer", ident.2 = "Macrophage_normal", verbose = FALSE) head(immune.response, n = 15) write.table(immune.response,"2_annotation/DEGs/macrophage.degs.csv",sep=",") degs_macrophage<-immune.response degs_filtered<-degs_macrophage[(degs_macrophage$avg_log2FC>log2(1.5)|degs_macrophage$avg_log2FC<=-log2(1.5) ) & (degs_macrophage$p_val_adj<0.05),] features_degs<-degs_filtered[order(degs_filtered$avg_log2FC),] pdf("2_annotation/DEGs/macrophage.heatmap.pdf",width = 20, height = 18) DoHeatmap(macrophage.cells, features = row.names(features_degs)) + NoLegend() dev.off() pdf("2_annotation/DEGs/macrophage.heatmap.pdf",width = 20, height = 18) DoHeatmap(macrophage.cells, features = row.names(features_degs)) dev.off() ### T cell WBY.combined$celltype<-Idents(WBY.combined) WBY_cancer<-subset(x=WBY.combined,subset = label == "cancer") T_cell.subset <- subset(WBY_cancer@meta.data, celltype=="T_cell") scRNAsub.T_cell <- subset(WBY_cancer, cells=row.names(T_cell.subset)) scRNAsub.T_cell <- FindVariableFeatures(scRNAsub.T_cell, selection.method = "vst", nfeatures = 2000) scale.genes.T_cell <- rownames(scRNAsub.T_cell) scRNAsub.T_cell <- ScaleData(scRNAsub.T_cell, features = scale.genes.T_cell) scRNAsub.T_cell <- RunPCA(scRNAsub.T_cell, features = VariableFeatures(scRNAsub.T_cell)) pdf("2_annotation/subcluster/Determine.T_cell.pcnumber.pdf") ElbowPlot(scRNAsub.T_cell, ndims=20, reduction="pca") dev.off() pc.num=1:9 ##??????? scRNAsub.T_cell <- FindNeighbors(scRNAsub.T_cell, dims = pc.num) scRNAsub.T_cell <- FindClusters(scRNAsub.T_cell, resolution = 0.8) table(scRNAsub.T_cell@meta.data$seurat_clusters) metadata <- scRNAsub.T_cell@meta.data cell_cluster <- data.frame(cell_ID=rownames(metadata), cluster_ID=metadata$seurat_clusters) write.csv(cell_cluster,'2_annotation/subcluster/T_cell.cell_cluster.csv',row.names = F) ##???????? #tSNE scRNAsub.T_cell = RunTSNE(scRNAsub.T_cell, dims = pc.num) embed_tsne <- Embeddings(scRNAsub.T_cell, 'tsne') write.csv(embed_tsne,'2_annotation/subcluster/T_cell.embed_tsne.csv') pdf("2_annotation/subcluster/tsne_T_cell.pdf") DimPlot(scRNAsub.T_cell, reduction = "tsne", label = TRUE, pt.size=1.5,label.size = 8) + NoLegend() dev.off() diff.wilcox = FindAllMarkers(scRNAsub.T_cell) all.markers = diff.wilcox %>% select(gene, everything()) %>% subset(p_val<0.05) top30 = all.markers %>% group_by(cluster) %>% top_n(n = 30, wt = avg_log2FC) write.csv(all.markers, "2_annotation/subcluster/T_cell.diff_genes_wilcox.csv", row.names = F) write.csv(top30, "2_annotation/subcluster/T_cell.top30_diff_genes_wilcox.csv", row.names = F) save(scRNAsub.T_cell,file="2_annotation/subcluster/scRNAsub.T_cell.RData") library(SingleR) #refdata <- MonacoImmuneData() hpca.se <- HumanPrimaryCellAtlasData() bpe.se <- BlueprintEncodeData() #immu.se <- DatabaseImmuneCellExpressionData() testdata <- GetAssayData(scRNAsub.T_cell, slot="data") clusters <- scRNAsub.T_cell@meta.data$seurat_clusters cellpred <- SingleR(test = testdata, ref = list(HP = hpca.se , BP = bpe.se), labels = list(hpca.se$label.main , bpe.se$label.main), method = "cluster", clusters = clusters, assay.type.test = "logcounts", assay.type.ref = "logcounts",de.method="wilcox") table(cellpred$labels) pdf("2_annotation/subcluster/test.pdf", width=18 ,height=9) plotScoreHeatmap(cellpred) dev.off() celltype = data.frame(ClusterID=rownames(cellpred), celltype=cellpred$labels, stringsAsFactors = F) write.csv(celltype,"2_annotation/subcluster/T_cell.celltype_singleR.csv",row.names = F) scRNAsub.T_cell@meta.data$celltype = "NA" for(i in 1:nrow(celltype)){ scRNAsub.T_cell@meta.data[which(scRNAsub.T_cell@meta.data$seurat_clusters == celltype$ClusterID[i]),'celltype'] <- celltype$celltype[i]} p1 = DimPlot(scRNAsub.T_cell, group.by="celltype", label=T, label.size=5, reduction='tsne') p2 = DimPlot(scRNAsub.T_cell, group.by="celltype", label=T, label.size=5, reduction='umap') p3 = plotc <- p1+p2+ plot_layout(guides = 'collect') ggsave("2_annotation/subcluster/T_cell.tSNE_celltype.pdf", p1, width=7 ,height=6) ggsave("2_annotation/subcluster/T_cell.UMAP_celltype.pdf", p2, width=10 ,height=6) ggsave("2_annotation/subcluster/T_cell.celltype.pdf", p3, width=10 ,height=5) ggsave("2_annotation/subcluster/T_cell.celltype.png", p3, width=10 ,height=5) diff.wilcox = FindAllMarkers(scRNAsub.T_cell) all.markers = diff.wilcox %>% select(gene, everything()) %>% subset(p_val<0.05) top30 = all.markers %>% group_by(cluster) %>% top_n(n = 30, wt = avg_log2FC) require(org.Hs.eg.db) library(topGO) library(DOSE) #devtools::install_github("eliocamp/ggnewscale") library("ggnewscale") x=as.list(org.Hs.egALIAS2EG) geneList<-rep(0,nrow(scRNAsub.T_cell)) names(geneList)<-row.names(scRNAsub.T_cell) geneList<-geneList[intersect(names(geneList),names(x))] newwallgenes=names(geneList) for (ii in 1:length(geneList)){ names(geneList)[ii]<-x[[names(geneList)[ii]]][1] } gene_erichment_results=list() for (c1 in as.character(unique(levels(all.markers$cluster)))){ print(paste0("RUN ", c1)) testgenes<-subset(all.markers,cluster==c1)$gene gene_erichment_results[[c1]]=list() testgeneList=geneList testgeneList[which(newwallgenes %in% testgenes)]= 1 #gene_erichment_results=list() tab1=c() for(ont in c("BP","MF")){ sampleGOdata<-suppressMessages(new("topGOdata",description="Simple session",ontology=ont,allGenes=as.factor(testgeneList), nodeSize=10,annot=annFUN.org,mapping="org.Hs.eg.db",ID="entrez")) resultTopGO.elim<-suppressMessages(runTest(sampleGOdata,algorithm="elim",statistic="Fisher")) resultTopGO.classic<-suppressMessages(runTest(sampleGOdata,algorithm="classic",statistic="Fisher")) tab1<-rbind(tab1,GenTable(sampleGOdata,Fisher.elim=resultTopGO.elim,Fisher.classic=resultTopGO.classic,orderBy="Fisher.elim", topNodes=200)) } gene_erichment_results[[c1]][["topGO"]]=tab1 x<-suppressMessages(enrichDO(gene=names(testgeneList)[testgeneList==1],ont="DO",pvalueCutoff=1,pAdjustMethod="BH",universe=names(testgeneList), minGSSize=5,maxGSSize=500,readable=T)) gene_erichment_results[[c1]][["DO"]]=x dgn<-suppressMessages(enrichDGN(names(testgeneList)[testgeneList==1])) gene_erichment_results[[c1]][["DGN"]]=dgn } save(gene_erichment_results,file="2_annotation/subcluster/T_cell_gene_erichment_results.RData") write.csv(gene_erichment_results[["T_helper"]][["topGO"]],"2_annotation/subcluster/Tcellsub.T_helper.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["NKT"]][["topGO"]],"2_annotation/subcluster/Tcellsub.NKT.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["Multilymphoid_progenitor_cell"]][["topGO"]],"2_annotation/subcluster/Tcellsub.MPC.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["T_cell"]][["topGO"]],"2_annotation/subcluster/Tcellsub.T_cell.csv",quote=F,row.names=F) load("2_annotation/subcluster/scRNAsub.T_cell.RData") new.cluster.ids<-c("T_helper", "NKT", "Multilymphoid_progenitor_cell", "NKT", "Multilymphoid_progenitor_cell","NA", "T_cell", "NA") names(new.cluster.ids) <- levels(scRNAsub.T_cell) scRNAsub.T_cell <- RenameIdents(scRNAsub.T_cell, new.cluster.ids) scRNAsub.T_cell$celltype<-Idents(scRNAsub.T_cell ) scRNAsub.T_cell_rmNA <- subset(scRNAsub.T_cell, subset = (celltype == "T_helper" | celltype == "NKT" | celltype == "Multilymphoid_progenitor_cell" | celltype == "T_cell")) scRNAsub.T_cell<-scRNAsub.T_cell_rmNA scRNAsub.T_cell <- RunUMAP(scRNAsub.T_cell, dims = 1:8) scRNAsub.T_cell$celltype<-Idents(scRNAsub.T_cell) save(scRNAsub.T_cell,file="2_annotation/subcluster/scRNAsub.T_cell.afteranno.RData") scRNAsub.T_cell.markers <- FindAllMarkers(object = scRNAsub.T_cell, only.pos = TRUE, min.pct = 0.25, thresh.use = 0.25) write.table(scRNAsub.T_cell.markers,"2_annotation/subcluster/scRNAsub.T_cell.markers.anno.csv",sep=",",quote=F) save(scRNAsub.T_cell.markers,file="2_annotation/subcluster/scRNAsub.T_cell.markers.afteranno.RData") pdf("2_annotation/subcluster/tsne.Tcell.integrate.pdf", width = 10, height = 10) DimPlot(scRNAsub.T_cell, reduction = "tsne", label = TRUE, pt.size=1.5,label.size = 8, split.by = 'label', group.by = 'celltype') dev.off() top30<-scRNAsub.T_cell.markers %>% group_by(cluster) %>% top_n(n=30,wt=avg_log2FC) write.table(top30,"2_annotation/subcluster/scRNAsub.T_cell.top30.anno.csv",sep=",",quote=F) features.plot <- c("LTB","NEAT1","IL7R","DUSP1","CCL5","JUNB","UBE2C","STMN1","BIRC5","NCL","HNRNPA3","DUT") pdf("2_annotation/subcluster/Tcellsub.dittoDotPlot.pdf",width = 9, height = 4) DotPlot(object = scRNAsub.T_cell, features=features.plot,dot.scale = 12,cols = c("lightgrey", "red")) + RotatedAxis() dev.off() prop.table(table(Idents(scRNAsub.T_cell), scRNAsub.T_cell$label)) allsampleprop.each <-as.data.frame(prop.table(table(Idents(scRNAsub.T_cell), scRNAsub.T_cell$label))) prop.table(table(Idents(scRNAsub.T_cell))) allsampleprop.total <-as.data.frame(prop.table(table(Idents(scRNAsub.T_cell)))) write.csv(x = allsampleprop.each,file = '2_annotation/subcluster/Tcellprop.each.prop.csv',quote = T,row.names = T) write.csv(x = allsampleprop.total,file = '2_annotation/subcluster/Tcellprop.prop.csv',quote = T,row.names = T) table(Idents(scRNAsub.T_cell)) pro.total <- table(Idents(scRNAsub.T_cell),scRNAsub.T_cell$label) table(Idents(scRNAsub.T_cell),scRNAsub.T_cell$label) pro.each <- table(Idents(scRNAsub.T_cell),scRNAsub.T_cell$label) write.csv(x =pro.total,file = '2_annotation/subcluster/Tcellanno.pro.total.csv',quote = T,row.names = T) write.csv(x =pro.each,file = '2_annotation/subcluster/Tcellanno.pro.each.csv',quote = T,row.names = T) ## Dendritic_cell WBY.combined$celltype<-Idents(WBY.combined) WBY_cancer<-subset(x=WBY.combined,subset = label == "cancer") CD8PlusDendritic_cell.subset <- subset(WBY_cancer@meta.data, celltype=="Dendritic_cell") scRNAsub.CD8PlusDendritic_cell <- subset(WBY_cancer, cells=row.names(CD8PlusDendritic_cell.subset)) scRNAsub.CD8PlusDendritic_cell <- FindVariableFeatures(scRNAsub.CD8PlusDendritic_cell, selection.method = "vst", nfeatures = 2000) scale.genes.CD8PlusDendritic_cell <- rownames(scRNAsub.CD8PlusDendritic_cell) scRNAsub.CD8PlusDendritic_cell <- ScaleData(scRNAsub.CD8PlusDendritic_cell, features = scale.genes.CD8PlusDendritic_cell) scRNAsub.CD8PlusDendritic_cell <- RunPCA(scRNAsub.CD8PlusDendritic_cell, features = VariableFeatures(scRNAsub.CD8PlusDendritic_cell)) pdf("2_annotation/subcluster/Determine.CD8PlusDendritic_cell.pcnumber.pdf") ElbowPlot(scRNAsub.CD8PlusDendritic_cell, ndims=20, reduction="pca") dev.off() pc.num=1:18 scRNAsub.CD8PlusDendritic_cell <- FindNeighbors(scRNAsub.CD8PlusDendritic_cell, dims = pc.num) scRNAsub.CD8PlusDendritic_cell <- FindClusters(scRNAsub.CD8PlusDendritic_cell, resolution = 1) table(scRNAsub.CD8PlusDendritic_cell@meta.data$seurat_clusters) metadata <- scRNAsub.CD8PlusDendritic_cell@meta.data cell_cluster <- data.frame(cell_ID=rownames(metadata), cluster_ID=metadata$seurat_clusters) write.csv(cell_cluster,'2_annotation/subcluster/CD8PlusDendritic_cell.cell_cluster.csv',row.names = F) #tSNE scRNAsub.CD8PlusDendritic_cell = RunTSNE(scRNAsub.CD8PlusDendritic_cell, dims = pc.num) embed_tsne <- Embeddings(scRNAsub.CD8PlusDendritic_cell, 'tsne') write.csv(embed_tsne,'2_annotation/subcluster/CD8PlusDendritic_cell.embed_tsne.csv') pdf("2_annotation/subcluster/tsne_CD8PlusDendritic_cell.pdf") DimPlot(scRNAsub.CD8PlusDendritic_cell, reduction = "tsne", label = TRUE, pt.size=1.5,label.size = 8) dev.off() diff.wilcox = FindAllMarkers(scRNAsub.CD8PlusDendritic_cell) all.markers = diff.wilcox %>% select(gene, everything()) %>% subset(p_val<0.05) top30 = all.markers %>% group_by(cluster) %>% top_n(n = 30, wt = avg_log2FC) write.csv(all.markers, "2_annotation/subcluster/CD8PlusDendritic_cell.diff_genes_wilcox.csv", row.names = F) write.csv(top30, "2_annotation/subcluster/CD8PlusDendritic_cell.top30_diff_genes_wilcox.csv", row.names = F) save(scRNAsub.CD8PlusDendritic_cell,file="2_annotation/subcluster/scRNAsub.CD8PlusDendritic_cell.RData") library(SingleR) #refdata <- MonacoImmuneData() hpca.se <- HumanPrimaryCellAtlasData() bpe.se <- BlueprintEncodeData() #immu.se <- DatabaseImmuneCellExpressionData() testdata <- GetAssayData(scRNAsub.CD8PlusDendritic_cell, slot="data") clusters <- scRNAsub.CD8PlusDendritic_cell@meta.data$seurat_clusters cellpred <- SingleR(test = testdata, ref = list(HP = hpca.se , BP = bpe.se), labels = list(hpca.se$label.main , bpe.se$label.main), method = "cluster", clusters = clusters, assay.type.test = "logcounts", assay.type.ref = "logcounts",de.method="wilcox") table(cellpred$labels) pdf("2_annotation/subcluster/test.pdf", width=18 ,height=9) plotScoreHeatmap(cellpred) dev.off() celltype = data.frame(ClusterID=rownames(cellpred), celltype=cellpred$labels, stringsAsFactors = F) write.csv(celltype,"2_annotation/subcluster/CD8PlusDendritic_cell.celltype_singleR.csv",row.names = F) scRNAsub.CD8PlusDendritic_cell@meta.data$celltype = "NA" for(i in 1:nrow(celltype)){ scRNAsub.CD8PlusDendritic_cell@meta.data[which(scRNAsub.CD8PlusDendritic_cell@meta.data$seurat_clusters == celltype$ClusterID[i]),'celltype'] <- celltype$celltype[i]} p1 = DimPlot(scRNAsub.CD8PlusDendritic_cell, group.by="celltype", label=T, label.size=5, reduction='tsne') p2 = DimPlot(scRNAsub.CD8PlusDendritic_cell, group.by="celltype", label=T, label.size=5, reduction='umap') p3 = plotc <- p1+p2+ plot_layout(guides = 'collect') ggsave("2_annotation/subcluster/CD8PlusDendritic_cell.tSNE_celltype.pdf", p1, width=7 ,height=6) ggsave("2_annotation/subcluster/CD8PlusDendritic_cell.UMAP_celltype.pdf", p2, width=10 ,height=6) ggsave("2_annotation/subcluster/CD8PlusDendritic_cell.celltype.pdf", p3, width=10 ,height=5) ggsave("2_annotation/subcluster/CD8PlusDendritic_cell.celltype.png", p3, width=10 ,height=5) diff.wilcox = FindAllMarkers(scRNAsub.CD8PlusDendritic_cell) all.markers = diff.wilcox %>% select(gene, everything()) %>% subset(p_val<0.05) top30 = all.markers %>% group_by(cluster) %>% top_n(n = 30, wt = avg_log2FC) write.csv(top30, "2_annotation/subcluster/CD8PlusDendritic_cell.top30_diff_genes_wilcox.csv", row.names = F) prop.table(table(Idents(scRNAsub.CD8PlusDendritic_cell), scRNAsub.CD8PlusDendritic_cell$label)) allsampleprop.each <-as.data.frame(prop.table(table(Idents(scRNAsub.CD8PlusDendritic_cell), scRNAsub.CD8PlusDendritic_cell$label))) prop.table(table(Idents(scRNAsub.CD8PlusDendritic_cell))) allsampleprop.total <-as.data.frame(prop.table(table(Idents(scRNAsub.CD8PlusDendritic_cell)))) write.csv(x = allsampleprop.each,file = '2_annotation/subcluster/Denprop.each.prop.csv',quote = T,row.names = T) write.csv(x = allsampleprop.total,file = '2_annotation/subcluster/Denprop.prop.csv',quote = T,row.names = T) table(Idents(scRNAsub.CD8PlusDendritic_cell)) pro.total <- table(Idents(scRNAsub.CD8PlusDendritic_cell),scRNAsub.CD8PlusDendritic_cell$label) table(Idents(scRNAsub.CD8PlusDendritic_cell),scRNAsub.CD8PlusDendritic_cell$label) pro.each <- table(Idents(scRNAsub.CD8PlusDendritic_cell),scRNAsub.CD8PlusDendritic_cell$label) write.csv(x =pro.total,file = '2_annotation/subcluster/Denanno.pro.total.csv',quote = T,row.names = T) write.csv(x =pro.each,file = '2_annotation/subcluster/Denanno.pro.each.csv',quote = T,row.names = T) require(org.Hs.eg.db) library(topGO) library(DOSE) #devtools::install_github("eliocamp/ggnewscale") library("ggnewscale") x=as.list(org.Hs.egALIAS2EG) geneList<-rep(0,nrow(scRNAsub.CD8PlusDendritic_cell)) names(geneList)<-row.names(scRNAsub.CD8PlusDendritic_cell) geneList<-geneList[intersect(names(geneList),names(x))] newwallgenes=names(geneList) for (ii in 1:length(geneList)){ names(geneList)[ii]<-x[[names(geneList)[ii]]][1] } gene_erichment_results=list() for (c1 in as.character(unique(levels(all.markers$cluster)))){ print(paste0("RUN ", c1)) testgenes<-subset(all.markers,cluster==c1)$gene gene_erichment_results[[c1]]=list() testgeneList=geneList testgeneList[which(newwallgenes %in% testgenes)]= 1 #gene_erichment_results=list() tab1=c() for(ont in c("BP","MF")){ sampleGOdata<-suppressMessages(new("topGOdata",description="Simple session",ontology=ont,allGenes=as.factor(testgeneList), nodeSize=10,annot=annFUN.org,mapping="org.Hs.eg.db",ID="entrez")) resultTopGO.elim<-suppressMessages(runTest(sampleGOdata,algorithm="elim",statistic="Fisher")) resultTopGO.classic<-suppressMessages(runTest(sampleGOdata,algorithm="classic",statistic="Fisher")) tab1<-rbind(tab1,GenTable(sampleGOdata,Fisher.elim=resultTopGO.elim,Fisher.classic=resultTopGO.classic,orderBy="Fisher.elim", topNodes=200)) } gene_erichment_results[[c1]][["topGO"]]=tab1 x<-suppressMessages(enrichDO(gene=names(testgeneList)[testgeneList==1],ont="DO",pvalueCutoff=1,pAdjustMethod="BH",universe=names(testgeneList), minGSSize=5,maxGSSize=500,readable=T)) gene_erichment_results[[c1]][["DO"]]=x dgn<-suppressMessages(enrichDGN(names(testgeneList)[testgeneList==1])) gene_erichment_results[[c1]][["DGN"]]=dgn } save(gene_erichment_results,file="2_annotation/subcluster/CD8PlusDendritic_cell_gene_erichment_results.RData") write.csv(gene_erichment_results[["cDC"]][["topGO"]],"2_annotation/subcluster/CD8PlusDendritic_cellsub.cDC.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["pDC"]][["topGO"]],"2_annotation/subcluster/CD8PlusDendritic_cellsub.pDC.GO.csv",quote=F,row.names=F) write.csv(gene_erichment_results[["mDC"]][["topGO"]],"2_annotation/subcluster/CD8PlusDendritic_cellsub.mDC.GO.csv",quote=F,row.names=F) library(enrichplot) #CD8PlusDendritic_cell_0 gene_erichment_results[["Dendritic_cell"]][["topGO"]][1:5,] pdf("2_annotation/subcluster/CD8PlusDendritic_cell_Dendritic_cell.pdf",width=8,height=10) dotplot(gene_erichment_results[["Dendritic_cell"]][["DGN"]], showCategory=30) dev.off() #CD8PlusDendritic_cell_1 gene_erichment_results[["Monocyte_derived_dendritic_cell"]][["topGO"]][1:5,] pdf("2_annotation/subcluster/CD8PlusDendritic_cell_Monocyte_derived_dendritic_cell.pdf",width=8,height=10) dotplot(gene_erichment_results[["Monocyte_derived_dendritic_cell"]][["DGN"]], showCategory=30) dev.off() #CD8PlusDendritic_cell_2 gene_erichment_results[["NPC"]][["topGO"]][1:5,] pdf("2_annotation/subcluster/CD8PlusDendritic_cell_NPC.pdf",width=8,height=10) dotplot(gene_erichment_results[["NPC"]][["DGN"]], showCategory=30) dev.off() #CD8PlusDendritic_cell_3 gene_erichment_results[["Lymphoid_dendritic_cells"]][["topGO"]][1:5,] pdf("2_annotation/subcluster/CD8PlusDendritic_cell_Lymphoid_dendritic_cells.pdf",width=8,height=10) dotplot(gene_erichment_results[["Lymphoid_dendritic_cells"]][["DGN"]], showCategory=30) dev.off() load("2_annotation/subcluster/scRNAsub.CD8PlusDendritic_cell.RData") new.cluster.ids<-c("cDC", "pDC", "mDC", "NA","NA") names(new.cluster.ids) <- levels(scRNAsub.CD8PlusDendritic_cell) scRNAsub.CD8PlusDendritic_cell <- RenameIdents(scRNAsub.CD8PlusDendritic_cell, new.cluster.ids) scRNAsub.CD8PlusDendritic_cell$celltype<-Idents(scRNAsub.CD8PlusDendritic_cell ) scRNAsub.CD8PlusDendritic_cell_rmNA <- subset(scRNAsub.CD8PlusDendritic_cell, subset = (celltype == "cDC" | celltype == "pDC" | celltype == "mDC")) scRNAsub.CD8PlusDendritic_cell<-scRNAsub.CD8PlusDendritic_cell_rmNA scRNAsub.CD8PlusDendritic_cell <- RunUMAP(scRNAsub.CD8PlusDendritic_cell, dims = 1:18) scRNAsub.CD8PlusDendritic_cell$celltype<-Idents(scRNAsub.CD8PlusDendritic_cell) save(scRNAsub.CD8PlusDendritic_cell,file="2_annotation/subcluster/scRNAsub.CD8PlusDendritic_cell.afteranno.RData") scRNAsub.CD8PlusDendritic_cell.markers <- FindAllMarkers(object = scRNAsub.CD8PlusDendritic_cell, only.pos = TRUE, min.pct = 0.25, thresh.use = 0.25) write.table(scRNAsub.CD8PlusDendritic_cell.markers,"2_annotation/subcluster/scRNAsub.CD8PlusDendritic_cell.markers.anno.csv",sep=",",quote=F) save(scRNAsub.CD8PlusDendritic_cell.markers,file="2_annotation/subcluster/scRNAsub.CD8PlusDendritic_cell.markers.afteranno.RData") pdf("2_annotation/subcluster/tsne.CD8PlusDendritic_cell.integrate.pdf", width = 10, height = 10) DimPlot(scRNAsub.CD8PlusDendritic_cell, reduction = "tsne", label = TRUE, pt.size=1.5,label.size = 8, split.by = 'label', group.by = 'celltype') dev.off() pdf("2_annotation/subcluster/tsne.CD8PlusDendritic_cell.integrate.nolegend.pdf", width = 10, height = 10) DimPlot(scRNAsub.CD8PlusDendritic_cell, reduction = "tsne", label = TRUE, pt.size=1.5,label.size = 8, split.by = 'label', group.by = 'celltype')+NoLegend() dev.off() top30<-scRNAsub.CD8PlusDendritic_cell.markers %>% group_by(cluster) %>% top_n(n=30,wt=avg_log2FC) write.table(top30,"2_annotation/subcluster/scRNAsub.CD8PlusDendritic_cell.top30.anno.csv",sep=",",quote=F) features.plot <- c("HIST1H4C","STMN1","HMGB2","IGLC2","GAS5","IL32","CST3","HLA-DPA1","HLA-DQB1") pdf("2_annotation/subcluster/CD8PlusDendritic_cell.dittoDotPlot.pdf",width = 10, height = 5) DotPlot(object = scRNAsub.CD8PlusDendritic_cell, features = features.plot,dot.scale = 12,cols = c("lightgrey", "red")) + RotatedAxis() dev.off() Meningeal_cell.cells <- subset(WBY.combined, idents = "Meningeal_cell") Idents(Meningeal_cell.cells) <- "label" avg.Meningeal_cell.cells <- as.data.frame(log1p(AverageExpression(Meningeal_cell.cells, verbose = FALSE)$RNA)) avg.Meningeal_cell.cells$gene <- rownames(avg.Meningeal_cell.cells) write.table(avg.Meningeal_cell.cells,"2_annotation/DEGs/avg.Meningeal_cell.cells.csv",sep=",",quote=F) WBY.combined$celltype.label <- paste(Idents(WBY.combined), WBY.combined$label, sep = "_") WBY.combined$celltype <- Idents(WBY.combined) Idents(WBY.combined) <- "celltype.label" Meningeal_cell.response <- FindMarkers(WBY.combined, ident.1 = "Meningeal_cell_cancer", ident.2 = "Meningeal_cell_normal", verbose = FALSE) head(Meningeal_cell.response, n = 15) write.table(Meningeal_cell.response,"2_annotation/DEGs/Meningeal_cell.degs.csv",sep=",") degs_meningeal<-Meningeal_cell.response degs_filtered<-degs_meningeal[(degs_meningeal$avg_log2FC>log2(1.5)|degs_meningeal$avg_log2FC<=-log2(1.5) ) & (degs_meningeal$p_val_adj<0.05),] features_degs<-degs_filtered[order(degs_filtered$avg_log2FC),] pdf("2_annotation/DEGs/meningeal.heatmap.pdf",width = 20, height = 18) DoHeatmap(Meningeal_cell.cells, features = row.names(features_degs)) + NoLegend() dev.off() degs_meningeal<-Meningeal_cell.response degs_filtered<-degs_meningeal[(degs_meningeal$avg_log2FC>log2(1.5)|degs_meningeal$avg_log2FC<=-log2(1.5) ) & (degs_meningeal$p_val_adj<0.05),] features_degs<-degs_filtered[order(degs_filtered$avg_log2FC),] pdf("2_annotation/DEGs/meningeal.heatmap.label.pdf",width = 20, height = 18) DoHeatmap(Meningeal_cell.cells, features = row.names(features_degs)) dev.off() pdf("2_annotation/DEGs/Meningeal_cell.figure1.pdf",width = 20, height = 18) FeaturePlot(WBY.combined, features = c("IL6ST","IRF1","PRDM1","IGFBP1","IGFBP2"), reduction = "tsne", split.by = "label", max.cutoff = 3, cols = c("grey", "red")) dev.off() pdf("2_annotation/DEGs/Meningeal_cell.figure2.pdf",width = 10, height = 18) plots <- VlnPlot(WBY.combined, features = c("CARD16","IRF1","PRDM1","IGFBP2","IGFBP7"), split.by = "label", group.by = "celltype", pt.size = 0, combine = FALSE) wrap_plots(plots = plots, ncol = 1) dev.off() pdf("2_annotation/DEGs/Meningeal_cell.figure3.pdf") genes.to.label = c("CARD16","IRF1","PRDM1","IGFBP2","IGFBP7") p1 <- ggplot(avg.Meningeal_cell.cells, aes(cancer, normal)) + geom_point() + ggtitle("Meningeal_cell") p1 <- LabelPoints(plot = p1, points = genes.to.label, repel = TRUE) p1 dev.off() ##############################################################################################################################
4fef26fd9dbc9ca88ab2da0f41a37e8076bcd20a
5d6ac20f8e20d5c7739c68e7d44542f3bc5f8ba7
/R/grid2.R
a55f90ad65b8ebd026c426a240307f5d844da0ee
[]
no_license
kl-lab/fformpp
d4585c8a8359e1d0a15bbcea379ffa54488e0992
1ec46c507e0c4781a8d274fb69354f7b778df92e
refs/heads/master
2022-11-16T14:36:59.297031
2020-07-14T14:51:23
2020-07-14T14:51:23
null
0
0
null
null
null
null
UTF-8
R
false
false
200
r
grid2.R
##' Add grids on plot ##' ##' @export grid2 <- function(x.at = NA, y.at = NA, col = "black", lty="dotted", lwd = 0.5, ...) { abline(h = y.at, v = x.at, col = col, lty = lty, lwd = lwd, ...) }
ec40df02cfe540c751e8221ad834516f07f72228
ccf77c83c0c4a328b7d6e353ad85ce4d2bf199d6
/R/summarize_model_results.R
c11e8fe0f879fcab213c8cdaeb52c35a79938c0a
[]
no_license
FerreiraAM/CyTOFpower
6c314ad5e842dcc3ac0c5481168f38b5f6c0fe01
0ba3553ad1c288fc35c89bbd25e46c4f1cf76f66
refs/heads/master
2023-08-29T10:09:27.221017
2021-10-18T20:40:35
2021-10-18T20:40:35
355,366,603
0
0
null
2021-10-13T01:51:48
2021-04-07T00:32:49
R
UTF-8
R
false
false
1,323
r
summarize_model_results.R
# Functions to summarize results from the different models #' Summarize data and results. #' #' @details Function to do a summary of the tested data and model's results #' for the CytoGLMM and diffcyt packages. #' #' @param summary_from_model list, output from the functions running the models. #' @param package character, package used to run the test: "CytoGLMM" or "diffcyt". #' #' @return data.frame of results for each simulation. #' #' @keywords internal function_summary_results_models <- function(summary_from_model, package){ # Get package argument package <- match.arg(package, choices = c("CytoGLMM", "diffcyt")) # Rename colnames # if the cytoGLMM package has been used, the column name in the results table # is "protein_name" if(package == "CytoGLMM"){ res_sum <- as.data.frame(summary_from_model$result_summary) colnames(res_sum) <- c("marker_id", "p_val", "p_adj") } else if(package =="diffcyt"){ # if the diffcyt package has been used, the column name in the results table # is "marker_id" res_sum <- as.data.frame(summary_from_model$result_summary[,c("marker_id", "p_val", "p_adj")]) } # Return return(as.data.frame(res_sum)) }
1cbd46b39aa98746196511a1c9563d6ad7ef39be
265fd47d1e5471091acf34c02769f0cf87a931c3
/ml02/ej_e_plot.R
c29aaffc73e38a3f3273d2310d8f0e381e02e9d7
[]
no_license
hgurmendi/machine-learning
1646e4e2d96841afa02f025a101130ae997a844b
72181f5a27dba1f25f498ecfc4f0b66899d16c59
refs/heads/master
2018-10-19T19:04:57.322637
2018-07-23T00:53:56
2018-07-23T00:53:56
86,375,207
0
0
null
null
null
null
UTF-8
R
false
false
1,438
r
ej_e_plot.R
#!/usr/bin/Rscript args <- commandArgs(trailingOnly = TRUE) if (length(args) != 3) { message("USAGE: ./ej07_plot.R parallel_errors diagonal_errors anns_errors") quit() } message("parallel") message(args[1]) message("diagonal") message(args[2]) parallel <- read.csv(args[1], header = TRUE) diagonal <- read.csv(args[2], header = TRUE) anns <- read.csv(args[3], header = FALSE) anns_diagonal <- subset(anns, V1=="diagonal") anns_parallel <- subset(anns, V1=="parallel") minX <- min(parallel$d) maxX <- max(parallel$d) minY <- min(diagonal$TestEAP, parallel$TestEAP, anns_diagonal$V3, anns_parallel$V3) maxY <- max(diagonal$TestEAP, parallel$TestEAP, anns_diagonal$V3, anns_parallel$V3) # red -> diagonal # green -> parallel # solid -> decision tree # dashed -> neural network png("ej_e.png") par(mar=c(4,4,1,1)) # par = parametros de plot, mar = margenes, c(bottom, left, top, right) plot(diagonal$d , diagonal$TestEAP , col = "red" , type = "o" , xlim = c(minX, maxX) , ylim = c(minY, maxY) , xlab = "Dimensions" , ylab = "Error percentage" , lwd = 2 , lty = 1) lines(parallel$d , parallel$TestEAP , col = "green" , type = "o" , lwd = 2 , lty = 1) lines(anns_parallel$V2 , anns_parallel$V3 , col = "green" , type = "o" , lwd = 2 , lty = 2) lines(anns_diagonal$V2 , anns_diagonal$V3 , col = "red" , type = "o" , lwd = 2 , lty = 2)
71d8c9f8d30402dbee3c95359cd7b00143d50376
18fb84b6b827113aea196209b55b34fc846f718c
/man/print.callfest.Rd
84fb24f08fdd3fc427191df2d84c622217d49c92
[]
no_license
vst/callfest
b291ce49598884ff4eecbeb3f43aa28bfca4949b
177c348cd2401b252c574ae07c43bf4a72766d39
refs/heads/master
2021-01-01T05:49:10.127641
2014-12-13T10:03:06
2014-12-13T10:03:06
null
0
0
null
null
null
null
UTF-8
R
false
false
376
rd
print.callfest.Rd
% Generated by roxygen2 (4.0.2): do not edit by hand \name{print.callfest} \alias{print.callfest} \title{Pretty prints the \code{callfest} instance} \usage{ \method{print}{callfest}(x, ...) } \arguments{ \item{x}{A \code{callfest} instance to be pretty printed.} \item{...}{Additional arguments to print method.} } \description{ Pretty prints the \code{callfest} instance }
537b03771687fdd357f02cf471e6393c35b695ea
10fe70854c82345f8bd8669330306c0e5fdcffb4
/function/test_what.R
2608019cbc74e8cde1b3cfbf2def124466c67ada
[]
no_license
yahcong/travel
724f7c40ff91c89cf1580df223af52b241cf55c7
1863d1d89476b81b4dc42e9ded65c4479535982b
refs/heads/master
2021-05-13T15:27:12.628805
2018-01-14T13:16:57
2018-01-14T13:16:57
116,768,809
0
0
null
null
null
null
UTF-8
R
false
false
361
r
test_what.R
rm(list=ls()) library(data.table) setwd("F:/DataMining/R/travel") load("model/randomForest2.rda") library(randomForest) test_action=new_aciton_test_hour str(test_action) test_action$predict_type=predict(fit2,test_action) table(test_action$predict_type) #-------------------predict----------------------# load("data/output/new_userProfile_comment_test.rda")
46f8960aed6fbe78dc4dcf1b7d25dcc5bb6f2270
efde884c9fe091891cc24f765a5d3dfe08eed653
/tests/testthat/test-normalisation.R
6beb66efa0681dce82e029ff2b35b8d637de3529
[]
no_license
koenvandenberge/dynnormaliser
7cd07ff17e4f4903491034dfa4f73fc9940d47a7
41e08d28a0ab83781ed550f3eb3f0f204b4d0752
refs/heads/master
2020-03-09T23:50:26.359309
2018-04-11T09:20:36
2018-04-11T09:20:36
129,066,110
0
0
null
null
null
null
UTF-8
R
false
false
502
r
test-normalisation.R
context("Normalisation") test_that("Testing normalise function", { counts <- matrix(round(2^rnorm(30*50, mean = 6, sd = 2)), ncol=50) counts[sample(c(T, F), length(counts), prob = c("T"=.1, "F"=.9), replace = TRUE)] <- 0 rownames(counts) <- paste0("Cell", seq_len(nrow(counts))) colnames(counts) <- paste0("Gene", seq_len(ncol(counts))) # todo: add mitochondrial and ercc spikeins normd <- normalise_filter_counts(counts) expect_error(normd <- normalise_filter_counts(counts), NA) })
3e5a61973c8b1dde5140b8114ec5f4e3694cd209
297dd41b2457e3d2b2fd0ea9f4fd6dc91ccc0217
/cimis/get_cimis_et.R
b102526ab2c94f1dfc2ccc436f0a84ae0bfd2774
[]
no_license
richpauloo/junkyard
51ee1bdbca9fa343872f03e753dddba08af5cc11
9a38f823805cc86d43a2a2b2523573062ef7ce56
refs/heads/master
2022-08-29T04:31:47.949705
2022-08-15T21:34:33
2022-08-15T21:34:33
164,265,351
0
0
null
null
null
null
UTF-8
R
false
false
6,927
r
get_cimis_et.R
########################################################################## # This script scrapes the last month's ET data from active stations in # California's Central Valley from CIMIS: # * web: https://cimis.water.ca.gov/ # * API: https://et.water.ca.gov/Rest/Index ########################################################################## # packages library(xml2) library(httr) library(dplyr) library(stringr) library(tidyr) library(sp) library(lubridate) ########################################################################## # check for active stations in the central valley ########################################################################## s <- GET("http://et.water.ca.gov/api/station") s <- content(s) cn <- s$Stations[[1]] %>% names() %>% .[-14] l <- lapply(s$Stations, function(x) as.data.frame(x[-14], col.names = cn)) %>% do.call(rbind.data.frame, .) # drop unnecerssary data and clean lat/lon l <- select(l, StationNbr, IsActive, IsEtoStation, HmsLatitude, HmsLongitude) %>% separate(col = HmsLatitude, into = letters[1:2], "/ ") %>% separate(col = HmsLongitude, into = letters[3:4], "/ ") %>% select(- c("a", "c")) %>% rename(lat = b, lng = d) %>% mutate(lat = as.numeric(lat), lng = as.numeric(lng), StationNbr = as.numeric(as.character(StationNbr))) # load central valley shapefile ll <- "+init=epsg:4269 +proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs +towgs84=0,0,0" cv <- raster::shapefile("C:/Users/rpauloo/Documents/Github/junkyard/cimis/data/Alluvial_Bnd.shp") cv <- spTransform(cv, ll) # make stations into spatial object spdf <- SpatialPointsDataFrame(coords = as.matrix(l[,c("lng","lat")]), data = l, proj4string = CRS(ll)) # sanity check plot(cv); points(spdf) # subset of points within cv spdf_in <- spdf[cv, ] # sanity check plot(cv); points(spdf_in, col = "red", pch = 16) # subset for active stations that record Eto # sanity check plot(cv); points(spdf_in[(spdf_in$IsActive == 'True' & spdf_in$IsEtoStation == 'True'), ], col = "red", pch = 16) # active station numbers active_stations <- spdf_in[(spdf_in$IsActive == 'True' & spdf_in$IsEtoStation == 'True'), ]@data %>% pull(StationNbr) %>% as.numeric() # all stations including currently inactive active_stations <- spdf_in[spdf_in$IsEtoStation == 'True', ]@data %>% pull(StationNbr) %>% as.numeric() ########################################################################## # query Eto at active stations for the last month ########################################################################## # length of ET window (today's date minus this many days) len <- 30 # query parameters key <- "43e46605-8d96-491e-aa09-be9a5ca4bcf3" targets <- paste(active_stations, collapse = ",") startdate <- "2001-01-01" #as.character(ymd(substr(Sys.time(), 1, 10)) - len) enddate <- substr(Sys.time(), 1, 10) dataitems <- "day-asce-eto" # url g <- paste0("http://et.water.ca.gov/api/data?appKey=", key, "&targets=", targets, "&startDate=", startdate, "&endDate=", enddate, "&dataItems=", dataitems) r <- GET(g) # GET HTTP response r <- content(r) # response content as list # get data from list # deal with variable number of unequal column lengths using # data.table::rbindlist(. , fill = TRUE) and do light cleaning d <- r$Data$Providers[[1]]$Records %>% lapply(., unlist) %>% lapply(., as.data.frame) %>% lapply(., t) %>% lapply(., as.data.frame) %>% data.table::rbindlist(., fill = TRUE) %>% rename(date = Date, julian = Julian, station = Station, et = DayAsceEto.Value) %>% mutate(date = ymd(date), julian = as.numeric(as.character(julian)), station = as.numeric(as.character(station)), et = as.numeric(as.character(et))) %>% select(date, julian, station, et) # join to station info d <- left_join(d, l, by = c("station" = "StationNbr")) ########################################################################## # split into list by date/julian, interpolate, and save raster output ########################################################################## # make into spatial object dsp <- SpatialPointsDataFrame(coords = as.matrix(d[,c("lng","lat")]), data = d, proj4string = CRS(ll)) dsp <- split(dsp, dsp$date) # interpolate and turn raster into data frame tps <- vector("list", length(dsp)) library(fields) library(raster) dtt <- names(dsp) for(i in 1:length(tps)){ mod <- Tps(dsp[[i]]@data[, c("lng", "lat")], dsp[[i]]@data[, "et"]) r <- raster(cv, nrow = 100, ncol = 100) # res: 0.002008855, 0.002061255 (x, y) r <- interpolate(r, mod) r <- mask(r, cv) tps[[i]] <- as.data.frame(r, xy = TRUE) %>% rename(et = layer) %>% mutate(date = ymd(dtt[i])) } tpsdf <- bind_rows(tps) %>% filter(!is.na(et)) # spplot style binning brks <- seq(min(tpsdf$et), max(tpsdf$et), (max(tpsdf$et) - min(tpsdf$et))/16) %>% round(2) labs <- paste(brks[1:length(brks)-1], brks[2:length(brks)], sep = " - ") tpsdf$etb <- cut(tpsdf$et, breaks = brks, labels = labs) library(gganimate) gifa <- ggplot(tpsdf, aes(x, y)) + geom_raster(aes(fill = et)) + geom_path(data = rename(fortify(cv), x = long, y = lat), aes(x,y, group = group)) + scale_fill_viridis_c(option = "A") + coord_fixed(1.3) + theme_void() + transition_time(date) + labs(title = "Date: {frame_time}", fill = "ET (in)", x = "Lng", y = "Lat") #anim_save("etb.gif", gifa, nframes = length(dtt), fps = 3) # save to root # mercator projection in m and surface area of each cell merc <- "+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs" sa <- prod(res(raster(spTransform(cv, merc), nrow = 100, ncol = 100))) etdf <- tpsdf %>% group_by(date) %>% mutate(etv = et * 0.0254 * sa * 1e-9) %>% # convert inches to m and m3 to km3 summarise(tot_et = sum(etv)) # km3 gifb <- ggplot(etdf, aes(date, tot_et)) + geom_line() + geom_point() + theme_minimal() + labs(x = "Date", y = expression(paste("Total ET ( ", km ^ 3, " )")), title = "Total Daily ET in the Central Valley") + transition_reveal(date) a_gif <- animate(gifa, width = 240, height = 240) b_gif <- animate(gifb, width = 360, height = 240) library(magick) a_mgif <- image_read(a_gif) b_mgif <- image_read(b_gif) new_gif <- image_append(c(a_mgif[1], b_mgif[1])) for(i in 2:100){ combined <- image_append(c(a_mgif[i], b_mgif[i])) new_gif <- c(new_gif, combined) } new_gif anim_save("etcomb.gif", new_gif) # save to root
01ab62b2f986b9af96721ee0548763e576bacfe0
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/StreamMetabolism/examples/simp.Rd.R
a27fdc87b2958605ceba56358e97f39857997dd2
[]
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
324
r
simp.Rd.R
library(StreamMetabolism) ### Name: simp ### Title: Numeric Integration Using Simpson's method ### Aliases: simp ### Keywords: math ### ** Examples # 4-x^2-y^2 fun <- function(x, y){ a <- 4 b <- x^2 d <- y^2 z <- a-b-d return(z) } a <- fun(seq(-1000,1000,1), seq(-1000,1000,1)) simp(a, x=-1000:1000, n=1000)
b9df6252ef6cba18186a808cde95fe4a07d7df8f
5ac57449f8a0cfbc0e9c8f716ab0a578d8606806
/man/temax.Rd
0053701f48ac16c9094b1c71dff69acf00b2b25c
[]
no_license
hugaped/MBNMAtime
bfb6913e25cacd148ed82de5456eb9c5d4f93eab
04de8baa16bf1be4ad7010787a1feb9c7f1b84fd
refs/heads/master
2023-06-09T01:23:14.240105
2023-06-01T12:51:48
2023-06-01T12:51:48
213,945,629
5
0
null
null
null
null
UTF-8
R
false
true
5,233
rd
temax.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/time.functions.R \name{temax} \alias{temax} \title{Emax time-course function} \usage{ temax( pool.emax = "rel", method.emax = "common", pool.et50 = "rel", method.et50 = "common", pool.hill = NULL, method.hill = NULL, p.expon = FALSE ) } \arguments{ \item{pool.emax}{Pooling for Emax parameter. Can take \code{"rel"} or \code{"abs"} (see details).} \item{method.emax}{Method for synthesis of Emax parameter. Can take \verb{"common}, \code{"random"}, or be assigned a numeric value (see details).} \item{pool.et50}{Pooling for ET50 parameter. Can take \code{"rel"} or \code{"abs"} (see details).} \item{method.et50}{Method for synthesis of ET50 parameter. Can take \verb{"common}, \code{"random"}, or be assigned a numeric value (see details).} \item{pool.hill}{Pooling for Hill parameter. Can take \code{"rel"} or \code{"abs"} (see details).} \item{method.hill}{Method for synthesis of Hill parameter. Can take \verb{"common}, \code{"random"}, or be assigned a numeric value (see details).} \item{p.expon}{Should parameters that can only take positive values be modeled on the exponential scale (\code{TRUE}) or should they be assigned a prior that restricts the posterior to positive values (\code{FALSE})} } \value{ An object of \code{class("timefun")} } \description{ ** For version 0.2.3: to ensure positive posterior values, et50 and hill parameters are now modeled on the natural scale using a half-normal prior rather than a symmetrical prior on the exponential scale to improve model stability ** } \details{ \itemize{ \item Emax represents the maximum response. \item ET50 represents the time at which 50\% of the maximum response is achieved. This can only take positive values and so is modeled on the exponential scale and assigned a symmetrical normal prior Alternatively it can be assigned a normal prior truncated at zero (half-normal) (this will be the default in MBNMAtime version >=0.2.3). \item Hill is the Hill parameter, which allows for a sigmoidal function. This can only take positive values and so is modeled on the exponential scale and assigned a symmetrical normal prior Alternatively it can be assigned a normal prior truncated at zero (half-normal) (this will be the default in MBNMAtime version >=0.2.3). } Without Hill parameter: \deqn{\frac{E_{max}\times{x}}{ET_{50}+x}} With Hill parameter: \deqn{\frac{E_{max}\times{x^{hill}}}{ET_{50}\times{hill}+x^{hill}}} } \section{Time-course parameters}{ Time-course parameters in the model must be specified using a \code{pool} and a \code{method} prefix. \code{pool} is used to define the approach used for pooling of a given time-course parameter and can take any of:\tabular{ll}{ \strong{Argument} \tab \strong{Model specification} \cr \code{"rel"} \tab Indicates that \emph{relative} effects should be pooled for this time-course parameter. Relative effects preserve randomisation within included studies, are likely to vary less between studies (only due to effect modification), and allow for testing of consistency between direct and indirect evidence. Pooling follows the general approach for Network Meta-Analysis proposed by \insertCite{lu2004;textual}{MBNMAtime}. \cr \code{"abs"} \tab Indicates that study arms should be pooled across the whole network for this time-course parameter \emph{independently of assigned treatment} to estimate an \emph{absolute} effect. This implies estimating a single value across the network for this time-course parameter, and may therefore be making strong assumptions of similarity. \cr } \code{method} is used to define the model used for meta-analysis for a given time-course parameter and can take any of the following values:\tabular{ll}{ \strong{Argument} \tab \strong{Model specification} \cr \code{"common"} \tab Implies that all studies estimate the same true effect (often called a "fixed effect" meta-analysis) \cr \code{"random"} \tab Implies that all studies estimate a separate true effect, but that each of these true effects vary randomly around a true mean effect. This approach allows for modelling of between-study heterogeneity. \cr \code{numeric()} \tab Assigned a numeric value, indicating that this time-course parameter should not be estimated from the data but should be assigned the numeric value determined by the user. This can be useful for fixing specific time-course parameters (e.g. Hill parameters in Emax functions, power parameters in fractional polynomials) to a single value. \cr } When relative effects are modelled on more than one time-course parameter, correlation between them is automatically estimated using a vague inverse-Wishart prior. This prior can be made slightly more informative by specifying the scale matrix \code{omega} and by changing the degrees of freedom of the inverse-Wishart prior using the \code{priors} argument in \code{mb.run()}. } \examples{ # Model without a Hill parameter temax(pool.emax="rel", method.emax="random", pool.et50="abs", method.et50="common") # Model including a Hill parameter and defaults for Emax and ET50 parameters temax(pool.hill="abs", method.hill="common") } \references{ \insertAllCited }
defeb0db1217403fc2a13f825d911f416947f194
9dd936c7b849d368e9ef2a450ebd32f09ed924da
/man/BrainIQ.Rd
97990df82d6b07288239dd7c64a5fbcb0bf0978e
[]
no_license
cran/MPsychoR
0d12d19c6044ebc9207ae27a41061301f217ae0c
717f2223eecdd97ad55ed9d073410512b1e94077
refs/heads/master
2021-04-03T09:19:37.646636
2020-06-18T05:17:05
2020-06-18T05:17:05
124,736,769
0
0
null
null
null
null
UTF-8
R
false
false
1,591
rd
BrainIQ.Rd
\name{BrainIQ} \alias{BrainIQ} \docType{data} \title{ Brain Size and Intelligence } \description{ Willerman et al. (1991) conducted their study at a large southwestern university. They selected a sample of 40 right-handed Anglo introductory psychology students who had indicated no history of alcoholism, unconsciousness, brain damage, epilepsy, or heart disease. These subjects were drawn from a larger pool of introductory psychology students with total Scholastic Aptitude Test Scores higher than 1350 or lower than 940 who had agreed to satisfy a course requirement by allowing the administration of four subtests (Vocabulary, Similarities, Block Design, and Picture Completion) of the Wechsler (1981) Adult Intelligence Scale-Revised. With prior approval of the University's research review board, students selected for MRI were required to obtain prorated full-scale IQs of greater than 130 or less than 103, and were equally divided by sex and IQ classification. } \usage{ data("BrainIQ") } \format{ A data frame with 40 individuals and the following 7 variables. \describe{ \item{\code{Gender}}{Participant's gender.} \item{\code{FSIQ}}{Full Scale IQ.} \item{\code{VIQ}}{Verbal IQ.} \item{\code{PIQ}}{Performance IQ.} \item{\code{Weight}}{Body weight.} \item{\code{Height}}{Body height.} \item{\code{MRI_Count}}{MRI pixel count (brain size).} } } \source{ Willerman, L., Schultz, R., Rutledge, J. N., & Bigler, E. (1991). In vivo brain size and intelligence. Intelligence, 15, 223-228. } \examples{ data(BrainIQ) str(BrainIQ) } \keyword{datasets}
eb16e09400d638de2b4fd5ba1692d738f7ef6aab
8cbfb091e9444261b9a957bbb745ac04a5ef2c98
/PCAWG_timing.R
c7cbf2eb6e0b30f1841f6562f2c76abc8c8ad225
[]
no_license
smm19900210/PCAWG11-Timing_and_Signatures
2ee400c7828e463a7486aa42126be144cc723c89
015bc714d8e9d45b61fb829b2e66bb634a2e8b43
refs/heads/master
2022-02-11T15:27:11.941919
2019-08-25T16:46:27
2019-08-25T16:46:27
null
0
0
null
null
null
null
UTF-8
R
false
false
10,157
r
PCAWG_timing.R
# Mutational timing of gains in single samples # Libraries and additional code library(VariantAnnotation) library(cancerTiming) source("cancerTiming.WGD.R") # each VCF file is input as argument to script args = commandArgs(TRUE) vcf_filename = args[1] # clustering results clustering_output_path = args[2] # copy number cn_path = args[3] # samplename from VCF id = gsub(".consensus.20160830.somatic.snv_mnv.vcf.gz","",basename(vcf_filename)) print(id) # function to assign mutations as clonal or subclonal assignMuts <- function(subclones_file){ clonal.rows = NULL # define clonal cluster and subclones if (nrow(subclones[subclones$fraction_cancer_cells > 0.9 & subclones$fraction_cancer_cells < 1.1, ]) == 1){ # if there is only one clone between 0.9 and 1.1 # take this as the clone, and add the superclonal mutations # subclones are everything below clonal.row = subclones[subclones$fraction_cancer_cells > 0.9 & subclones$fraction_cancer_cells < 1.1, ] clonal.rows = subset(subclones, fraction_cancer_cells >= clonal.row$fraction_cancer_cells) subclonal.rows = subset(subclones, fraction_cancer_cells < clonal.row$fraction_cancer_cells) no.subclones = nrow(subclonal.rows) # if there is nothing in the range of 0.9 to 1.1 # remove superclone # and count only subclonal clusters and mutations } else if (nrow(subclones[subclones$fraction_cancer_cells > 0.9 & subclones$fraction_cancer_cells < 1.1, ]) == 0){ subclones = subset(subclones, fraction_cancer_cells < 1) clonal.rows = as.data.frame(matrix(ncol=3, nrow=0)) subclonal.rows = subset(subclones, fraction_cancer_cells < 1) no.subclones = nrow(subclonal.rows) # if there are multiple clusters in the range of 0.9 and 1.1 # look between 0.95 and 1.05 } else if (nrow(subclones[subclones$fraction_cancer_cells > 0.9 & subclones$fraction_cancer_cells < 1.1, ]) > 1){ clonal.row.strict = subclones[subclones$fraction_cancer_cells > 0.95 & subclones$fraction_cancer_cells < 1.05,] # if there is only 1 cluster in the strict range if (nrow(clonal.row.strict) == 1){ clonal.row = clonal.row.strict clonal.rows = subset(subclones, fraction_cancer_cells >= clonal.row$fraction_cancer_cells) subclonal.rows = subset(subclones, fraction_cancer_cells < clonal.row$fraction_cancer_cells) no.subclones = nrow(subclonal.rows) # if there are still two clusters in the strict range # then take the larger ccf } else if (nrow(clonal.row.strict) > 1){ clonal.row = clonal.row.strict[which.max(clonal.row.strict$fraction_cancer_cells),] clonal.rows = subset(subclones, fraction_cancer_cells >= clonal.row$fraction_cancer_cells) subclonal.rows = subset(subclones, fraction_cancer_cells < clonal.row$fraction_cancer_cells) no.subclones = nrow(subclonal.rows) # if there is nothing between 0.95 and 1.05 # but two within 0.9 and 1.1 } else if (nrow(clonal.row.strict) == 0){ clonal.row.relaxed = subclones[subclones$fraction_cancer_cells > 0.9 & subclones$fraction_cancer_cells < 1.1, ] clonal.row = clonal.row.relaxed[which.max(clonal.row.relaxed$n_snvs),] clonal.rows = subset(subclones, fraction_cancer_cells >= clonal.row$fraction_cancer_cells) subclonal.rows = subset(subclones, fraction_cancer_cells < clonal.row$fraction_cancer_cells) no.subclones = nrow(subclonal.rows) } } return(clonal.rows) } # these are all files available for the clustering clustering_output_files = list.files(clustering_output_path, pattern = "cluster_assignments.txt.gz", recursive=FALSE, full.names = TRUE) subclonal_structure_files = list.files(clustering_output_path, pattern = "subclonal_structure.txt.gz", recursive=FALSE, full.names = TRUE) # the file containing tumour purity and ploidy purity_ploidy = read.table("consensus_subclonal_reconstruction_v1.1_20181121_summary_table.txt", header = TRUE) sample_purity = subset(purity_ploidy, samplename == id)$purity norm_cont = 1 - sample_purity # the copy number files cn_files = list.files(cn_path, recursive=FALSE, full.names = TRUE) # get mutations and read counts from vcf sample_vcf = vcf_filename # first read in vcf file and format vcf = readVcfAsVRanges(sample_vcf, "hg19", param = ScanVcfParam(fixed=c("ALT","FILTER"),geno=NA)) print(sample_vcf) vcf_df = as.data.frame(vcf) vcf_df = subset(vcf_df, !is.na(vcf_df$t_alt_count) & !is.na(vcf_df$t_ref_count)) vcf_df = vcf_df[,c(1,2,3,20,21)] # for each sample, get the clustering output sample_clustering_output = clustering_output_files[grep(id, clustering_output_files)] print(sample_clustering_output) # get DP output files if (file.exists(sample_clustering_output)){ cl_output = read.table(gzfile(sample_clustering_output), header=TRUE) print("1. Sample has clustering output") # get subclonal structure file sample_subclones = subclonal_structure_files[grep(id, subclonal_structure_files)] print(sample_subclones) if (file.exists(sample_subclones)){ subclones = read.table(gzfile(sample_subclones), header=TRUE) print("2. Sample has subclonal structure file") # remove clusters with less than 1% subclones$n_snvs_prop = subclones$n_snvs/sum(subclones$n_snvs) subclones = subset(subclones, n_snvs_prop > 0.01) subclones$cluster = paste0("cluster_", subclones$cluster) clonal.rows = assignMuts(subclones) clonal = clonal.rows # remove anything not SNV and assign muts to subclones cl_output = subset(cl_output, mut_type == "SNV") clusters = unique(subclones$cluster) cluster.cols = subset(cl_output, select=c(clusters)) cl_output[, "max_cluster"] = colnames(cluster.cols)[max.col(cluster.cols,ties.method="first")] clonal_mutations = subset(cl_output, max_cluster %in% clonal$cluster) if (is.data.frame(clonal_mutations) == TRUE & nrow(clonal_mutations) > 0){ print("3. Sample has clonal mutations") # convert vcf and clonal dp_output to granges, subset vcf to get only clonal mutations vcf_gr = makeGRangesFromDataFrame(vcf_df, keep.extra.columns = T) clonal_mutations$start = clonal_mutations$position clonal_mutations$end = clonal_mutations$position clonal_mutations$position = NULL clonal_mutations_gr = makeGRangesFromDataFrame(clonal_mutations) # get overlap between vcf and clonal mutations hits = findOverlaps(vcf_gr, clonal_mutations_gr, type = "start") idx = hits@from vcf_clonal_gr = unique(vcf_gr[idx]) # read in consensus copy number file and get clonal regions sample_cn = cn_files[grep(id, cn_files)] print(sample_cn) if (file.exists(sample_cn)) { print("4. Sample has copy number") cn = read.table(gzfile(sample_cn), header=TRUE) # get clonal gain segments and reduce file # take only a-d segments cn_gains = subset(cn, level %in% c("a","b","c","d") & major_cn > 1)[,1:6] if (is.data.frame(cn_gains) == TRUE & nrow(cn_gains) > 0){ print("5. Sample has clonal gains") # make GRanges of clonal gain position cn_gains_gr = makeGRangesFromDataFrame(cn_gains, keep.extra.columns=TRUE) # get mutations in regions of clonal copy number vcf_gains_gr = mergeByOverlaps(vcf_clonal_gr, cn_gains_gr, type = "within") muts_df = as.data.frame(vcf_gains_gr$vcf_clonal_gr) cn_df = as.data.frame(vcf_gains_gr$cn_gains_gr, row.names=NULL) muts_clonal_gains = cbind(muts_df, cn_df) names(muts_clonal_gains)[9] = "segment.start" names(muts_clonal_gains)[10] = "segment.end" if (is.data.frame(muts_clonal_gains) == TRUE & nrow(muts_clonal_gains) > 0){ print("6. Sample has clonal mutations in clonal gains") muts_clonal_gains$type = "none" muts_clonal_gains$type[muts_clonal_gains$major_cn == 2 & muts_clonal_gains$minor_cn == 1] = "SingleGain" muts_clonal_gains$type[muts_clonal_gains$major_cn == 2 & muts_clonal_gains$minor_cn == 0] = "CNLOH" muts_clonal_gains$type[muts_clonal_gains$major_cn == 3 & muts_clonal_gains$minor_cn == 1] = "DoubleGain" muts_clonal_gains$type[muts_clonal_gains$major_cn == 2 & muts_clonal_gains$minor_cn == 2] = "WGD" names(muts_clonal_gains)[1] = "chr" muts_clonal_gains$segId = paste0(muts_clonal_gains$chr,"_",muts_clonal_gains$segment.start, "_", muts_clonal_gains$segment.end, "_", muts_clonal_gains$type) muts_clonal_gains = subset(muts_clonal_gains, type != "none") if (is.data.frame(muts_clonal_gains) == TRUE & nrow(muts_clonal_gains) > 0){ print("7. Sample has clonal mutations within clonal timeable gains") muts_clonal_gains$sample = id # do formatting for eventTiming names(muts_clonal_gains)[6] = "nMutAllele" muts_clonal_gains$nReads = muts_clonal_gains$t_ref_count + muts_clonal_gains$nMutAllele muts_clonal_gains$mutationId = paste0(muts_clonal_gains$chr, "_", muts_clonal_gains$start) clonal_events_list = split(muts_clonal_gains, muts_clonal_gains$sample) arguments = list(bootstrapCI="nonparametric", minMutations=2) x = eventTimingOverList.WGD(dfList = clonal_events_list, normCont = norm_cont, eventArgs = arguments) # format results y = getPi0Summary(x, CI=TRUE) piSum = na.omit(y) rownames(piSum) = NULL print("8. Writing output") # save as gz files write.table(piSum, file=gzfile(paste0(id, "_timed_segments.txt.gz")), sep="\t", quote = FALSE, row.names=FALSE) } } } } } } }
7b952bc6613fcf35c106048469c0de4e36a5c52c
7f83f684b76b225e21f00ef721f846d371025521
/join.R
61f56e1c0a0f43156fedb22a595ec83132484d2a
[]
no_license
vladmonteiro/eletiva_analise_de_dados
2225771ba7c145742f478d1835fc3852605f6c7d
650d283a68148ece6fda730f2fda237ea6c67d04
refs/heads/master
2023-06-10T13:56:19.802780
2021-07-05T02:33:37
2021-07-05T02:33:37
356,731,299
0
0
null
null
null
null
UTF-8
R
false
false
413
r
join.R
library(tidyverse) library(dplyr) library(foreign) conflicts <- read.csv2('base_original/MIDB4.3.CSV', sep = ',') politics <- read.csv2('base_original/institutions.csv', sep = ',') banco <- inner_join(conflicts, politics, by = c("styear" = "year", "stabb" ="ifs")) banco2 <- inner_join(banco, mundo, by = c("countryname" = "country") )
6d5221b595a9e71b9791d0c46e2642665ad47d20
83840bba98c2ed74d2256f9bddc436a4c59a8126
/tests/testthat/test_common_artifact_part.R
03ace8f4bdad5b6f93409aba1fac7346498c5607
[]
no_license
botchkoAI/VertaRegistryService
4290e1d5fbb67c979ead090f4c042f2d3dedf5f7
0bc53050d6ddc4ab9ff540e8116d571cd9eb5699
refs/heads/main
2023-06-03T08:37:22.340430
2021-06-16T23:01:05
2021-06-16T23:01:05
377,648,143
0
0
null
null
null
null
UTF-8
R
false
false
563
r
test_common_artifact_part.R
# Automatically generated by openapi-generator (https://openapi-generator.tech) # Please update as you see appropriate context("Test CommonArtifactPart") model.instance <- CommonArtifactPart$new() test_that("part_number", { # tests for the property `part_number` (character) # uncomment below to test the property #expect_equal(model.instance$`part_number`, "EXPECTED_RESULT") }) test_that("etag", { # tests for the property `etag` (character) # uncomment below to test the property #expect_equal(model.instance$`etag`, "EXPECTED_RESULT") })
5cfac08d714fb53f0f9dd3f073442e503afdf481
5a952d0bc4237afd8c732186f263f6016f99d508
/run_analysis.R
d00627e6408c968d290006c0e2c91c0a4cac40f4
[]
no_license
pjohnston/gettingandcleaningdata
cd2f4fb24024b2b1046c2f141aa56cbe870572d1
c276bbf732f60d9551af09aa145d0dcd89f10aad
refs/heads/master
2020-05-07T05:46:37.075361
2014-12-19T16:51:04
2014-12-19T16:51:04
null
0
0
null
null
null
null
UTF-8
R
false
false
4,962
r
run_analysis.R
# Getting and Cleaning Data - Coursera Course. Course Project # # Paul Johnston # 12/8/2014 # One of the most exciting areas in all of data science right now is wearable computing # Companies like Fitbit, Nike, and Jawbone Up are racing to develop the most advanced algorithms to attract # new users. The data linked to from the course website represent data collected from the accelerometers # from the Samsung Galaxy S smartphone. A full description is available at the site where the data was obtained: # http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones # Here are the data for the project: # https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip # This script assumes the above data has been downloaded and # unzipped into the current working directory and then does the following: # 1. Merges the training and the test sets to create one data set. # 2. Extracts only the measurements on the mean and standard deviation for each measurement. # 3. Uses descriptive activity names to name the activities in the data set # 4. Appropriately labels the data set with descriptive variable names. Data is stored in the "activityData" variable. # 5, Writes a tidy data set with the average of each variable for each activity and each subject to "tidy.txt" # file in current working directory # Merges the training and the test sets to create one data set. # Note this script makes extensive use of the "dplyr" and "tidyr" R packages. Make sure those are loaded library(dplyr) library(tidyr) # Load the "activities_labels.txt" file # Label the column actiivyt_id and activity_name activities <- read.table("activity_labels.txt", col.names=c("activity_id","activity_name")) # Load the "features.txt" file # Label the column actiivity_id and activity_name features <- read.table("features.txt", col.names=c("feature_id","feature_name")) # # Load the test data - subject_test.txt, X_test.txt, y_test.txt # # - Subject file 1 column testSubject <- read.table("test/subject_test.txt", col.names=c("subject_id")) # Activities file - 1 column testActivities <- read.table("test/y_test.txt", col.names=c("activity_id")) # Features file - 561 columns, one per feature testFeatures <- read.table("test/X_test.txt") # Create a combined data.frame from the 3 test tables. testData <- data.frame(testSubject,testActivities,testFeatures) # # Load the training data - subject_train.txt, X_train.txt, y_train.txt # # - Subject file 1 column trainSubject <- read.table("train/subject_train.txt", col.names=c("subject_id")) # Activities file - 1 column trainActivities <- read.table("train/y_train.txt", col.names=c("activity_id")) # Features file - 561 columns, one per feature trainFeatures <- read.table("train/X_train.txt") # Create a combined data.frame from the 3 test tables. trainData <- data.frame(trainSubject,trainActivities,trainFeatures) # Now combine the test and training data into a single data frame mergedData <- rbind(testData,trainData) # Set the column headers to the names of id plus "-" plus name of the measure (measure names are not unique and # the dplyr "select" function requires them to be unique) colnames(mergedData) <- c("subject_id","activity_id", as.character(paste(features$feature_id,"-",features$feature_name))) meansAndStds <- mergedData %>% # Select columns using select that end in _id, or contain -std() or -mean() select(matches("_id$|-mean()|-std()")) # We have unique column names now (guaranteed by select) so get rid of the "id - " from the front of them colnames(meansAndStds) <- gsub("^(.* - )(.*$)","\\2",colnames(meansAndStds)) # and replace () and - with underscores and lowercase the column names colnames(meansAndStds) <- tolower(gsub("\\(\\)$","",gsub("-","_",gsub("\\(\\)-+","_",colnames(meansAndStds))))) # join in the names of the activities from the activity table using dplyr inner_join function activityTmp <- tbl_df(inner_join(activities,meansAndStds,by="activity_id")) # and get rid of the activity_id column. activityData <- activityTmp %>% select(-contains("activity_id") ) # So "activityData" variable now contains the (untidy) data we want. # Now tidy it using tidyr into a variable called "tidyActivityData" tidyActivityData <- activityData %>% # 1. Gather all the measures, to convert to a 4 column layout with activty_name, subject_id, measure and value gather(measure, value, tbodyacc_mean_x:fbodybodygyrojerkmag_meanfreq) %>% # 2. Group the data by activity and subject and measure group_by(activity_name,subject_id,measure) %>% # 3. Calculate the average measure by activity and subject summarize(mean_value = mean(value)) %>% # 4. Sort output data by activity, subject and measure arrange(activity_name, subject_id, measure) # write it out to a txt file in the current working directory named "tidy.txt" without rownames write.table(tidyActivityData,file="tidy.txt",row.names=FALSE)
5fa60a8d85d6a4f56250c88bacd14a554e764b0a
161940a51deb66a640489adcd953caa85317e107
/R/import.R
0ecf9f5cc6111d35386f2ec3ca392983ff8f64c0
[]
no_license
baifengbai/modules
f8d00c9ac573efb01b78343189c437981c2c3849
9873a6ada76f7d1f24d7dc6293459498f3e59f3c
refs/heads/master
2020-04-02T12:03:38.991021
2018-06-24T20:50:46
2018-06-24T20:50:46
null
0
0
null
null
null
null
UTF-8
R
false
false
1,124
r
import.R
#' @rdname module #' @export import <- function(from, ..., attach = TRUE, where = parent.frame()) { where <- importCheckAttach(where, attach) pkg <- importGetPkgName(match.call()) objectsToImport <- importGetSelection(match.call(), pkg) addDependency(pkg, objectsToImport, where, makeDelayedAssignment, pkg) invisible(parent.env(where)) } importCheckAttach <- function(where, attach) { if (!attach) new.env(parent = baseenv()) else where } importGetPkgName <- function(mc) { pkg <- Map(deparse, mc)$from pkg <- deleteQuotes(pkg) importCheckInstall(pkg) } importCheckInstall <- function(pkg) { ind <- !is.element(pkg, installed.packages()[, "Package"]) if (ind) stop( "'package:", pkg, "' is not installed!" ) else pkg } importGetSelection <- function(mc, pkg) { objectsToImport <- importDeparseEllipses(mc) if (length(objectsToImport) == 0) getNamespaceExports(pkg) else objectsToImport } importDeparseEllipses <- function(mc) { args <- Map(deparse, mc) args[[1]] <- NULL args$from <- NULL args$where <- NULL args$attach <- NULL args <- unlist(args) deleteQuotes(args) }
8caae52bfd7dc0f9566c438460b74d4b554c954c
414754f98514fec8c8c8230e064f742f2a4ae6b3
/machine_learning/matrix_factorization.R
71f694e59b892a49dbb31e70cc25cf05f3f87784
[]
no_license
brambloemen/HarvardX_GenomicsClass
38da74d6eb56c5704ee4af7bfc052c614af7baf9
2a0a2357b21866832d7ccef5b7a2dd37b8561562
refs/heads/main
2023-05-08T15:00:38.847068
2021-05-29T12:01:58
2021-05-29T12:01:58
371,959,067
2
0
null
null
null
null
UTF-8
R
false
false
3,119
r
matrix_factorization.R
.libPaths('C:/Users/BrBl1834/R/win-library') library(tidyverse) # set.seed(1987) #if using R 3.6 or later, use `set.seed(1987, sample.kind="Rounding")` instead set.seed(1987, sample.kind="Rounding") n <- 100 k <- 8 Sigma <- 64 * matrix(c(1, .75, .5, .75, 1, .5, .5, .5, 1), 3, 3) m <- MASS::mvrnorm(n, rep(0, 3), Sigma) m <- m[order(rowMeans(m), decreasing = TRUE),] y <- m %x% matrix(rep(1, k), nrow = 1) + matrix(rnorm(matrix(n*k*3)), n, k*3) colnames(y) <- c(paste(rep("Math",k), 1:k, sep="_"), paste(rep("Science",k), 1:k, sep="_"), paste(rep("Arts",k), 1:k, sep="_")) # Q1 my_image <- function(x, zlim = range(x), ...){ colors = rev(RColorBrewer::brewer.pal(9, "RdBu")) cols <- 1:ncol(x) rows <- 1:nrow(x) image(cols, rows, t(x[rev(rows),,drop=FALSE]), xaxt = "n", yaxt = "n", xlab="", ylab="", col = colors, zlim = zlim, ...) abline(h=rows + 0.5, v = cols + 0.5) axis(side = 1, cols, colnames(x), las = 2) } my_image(y) # Q2 my_image(cor(y), zlim = c(-1,1)) range(cor(y)) axis(side = 2, 1:ncol(y), rev(colnames(y)), las = 2) # Q3 s <- svd(y) names(s) y_svd <- s$u %*% diag(s$d) %*% t(s$v) max(abs(y - y_svd)) ss_y <- colSums(y^2) ss_yv <- colSums((y%*%s$v)^2) sum(ss_y) sum(ss_yv) # Q4 plot(1:ncol(y),ss_y) plot(1:ncol(y),ss_yv) # Q5 plot(s$d,sqrt(ss_yv)) # Q6 # first 3 columns of YV ss_yv_first3 <- colSums((y%*%s$v[,1:3])^2) # total variation explained by first 3 of YV sum(ss_yv_first3)/sum(ss_y) # Q7 identical(s$u %*% diag(s$d), sweep(s$u, 2, s$d, FUN = "*")) # Q8 s$u %*% diag(s$d) # first component of UD U1d1.1 <- s$u[,1]*s$d[1] # average per student student_avgs <- rowMeans(y) plot(U1d1.1,student_avgs) # Q9 cols <- 1:ncol(s$v) rows <- 1:nrow(s$v) my_image(s$v) # Q10 plot(s$u[,1]) range(s$u[,1]) plot(s$v[,1]) plot(t(s$v[,1])) U1d1.1.tsv1 <- U1d1.1 %*% t(s$v[,1]) my_image(U1d1.1.tsv1) my_image(y) # Q11 resid <- y - with(s,(u[, 1, drop=FALSE]*d[1]) %*% t(v[, 1, drop=FALSE])) my_image(cor(resid), zlim = c(-1,1)) axis(side = 2, 1:ncol(y), rev(colnames(y)), las = 2) plot(s$u[,2]) range(s$u[,2]) plot(s$v[,2]) plot(t(s$v[,2])) U2d2.2 <- s$u[,2]*s$d[2] U2d2.2.tsv2 <- U2d2.2 %*% t(s$v[,2]) my_image(U2d2.2.tsv2) my_image(y) # Q12 # variance explained by first two columns sum(s$d[1:2]^2)/sum(s$d^2) * 100 resid <- y - with(s,sweep(u[, 1:2], 2, d[1:2], FUN="*") %*% t(v[, 1:2])) my_image(cor(resid), zlim = c(-1,1)) axis(side = 2, 1:ncol(y), rev(colnames(y)), las = 2) plot(s$u[,3]) range(s$u[,3]) plot(s$v[,3]) plot(t(s$v[,3])) U3d3.3 <- s$u[,3]*s$d[3] U3d3.3.tsv3 <- U3d3.3 %*% t(s$v[,3]) my_image(U3d3.3.tsv3) my_image(y) # Q13 sum(s$d[1:3]^2)/sum(s$d^2) * 100 resid <- y - with(s,sweep(u[, 1:3], 2, d[1:3], FUN="*") %*% t(v[, 1:3])) my_image(cor(resid), zlim = c(-1,1)) axis(side = 2, 1:ncol(y), rev(colnames(y)), las = 2) my_image(U1d1.1.tsv1 + U2d2.2.tsv2 +U3d3.3.tsv3) my_image(y) my_image(y-(U1d1.1.tsv1 + U2d2.2.tsv2 +U3d3.3.tsv3)) y_hat <- with(s,sweep(u[, 1:3], 2, d[1:3], FUN="*") %*% t(v[, 1:3])) my_image(y, zlim = range(y)) my_image(y_hat, zlim = range(y)) my_image(y - y_hat, zlim = range(y))
acb19f34fa4d702a781b02ed18ed50be8a7b58f0
9c0aa0ced21d27e9dd0618fef4785943d59c420d
/ui.R
457d1085d47fd7381d8c5c1206c06d83592ae9dc
[]
no_license
travisfell/10---Capstone
d7107c1cf341ca0dc2ee30f06241226d208d6031
cf74dd63b9c308e66d27085f0ccda9e90fdcad68
refs/heads/master
2021-01-21T13:07:26.466000
2016-04-21T04:13:25
2016-04-21T04:13:25
53,469,004
0
0
null
null
null
null
UTF-8
R
false
false
833
r
ui.R
#ui.R # This is the UI definition script for the #Capstone final project library(shiny) shinyUI(pageWithSidebar( headerPanel("Text Prediction Cloud"), sidebarPanel( h3('Enter your text.'), p("This app predicts the next word based on the words you enter."), p("Type your text in the text box below. Then click Submit."), p("Please allow 5-10 seconds for the app to return results."), textInput('enteredtext', 'Enter your text here: '), #submitButton('Submit') actionButton('Submit', "Submit") ), mainPanel( h3('The top 3 words associated with your text are: '), verbatimTextOutput("prediction"), p("The word cloud below shows upto the top 25 words predicted from the entered text."), plotOutput("textcloudplot") ) ))
aa7880fa2d6a93677a5efe2ab1b6b72cdd0a221a
e3495708f48030176093019ba38a08b0afc6fe5a
/waterfall.R
bc4621e4bcf45ae6ab6f943d429972f86fddd4ca
[]
no_license
plus4u/Data-Analytics
32ae849aeb0c40484e733d02a4edc6e5b64b1c5c
811ea7ac651019d6cb03f71d47d008f7074beb25
refs/heads/master
2022-07-07T09:47:05.876879
2022-07-03T23:01:36
2022-07-03T23:01:36
146,960,490
0
0
null
null
null
null
UTF-8
R
false
false
1,834
r
waterfall.R
### waterfall ### 2 methods : simple , ################################### ### @ 1 install.packages("waterfalls") library(waterfalls) group <- LETTERS[1:6] value <- c(2000, 4000, 2000, -1500, -1000, -2500) df <- data.frame(x = group, y = value) waterfall(values = value, labels = group) ### @ 2 install.packages("tidyverse") library(tidyverse) df <- tribble( ~Category, ~Value, # --------- header record ---------- "Prev Budget", 5, "Salaries", 0.1, "CapEx", 0.175, "Travel", -0.2, "Contracting", -0.1, "Operations", -0.2, "RealEstate", -0.1, "Gap to Target", -0.175, "Current Budget", -4.5 ) df ## levels <- df$Category data1 <- df %>% mutate(Category = factor(Category, levels = levels), ymin = round(cumsum(Value), 3), ymax = lag(cumsum(Value), default = 0), xmin = c(head(Category, -1), NA), xmax = c(tail(Category, -1), NA), Impact = ifelse(Category %in% c(as.character(df$Category[1]), as.character(df$Category[nrow(df)])),"Budget", ifelse(Value > 0, "Increase", "Decrease") )) data1 ## g <- ggplot(data1) + theme_bw()+ theme(legend.position = "right", panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5)) + labs(y = "USD Millions", x = "Expense Category", title = "Explanation of Budget Gap Closure") w <- 0.4 #use to set width of bars g <- g + geom_rect(aes(xmin = as.integer(Category) - w/2, xmax = as.integer(Category) + w/2, ymin = ymin, ymax = ymax, fill = Impact), colour = "black") + scale_x_discrete(limits = levels) + scale_fill_manual(values = (c("Decrease" = "blue", "Increase" = "orange", "Budget" = "black"))) g
fcecc45d7a099f97e517c1aea7be4e7e059828e6
6984fd7eca0e35087b50c245a2c4f55b3b1c0964
/WIP/Evaluating Variational Inference/Figure_2_linear_reg.R
939bf09637210d7b610a9dae11d56003a592cc15
[ "MIT" ]
permissive
junpenglao/Planet_Sakaar_Data_Science
20620b5b0de0705fd7f7dcf0a477745325fa43c1
4366de036cc608c942fdebb930e96f2cc8b83d71
refs/heads/main
2023-04-13T15:06:08.128262
2023-04-05T08:56:32
2023-04-05T08:56:32
127,780,588
55
14
null
null
null
null
UTF-8
R
false
false
7,526
r
Figure_2_linear_reg.R
###### Figure_2, a bayesian linear regression, ############################## #############the result is sensitive to the tolorance, which scales with the problem complexity. K hat gives a convergence diagnoistic library(rstan) library(loo) ### loo is used for PSIS setwd("") rstan_options(auto_write = TRUE) options(mc.cores = parallel::detectCores()) stan_code=' data { int <lower=0> N; int <lower=0> D; matrix [N,D] x ; vector [N] y; } parameters { vector [D] b; real <lower=0> sigma; } model { y ~ normal(x * b, sigma); b~normal(0,1); sigma~gamma(0.5,0.5); } generated quantities{ real log_density; log_density=normal_lpdf(y |x * b, sigma)+normal_lpdf(b|0,1)+gamma_lpdf(sigma|0.5,0.5)+log(sigma); } ' # linear regression model ##log(sigma) in the last line: the jacobian term in the joint density using log(sigma) as the transformed parameters. m=stan_model(model_code = stan_code) # the function for PSIS re-weighting. ip_weighted_average=function(lw, x){ ip_weights=exp(lw-min(lw)) return( t(ip_weights)%*%x /sum(ip_weights) ) } set.seed(1000) N=10000 # a linear regression with 10^5 data and 100 variables D=100 beta=rnorm(D,0,1) x=matrix(rnorm(N*D,0,1), N, D) y=as.vector(x%*%beta+rnorm(N,0,2)) time_temp=proc.time() fit_stan=stan(model_code=stan_code, data=list(x=x,y=y, D=D,N=N), iter=3000) time_temp2=proc.time() time_diff=c(time_temp2-time_temp) running_time_stan=sum(get_elapsed_time(fit_stan)) stan_sample=extract(fit_stan) trans_para=cbind(stan_sample$b, log(stan_sample$sigma)) stan_mean= apply(trans_para, 2, mean) stan_square= apply(trans_para^2, 2, mean) tol_vec=c(0.03,0.01,0.003,0.001,0.0003,0.0001,0.00003,0.00001) # choose relative tolerance. The default in the published ADVI paper is 0.01. sim_N=50 # repeat simulations. 50 is enough as we can check the sd. The only uncertainty is stochastic optimization in ADVI I=length(tol_vec) K_hat=running_time=matrix(NA,sim_N,I ) bias_mean=bias_square=array(NA,c(3,sim_N,I,length(stan_mean)) ) set.seed(1000) for(i in c(I) ) for(sim_n in 1:sim_N) { tol=tol_vec[i] time_temp=proc.time() fit_vb=vb(m, data=list(x=x,y=y, D=D,N=N), iter=1e5,output_samples=5e4,tol_rel_obj=tol,eta=0.05,adapt_engaged=F) ## it is also sensitive to eta. time_temp2=proc.time() time_diff=c(time_temp2-time_temp) running_time[sim_n,i]= time_diff[3] vb_samples=extract(fit_vb) trans_parameter=cbind(vb_samples$b,log(vb_samples$sigma)) vi_parameter_mean=apply(trans_parameter, 2, mean) vi_parameter_sd=apply(trans_parameter, 2, sd) normal_likelihood=function(trans_parameter){ one_data_normal_likelihood=function(vec){ return( sum( dnorm(vec,mean=vi_parameter_mean,sd=vi_parameter_sd, log=T))) } return( apply(trans_parameter, 1, one_data_normal_likelihood)) } lp_vi=normal_likelihood(trans_parameter) lp_target=vb_samples$log_density ip_ratio=lp_target-lp_vi ok=complete.cases(ip_ratio) joint_diagnoistics=psislw(lw=ip_ratio[ok]) bias_mean[1,sim_n,i,]=vi_parameter_mean-stan_mean bias_square[1,sim_n,i,]=apply(trans_parameter^2, 2, mean)-stan_square K_hat[sim_n,i]=joint_diagnoistics$pareto_k trans_parameter=trans_parameter[ok,] psis_lw=joint_diagnoistics$lw_smooth bias_mean[2,sim_n,i,]=ip_weighted_average(lw=ip_ratio, x=trans_parameter)-stan_mean bias_square[2,sim_n,i,]=ip_weighted_average(lw=ip_ratio, x=trans_parameter^2)-stan_square bias_mean[3,sim_n,i,]=ip_weighted_average(lw=psis_lw, x=trans_parameter)-stan_mean bias_square[3,sim_n,i,]=ip_weighted_average(lw=psis_lw, x=trans_parameter^2)-stan_square print(paste("======================= i=",i," ========================")) print(paste("=======================iter",sim_n,"========================")) } running_time=matrix(NA,5,I) ## calculate the running time again. most of the elapsed time calculated above is on sampling. now we skip the sampling procudure. set.seed(1000) for(i in 1:I ) for(sim_n in 1:5) { tol=tol_vec[i] time_temp=proc.time() fit_vb=vb(m, data=list(x=x,y=y, D=D,N=N), iter=1e5,output_samples=2,tol_rel_obj=tol,eta=0.09,adapt_engaged=F) time_temp2=proc.time() time_diff=c(time_temp2-time_temp) running_time[sim_n,i]= time_diff[3] } time_vec=apply(running_time, 2, mean, na.rm=T) #save(K_hat,running_time_vec,bias_mat, bias_mean_new,bias_square_new,running_time,running_time_stan,file="linear_1e52.RData") #save(K_hat, bias_mean,bias_square,running_time,running_time_stan,file="linear_1e52_copy.RData") #load("linear_1e52.RData") k_vec=apply(K_hat, 2, mean, na.rm=T) ## average among all repeated simulations time_vec=apply(running_time, 2, mean, na.rm=T) ## average among all repeated simulations bias_mat=matrix(NA,I,3) ## average among all repeated simulations for(i in 1:I) for(j in 1:3) bias_mat[i,j]= sqrt((D+1)*mean(bias_mean_new[j,,i,]^2,na.rm=T)) # L_2 norm of first order error (RMSE) bias_sq_mat=matrix(NA,I,3) for(i in 1:I) for(j in 1:3) bias_sq_mat[i,j]= sqrt((D+1)*mean(bias_square_new[j,,i,]^2,na.rm=T)) # L_2 norm of second order error (RMSE of x^2) ## Figure 2 PSIS in linear regression ######## library(plotrix) pdf("~/Desktop/linear_large_n.pdf",width=4,height=1.5) ## Figure 2 linear regression par(mfcol=c(1,3),oma=c(0.5,0.8,0.1,0.2), pty='m',mar=c(1,0.6,0.5,0.7) ,mgp=c(1.5,0.25,0), lwd=0.5,tck=-0.01, cex.axis=0.6, cex.lab=0.9, cex.main=0.9) plot(log10(tol_vec),k_vec,xlim=c(-4.3,-1.5),ylim=c(0,2.8), type='l' , xlab="",ylab="" ,axes=F,lwd=1,yaxs='i',xpd=T) abline(h=c(0.7),lty=2,lwd=0.6, col='grey') points(log10(tol_vec),k_vec,pch=19,cex=0.3) axis(1,padj=-0.5, at=c(-5,-4,-3,-2),labels = c(NA,expression(10^-4),expression(10^-3), expression(10^-2) ) ,lwd=0.5, cex.axis=0.7) at.x <- outer(c(2,4,6,8) , 10^(-3:-5)) lab.x <- ifelse(log10(at.x) %% 1 == 0, at.x, NA) axis(1,padj=-1, at=log10(at.x), labels=NA,lwd=0.2,lwd.ticks=0.4,tck=-0.007) axis(2, at=c(0,0.5,0.7,1, 2) ,labels=c(0,".5",".7",1,2) ,lwd=0.5,las=2) box(bty='l',lwd=0.5) mtext(2, text="k hat", cex=0.7, line = 0.5) mtext(1, text="relative tolerance", cex=0.7, line = 0.5,las=1) plot( time_vec,k_vec,xlim=c(0,72),ylim=c(0,2.8), type='l' , xlab="",ylab="" ,axes=F,lwd=1,yaxs='i',xpd=T,xaxs='i') abline(h=c(0.7),lty=2,lwd=0.6, col='grey') points(time_vec,k_vec,pch=19,cex=0.3) axis(1,padj=-1, at=c(0,20,40,60),lwd=0.5) axis(2, at=c(0,0.5,0.7,1, 2) ,labels=c(0,".5",".7",1,2) ,lwd=0.5,las=2) box(bty='l',lwd=0.5) mtext(2, text="k hat", cex=0.7, line = 0.5) mtext(1, text="running time (s)", cex=0.7, line = 0.5,las=1) axis.break(1,65,style="zigzag") axis(1,padj=-0.5, at=c(70),lwd=0.5,col=2,labels = NA, tick=0.5, cex.axis=0.4) round(running_time_stan,-2) text(67,0.44,labels = "NUTS\n sampling\n time=2300",xpd=T, cex=0.65,col=2) lines(x=c(70,70),y=c(0,0.15),col=2,lwd=0.5,lty=2) plot(bias_mat,xlim=c(0.4,1.57),ylim=c(0,0.05),type='n', xlab="",ylab="" ,axes=F,lwd=1,yaxs='i') for(i in 1:3) lines(k_vec,bias_mat[,i],col=c("blue","red","forest green")[i],lwd=1,xpd=T) axis(1,padj=-1, at=c(0.5,1,1.5),labels = c(.5,1,1.5),lwd=0.5) axis(2, at=c(0,0.02,0.04) ,labels=c(0,".02",".04") ,lwd=0.5,las=2) mtext(2, text="RMSE", cex=0.6, line = 1) mtext(1, text="k hat", cex=0.7, line = 0.5,las=1) text(1.46,0.04,labels = "Raw ADVI",col="blue",xpd=T,cex=0.8) text(1.48,0.047,labels = "IS",col="forest green",xpd=T,cex=0.8) text(1.4,0.015,labels = "PSIS",col="red",xpd=T,cex=0.8) box(bty='l',lwd=0.5) dev.off()
b3c4cbdd4e4d8e035e9fec1277cfbb92f2adbe1a
644cf30f84ed01751811c124c9c3594f62a25de0
/Part 2/Prediction/Random Forest/RF_FULL.R
34c5708d9247077cb5b7261e81f547ee7b03d302
[]
no_license
ahmeduncc/Team_1_Energy_Consumption_modeling
f35c369cb1e9d4668c2cc71190b75f9c9e6ddb6f
a9593549c582042719fabb1b545a2bc295ad883d
refs/heads/master
2021-06-08T23:19:12.311840
2016-11-19T05:24:59
2016-11-19T05:24:59
null
0
0
null
null
null
null
UTF-8
R
false
false
2,929
r
RF_FULL.R
install.packages("hydroGOF") install.packages("randomForest") library("hydroGOF") library("randomForest") install.packages("rjson") library("rjson") config_json<- fromJSON(file="config_RF.json") n_tree_value <- as.integer(config_json$ntree) ab <- read.csv("final_sample_format_Part1.csv") #View(ab) final_file <- data.frame() outlier_tag_file <- data.frame() #View(ab) ab$Base_hour_Flag <- as.character(ab$Base_hour_Flag) ab$Base_hour_Flag[ab$Base_hour_Flag=='True'] <- 0 ab$Base_hour_Flag[ab$Base_hour_Flag=='False'] <- 1 ab$Base_hour_Flag <- as.numeric(ab$Base_hour_Flag) ab$X..address.y<-NULL ab$area_floor._m.sqr.y<-NULL ab$BuildingID <-NULL ab$building<-NULL ab$meternumb<-NULL ab$airport_code<-NULL #ab$type<- NULL ab$date<- NULL ab$year<-NULL ab$Base_hour_usage <- NULL ab$Consumption <- NULL ab$Base_Hour_Class <- NULL ab$VisibilityMPH <- NULL ## more than 50% data is negative ab$Gust_SpeedMPH<-NULL #601105 values = '-' ab$PrecipitationIn<-NULL #614116 values N/A ab$Wind_Direction <- NULL # wind dir deg is numreical for wind_direction ab$Events <- NULL # 350626 values empty ab$Weekday <- as.numeric(ab$Weekday) ab$Holiday <- as.numeric(ab$Holiday) ab$Base_hour_Flag <- as.numeric(ab$Base_hour_Flag) #ab$month <- factor(ab$month) smp_size <- floor(0.60 * nrow(ab)) #Set the seed to make your partition reproductible set.seed(123) train_ind <- sample(seq_len(nrow(ab)), size = smp_size) #Split the data into training and testing train <- ab[train_ind, ] test <- ab[-train_ind, ] #View(ab) y=train$Norm_Consumption train$month <- factor(train$month) train$Weekday <- as.numeric(train$Weekday) train$Holiday <- as.numeric(train$Holiday) train$Base_hour_Flag <- as.numeric(train$Base_hour_Flag) rf_fit <- randomForest(y~ train$Base_hour_Flag +train$Weekday +train$Holiday+ train$month +train$TemperatureF +train$Dew_PointF ,data=train,ntree = n_tree_value) #summary(rf_fit) selected_model <- formula(rf_fit$terms) test_pred_rf <- predict(rf_fit,data=train) library("forecast") accuracy(test_pred_rf,train$Norm_Consumption) # summary(rf_fit) #Prediction parameters selected_model <- formula(rf_fit$terms) pred_rf <- predict(rf_fit,train) acc <- accuracy(pred_rf,train$Norm_Consumption) acc_df <- as.data.frame(acc) acc_df$model <- as.character(selected_model[3]) train$predicted_value <- pred_rf residual_values <- train$Norm_Consumption - pred_rf train$residual_values <- residual_values std_dev_residuals<- sd(residual_values) #train$outlier <- "False" train$outlier <- ifelse(train$residual_values>=2*std_dev_residuals,"True","False") train$residual_values <- NULL final_file<- rbind(final_file,acc_df) outlier_tag_file <- rbind(outlier_tag_file,train) final_file$ME<-NULL final_file$MPE<-NULL final_file$algorithm <- "Random Forest" write.csv(final_file,file="RF_Pred_model_FULL.csv",row.names=FALSE) write.csv(outlier_tag_file,file = "Outlier_RF_Pred_FULL.csv")
c14778450a5d4b477f0bc797481fb3eb8ad2bf18
8ced7c6508be6fbc0b3c3ba6a84440a6353f33b9
/bsem_analyses/process_models.R
b0cb55dd74676b74853b751ef016ee2d9d4f214a
[]
no_license
UNCDEPENdLab/attachment_physio_coreg
ae7bff7c288874204a6900addff101cd005d5d37
5a73c065e5b82f168a93dceebdad46adf02c7643
refs/heads/master
2022-12-16T08:44:25.337138
2020-09-25T17:46:43
2020-09-25T17:46:43
null
0
0
null
null
null
null
UTF-8
R
false
false
46,652
r
process_models.R
# Set up paths ------------------------------------------------------------ output_dir <- "../output" bsem_process_res_dir <- "../output/bsem_process" bsem_personalitymod_res_dir <- "../output/bsem_personalitymod" if(!dir.exists(output_dir)) {dir.create(output_dir)} if(!dir.exists(bsem_process_res_dir)) {dir.create(bsem_process_res_dir)} if(!dir.exists(bsem_personalitymod_res_dir)) {dir.create(bsem_personalitymod_res_dir)} # Source functions -------------------------------------------------------- source(paste0(project_dir, "/code/support_fx.R")) # Load Packages ----------------------------------------------------------- if (!require(pacman)) { install.packages("pacman"); library(pacman) } p_load(tidyverse, R.matlab,lavaan,lattice, MplusAutomation) # Load Data --------------------------------------------------------------- posnegint_personality <- read.csv("../data/posnegint_personality.csv") # Process Model for Negint Avo -------------------------------------------- avo_allfree <- " pavo1 ~ scpt + ccpt + scpr + ccpr pavo0 ~ scpt + ccpt + scpr + ccpr scpt ~ pravo1 + pravo0 ccpt ~ pravo1 + pravo0 scpr ~ pravo1 + pravo0 ccpr ~ pravo1 + pravo0 pravo1 ~~ pravo0 pavo1~~pavo0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr pavo1~pravo1 pavo0 ~ pravo0 " avo_allfree_m <- sem(model = avo_allfree, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) avo_afixed <- " pavo1 ~ a*scpt pavo1 ~ b*ccpt pavo1 ~ scpr pavo1 ~ ccpr pavo0 ~ scpt pavo0 ~ ccpt pavo0 ~ a*scpr pavo0 ~ b*ccpr scpt ~ c*pravo1 scpt ~ pravo0 ccpt ~ d*pravo1 ccpt ~ pravo0 scpr ~ pravo1 scpr ~c*pravo0 ccpr ~ pravo1 ccpr ~ d*pravo0 pravo1 ~~ pravo0 pavo1~~pavo0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr pavo1~pravo1 pavo0 ~ pravo0 " avo_afixed_m <- sem(model = avo_afixed, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) avo_pfixed <- " pavo1 ~ scpt pavo1 ~ ccpt pavo1 ~ a*scpr pavo1 ~ b*ccpr pavo0 ~ a*scpt pavo0 ~ b*ccpt pavo0 ~ scpr pavo0 ~ ccpr scpt ~ pravo1 scpt ~ c*pravo0 ccpt ~ pravo1 ccpt ~ d*pravo0 scpr ~ c*pravo1 scpr ~pravo0 ccpr ~ d*pravo1 ccpr ~ pravo0 pravo1 ~~ pravo0 pavo1~~pavo0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr pavo1~pravo1 pavo0 ~ pravo0 " avo_pfixed_m <- sem(model = avo_pfixed, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) avo_apfixed <- " pavo1 ~ e*scpt pavo1 ~ f*ccpt pavo1 ~ a*scpr pavo1 ~ b*ccpr pavo0 ~ a*scpt pavo0 ~ b*ccpt pavo0 ~ e*scpr pavo0 ~ f*ccpr scpt ~ g*pravo1 scpt ~ c*pravo0 ccpt ~ h*pravo1 ccpt ~ d*pravo0 scpr ~ c*pravo1 scpr ~g*pravo0 ccpr ~ d*pravo1 ccpr ~ h*pravo0 pravo1 ~~ pravo0 pavo1~~pavo0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr pavo1~pravo1 pavo0 ~ pravo0 " avo_apfixed_m <- sem(model = avo_apfixed, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) avo_aonly <- " pavo1 ~ scpt pavo1 ~ a*ccpt pavo0 ~ scpr pavo0 ~ ccpr scpt ~ pravo1 ccpt ~ c*pravo1 scpr ~pravo0 ccpr ~ pravo0 pravo1 ~~ pravo0 pavo1~~pavo0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr ac:=a*c pavo1~pravo1 pavo0 ~ pravo0 " avo_aonly_m <- sem(model = avo_aonly, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) avo_ponly <- " pavo1 ~ scpr pavo1 ~ ccpr pavo0 ~ scpt pavo0 ~ ccpt scpt ~ pravo0 ccpt ~ pravo0 scpr ~ pravo1 ccpr ~ pravo1 pravo1 ~~ pravo0 pavo1~~pavo0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr pavo1~pravo1 pavo0 ~ pravo0 " avo_ponly_m <- sem(model = avo_ponly, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) # adds in paths that were significant from competitive model and fixes paths that are approximately zero (i.e., P > .4) avo_mod <- " #paths that are not particularly strong pavo1 ~ 0*scpt pavo0 ~ scpr pavo0 ~ 0*ccpr scpt ~ 0*pravo1 scpt ~ 0*pravo0 scpr ~ 0*pravo0 ccpr ~ 0*pravo0 #strong paths pavo1 ~ a*ccpt ccpt ~ c*pravo1 scpr ~ pravo1 ccpr ~ c*pravo1 pravo1 ~~ pravo0 pavo1~~pavo0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr pavo1 ~ pravo1 pavo0 ~pravo0 ac:=a*c " avo_mod_m <- sem(model = avo_mod, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) #Re do so only cc avo_mod <- " #paths that are not particularly strong pavo0 ~ 0*ccpr ccpr ~ 0*pravo0 #strong paths pavo1 ~ a*ccpt ccpt ~ c*pravo1 ccpr ~ c*pravo1 pravo1 ~~ pravo0 pavo1~~pavo0 ccpt ~~ ccpr pavo1 ~ pravo1 pavo0 ~pravo0 ac:=a*c " avo_mod_m <- sem(model = avo_mod, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anova(avo_allfree_m, avo_apfixed_m, avo_afixed_m, avo_pfixed_m, avo_aonly_m, avo_ponly_m, avo_mod_m) # avo mod m preferred but ponly is close second model_list <- c(avo_allfree_m, avo_apfixed_m, avo_afixed_m, avo_pfixed_m, avo_aonly_m, avo_ponly_m, avo_mod_m) # avo mod m preferred but ponly is close second syn_model_list <- c(avo_allfree, avo_apfixed, avo_afixed, avo_pfixed, avo_aonly, avo_ponly, avo_mod) syn_model_list_full <- syn_model_list df <- mapply(pull_fitmeasures, model_list, syn_model_list, list(posnegint_personality)) if(class(df) == "list") {df <- as.data.frame(do.call(rbind, df)) } else {df <- as.data.frame(t(df))} df <- df%>% mutate_all(funs(as.numeric(.))) df$mname <- "negint_avo" fulldf <- df # Process Model for Negint Anx -------------------------------------------- anx_allfree <- " panx1 ~ scpt + ccpt + scpr + ccpr panx0 ~ scpt + ccpt + scpr + ccpr scpt ~ pranx1 + pranx0 ccpt ~ pranx1 + pranx0 scpr ~ pranx1 + pranx0 ccpr ~ pranx1 + pranx0 pranx1 ~~ pranx0 panx1~~panx0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr panx1~pranx1 panx0 ~ pranx0 " anx_allfree_m <- sem(model = anx_allfree, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anx_afixed <- " panx1 ~ a*scpt panx1 ~ b*ccpt panx1 ~ scpr panx1 ~ ccpr panx0 ~ scpt panx0 ~ ccpt panx0 ~ a*scpr panx0 ~ b*ccpr scpt ~ c*pranx1 scpt ~ pranx0 ccpt ~ d*pranx1 ccpt ~ pranx0 scpr ~ pranx1 scpr ~c*pranx0 ccpr ~ pranx1 ccpr ~ d*pranx0 pranx1 ~~ pranx0 panx1~~panx0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr panx1~pranx1 panx0 ~ pranx0 " anx_afixed_m <- sem(model = anx_afixed, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anx_pfixed <- " panx1 ~ scpt panx1 ~ ccpt panx1 ~ a*scpr panx1 ~ b*ccpr panx0 ~ a*scpt panx0 ~ b*ccpt panx0 ~ scpr panx0 ~ ccpr scpt ~ pranx1 scpt ~ c*pranx0 ccpt ~ pranx1 ccpt ~ d*pranx0 scpr ~ c*pranx1 scpr ~pranx0 ccpr ~ d*pranx1 ccpr ~ pranx0 pranx1 ~~ pranx0 panx1~~panx0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr panx1~pranx1 panx0 ~ pranx0 " anx_pfixed_m <- sem(model = anx_pfixed, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anx_apfixed <- " panx1 ~ e*scpt panx1 ~ f*ccpt panx1 ~ a*scpr panx1 ~ b*ccpr panx0 ~ a*scpt panx0 ~ b*ccpt panx0 ~ e*scpr panx0 ~ f*ccpr scpt ~ g*pranx1 scpt ~ c*pranx0 ccpt ~ h*pranx1 ccpt ~ d*pranx0 scpr ~ c*pranx1 scpr ~g*pranx0 ccpr ~ d*pranx1 ccpr ~ h*pranx0 pranx1 ~~ pranx0 panx1~~panx0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr panx1~pranx1 panx0 ~ pranx0 " anx_apfixed_m <- sem(model = anx_apfixed, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anx_aonly <- " panx1 ~ scpt panx1 ~ a*ccpt panx0 ~ scpr panx0 ~ ccpr scpt ~ pranx1 ccpt ~ c*pranx1 scpr ~pranx0 ccpr ~ pranx0 pranx1 ~~ pranx0 panx1~~panx0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr ac:=a*c panx1~pranx1 panx0 ~ pranx0 " anx_aonly_m <- sem(model = anx_aonly, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anx_ponly <- " panx1 ~ scpr panx1 ~ ccpr panx0 ~ scpt panx0 ~ ccpt scpt ~ pranx0 ccpt ~ pranx0 scpr ~ pranx1 ccpr ~ pranx1 pranx1 ~~ pranx0 panx1~~panx0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr panx1~pranx1 panx0 ~ pranx0 " anx_ponly_m <- sem(model = anx_ponly, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anx_mod <- " panx1 ~ f*ccpt panx1 ~ scpr panx0 ~ ccpt panx0 ~ scpr panx0 ~ f*ccpr scpt ~ a*pranx0 scpt ~ b*pranx1 scpr ~ a*pranx0 scpr ~ b*pranx1 ccpt ~ h*pranx1 ccpt ~ d*pranx0 ccpr ~ d*pranx1 ccpr ~ h*pranx0 pranx1 ~~ pranx0 panx1~~panx0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr panx1~~0*scpt panx0~~0*scpt panx1~pranx1 panx0 ~ pranx0 " anx_mod_m <- sem(model = anx_mod, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) # Re do so only cc anx_mod <- " panx1 ~ f*ccpt panx0 ~ ccpt panx0 ~ f*ccpr ccpt ~ h*pranx1 ccpt ~ d*pranx0 ccpr ~ d*pranx1 ccpr ~ h*pranx0 pranx1 ~~ pranx0 panx1~~panx0 ccpt ~~ ccpr panx1~pranx1 panx0 ~ pranx0 " anx_mod_m <- sem(model = anx_mod, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anova(anx_allfree_m, anx_apfixed_m, anx_afixed_m, anx_pfixed_m, anx_aonly_m, anx_ponly_m, anx_mod_m) model_list <- c(anx_allfree_m, anx_apfixed_m, anx_afixed_m, anx_pfixed_m, anx_aonly_m, anx_ponly_m, anx_mod_m) syn_model_list <- c(anx_allfree, anx_apfixed, anx_afixed, anx_pfixed, anx_aonly, anx_ponly, anx_mod) syn_model_list_full <- c(syn_model_list_full, syn_model_list) df <- mapply(pull_fitmeasures, model_list, syn_model_list) if(class(df) == "list") {df <- as.data.frame(do.call(rbind, df)) } else {df <- as.data.frame(t(df))} df <- df%>% mutate_all(funs(as.numeric(.))) df$mname <- "negint_anx" fulldf <- bind_rows(fulldf, df) # Process model for Negint Sec -------------------------------------------- sec_allfree <- " psec1 ~ scpt + ccpt + scpr + ccpr psec0 ~ scpt + ccpt + scpr + ccpr scpt ~ prsec1 + prsec0 ccpt ~ prsec1 + prsec0 scpr ~ prsec1 + prsec0 ccpr ~ prsec1 + prsec0 prsec1 ~~ prsec0 psec1~~psec0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr psec1~prsec1 psec0 ~ prsec0 " sec_allfree_m <- sem(model = sec_allfree, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) sec_afixed <- " psec1 ~ a*scpt psec1 ~ b*ccpt psec1 ~ scpr psec1 ~ ccpr psec0 ~ scpt psec0 ~ ccpt psec0 ~ a*scpr psec0 ~ b*ccpr scpt ~ c*prsec1 scpt ~ prsec0 ccpt ~ d*prsec1 ccpt ~ prsec0 scpr ~ pravo1 scpr ~c*prsec0 ccpr ~ prsec1 ccpr ~ d*prsec0 prsec1 ~~ prsec0 psec1~~psec0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr psec1~prsec1 psec0 ~ prsec0 " sec_afixed_m <- sem(model = sec_afixed, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) sec_pfixed <- " psec1 ~ scpt psec1 ~ ccpt psec1 ~ a*scpr psec1 ~ b*ccpr psec0 ~ a*scpt psec0 ~ b*ccpt psec0 ~ scpr psec0 ~ ccpr scpt ~ prsec1 scpt ~ c*prsec0 ccpt ~ prsec1 ccpt ~ d*prsec0 scpr ~ c*prsec1 scpr ~prsec0 ccpr ~ d*prsec1 ccpr ~ prsec0 prsec1 ~~ prsec0 psec1~~psec0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr psec1~prsec1 psec0 ~ prsec0 " sec_pfixed_m <- sem(model = sec_pfixed, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) sec_apfixed <- " psec1 ~ e*scpt psec1 ~ f*ccpt psec1 ~ a*scpr psec1 ~ b*ccpr psec0 ~ a*scpt psec0 ~ b*ccpt psec0 ~ e*scpr psec0 ~ f*ccpr scpt ~ g*prsec1 scpt ~ c*prsec0 ccpt ~ h*prsec1 ccpt ~ d*prsec0 scpr ~ c*prsec1 scpr ~g*prsec0 ccpr ~ d*prsec1 ccpr ~ h*prsec0 prsec1 ~~ prsec0 psec1~~psec0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr psec1~prsec1 psec0 ~ prsec0 " sec_apfixed_m <- sem(model = sec_apfixed, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) sec_aonly <- " psec1 ~ scpt psec1 ~ a*ccpt psec0 ~ scpr psec0 ~ ccpr scpt ~ prsec1 ccpt ~ c*prsec1 scpr ~prsec0 ccpr ~ prsec0 prsec1 ~~ prsec0 psec1~~psec0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr ac:=a*c psec1~prsec1 psec0 ~ prsec0 " sec_aonly_m <- sem(model = sec_aonly, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) sec_ponly <- " psec1 ~ scpr psec1 ~ ccpr psec0 ~ scpt psec0 ~ ccpt scpt ~ prsec0 ccpt ~ prsec0 scpr ~ prsec1 ccpr ~ prsec1 prsec1 ~~ prsec0 psec1~~psec0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr psec1~prsec1 psec0 ~ prsec0 " sec_ponly_m <- sem(model = sec_ponly, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) sec_mod <- " psec1 ~ e*scpt psec1 ~ f*ccpt psec1 ~ 0*scpr psec1 ~ 0*ccpr psec0 ~ a*scpt psec0 ~ b*ccpt psec0 ~ 0*scpr psec0 ~ 0*ccpr scpt ~ g*prsec1 scpt ~ h*prsec0 ccpt ~ 0*prsec1 ccpt ~ 0*prsec0 scpr ~ 0*prsec1 scpr ~0*prsec0 ccpr ~ h*prsec1 ccpr ~ 0*prsec0 prsec1 ~~ prsec0 psec1~~psec0 scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr psec1~prsec1 psec0 ~ prsec0 " sec_mod_m <- sem(model = sec_mod, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) sec_mod <- " psec1 ~ f*ccpt psec1 ~ 0*ccpr psec0 ~ b*ccpt psec0 ~ 0*ccpr ccpt ~ 0*prsec1 ccpt ~ 0*prsec0 ccpr ~ h*prsec1 ccpr ~ 0*prsec0 prsec1 ~~ prsec0 psec1~~psec0 ccpt ~~ ccpr psec1~prsec1 psec0 ~ prsec0 " sec_mod_m <- sem(model = sec_mod, data = posnegint_personality, missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anova(sec_allfree_m, sec_apfixed_m, sec_afixed_m, sec_pfixed_m, sec_aonly_m, sec_ponly_m, sec_mod_m) model_list <- c(sec_allfree_m, sec_apfixed_m, sec_afixed_m, sec_pfixed_m, sec_aonly_m, sec_ponly_m, sec_mod_m) syn_model_list <- c(sec_allfree, sec_apfixed, sec_afixed, sec_pfixed, sec_aonly, sec_ponly, sec_mod) syn_model_list_full <- c(syn_model_list_full, syn_model_list) df <- mapply(pull_fitmeasures, model_list, syn_model_list, list(posnegint_personality)) if(class(df) == "list") {df <- as.data.frame(do.call(rbind, df)) } else {df <- as.data.frame(t(df))} df <- df%>% mutate_all(funs(as.numeric(.))) df$mname <- "negint_sec" fulldf <- bind_rows(fulldf, df) # Process Model for Posint Avo -------------------------------------------- posint_avo_allfree <- " p_scpt ~ pavo1 # actor p_scpt ~ pravo1 # actor p_scpt ~pavo0 #partner p_scpt ~pravo0 #p p_scpr ~ pavo1 #p p_scpr ~ pravo1 #p p_scpr ~ pavo0 #a p_scpr ~ pravo0 #a p_ccpt ~ pavo1 #a p_ccpt ~ pravo1 #a p_ccpt ~ pavo0 #p p_ccpt ~ pravo0 #p p_ccpr ~ pavo1 #p p_ccpr ~ pravo1 #p p_ccpr ~ pavo0 # a p_ccpr ~ pravo0 #a pravo1 ~~ pravo0 pavo1~~pavo0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr pavo1 ~ pravo1 pavo0 ~pravo0 " posint_avo_allfree_m <- sem(model = posint_avo_allfree, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_avo_afixed <- " p_scpt ~ a*pavo1 # actor p_scpt ~ b*pravo1 # actor p_scpt ~pavo0 #partner p_scpt ~pravo0 #p p_scpr ~ pavo1 #p p_scpr ~ pravo1 #p p_scpr ~ a*pavo0 #a p_scpr ~ b*pravo0 #a p_ccpt ~ c*pavo1 #a p_ccpt ~ d*pravo1 #a p_ccpt ~ pavo0 #p p_ccpt ~ pravo0 #p p_ccpr ~ pavo1 #p p_ccpr ~ pravo1 #p p_ccpr ~ c*pavo0 # a p_ccpr ~ d*pravo0 #a pravo1 ~~ pravo0 pavo1~~pavo0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr pavo1 ~ pravo1 pavo0 ~pravo0 " posint_avo_afixed_m <- sem(model = posint_avo_afixed, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_avo_pfixed <- " p_scpt ~ pavo1 # actor p_scpt ~ pravo1 # actor p_scpt ~a*pavo0 #partner p_scpt ~b*pravo0 #p p_scpr ~ a*pavo1 #p p_scpr ~ b*pravo1 #p p_scpr ~ pavo0 #a p_scpr ~ pravo0 #a p_ccpt ~ pavo1 #a p_ccpt ~ pravo1 #a p_ccpt ~ c*pavo0 #p p_ccpt ~ d*pravo0 #p p_ccpr ~ c*pavo1 #p p_ccpr ~ d*pravo1 #p p_ccpr ~ pavo0 # a p_ccpr ~ pravo0 #a pravo1 ~~ pravo0 pavo1~~pavo0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr pavo1 ~ pravo1 pavo0 ~pravo0 " posint_avo_pfixed_m <- sem(model = posint_avo_pfixed, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_avo_apfixed <- " p_scpt ~ a*pavo1 # actor p_scpt ~ b*pravo1 # actor p_scpt ~c*pavo0 #partner p_scpt ~d*pravo0 #p p_scpr ~ c*pavo1 #p p_scpr ~ d*pravo1 #p p_scpr ~ a*pavo0 #a p_scpr ~ b*pravo0 #a p_ccpt ~ e*pavo1 #a p_ccpt ~ f*pravo1 #a p_ccpt ~ g*pavo0 #p p_ccpt ~ h*pravo0 #p p_ccpr ~ g*pavo1 #p p_ccpr ~ h*pravo1 #p p_ccpr ~ e*pavo0 # a p_ccpr ~ f*pravo0 #a pravo1 ~~ pravo0 pavo1~~pavo0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr pavo1 ~ pravo1 pavo0 ~pravo0 " posint_avo_apfixed_m <- sem(model = posint_avo_apfixed, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_avo_aonly <- " p_scpt ~ pavo1 # actor p_scpt ~ pravo1 # actor p_scpr ~ pavo0 #a p_scpr ~ pravo0 #a p_ccpt ~ pavo1 #a p_ccpt ~ pravo1 #a p_ccpr ~ pavo0 # a p_ccpr ~ pravo0 #a pravo1 ~~ pravo0 pavo1~~pavo0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr pavo1 ~ pravo1 pavo0 ~pravo0 " posint_avo_aonly_m <- sem(model = posint_avo_aonly, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_avo_ponly <- " p_scpt ~pavo0 #partner p_scpt ~pravo0 #p p_scpr ~ pavo1 #p p_scpr ~ pravo1 #p p_ccpt ~ pavo0 #p p_ccpt ~ pravo0 #p p_ccpr ~ pavo1 #p p_ccpr ~ pravo1 #p pravo1 ~~ pravo0 pavo1~~pavo0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr pavo1 ~ pravo1 pavo0 ~pravo0 " posint_avo_ponly_m <- sem(model = posint_avo_ponly, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_avo_mod <- " p_scpt ~ a*pavo0 #partner p_scpt ~ b*pravo0 #p p_scpr ~ a*pavo1 #p p_scpr ~ b*pravo1 #p p_ccpr ~ pravo1 #p pravo1 ~~ pravo0 pavo1 ~~ pavo0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr pavo1 ~ pravo1 pavo0 ~ pravo0 p_ccpt ~ 0*pavo0 p_ccpt ~ 0*pavo1 p_ccpt ~ 0*pravo0 p_ccpt ~ 0*pravo1 " posint_avo_mod_m <- sem(model = posint_avo_mod, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_avo_mod2 <- " p_scpt ~pravo0 #partner p_scpr ~ pravo1 #p p_ccpr ~ pravo1 #p pavo1 ~ pravo1 pavo0 ~pravo0 pravo1 ~~ pravo0 pavo1 ~~ pavo0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr p_scpt ~~ 0*pavo1 p_scpt ~~ 0*pavo0 p_scpr ~~ 0*pavo1 p_scpr ~~ 0*pavo0 p_ccpr ~~ 0*pavo1 p_ccpr ~~ 0*pavo0 p_ccpt ~ 0*pavo0 p_ccpt ~ 0*pavo1 p_ccpt ~ 0*pravo0 p_ccpt ~ 0*pravo1 " posint_avo_mod2_m <- sem(model = posint_avo_mod2, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_avo_mod3 <- " p_scpt ~pavo0 #partner p_scpr ~ pavo1 #p p_ccpr ~ pravo1 #p pavo1 ~ pravo1 pavo0 ~pravo0 pravo1 ~~ pravo0 pavo1 ~~ pavo0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr p_scpt ~~ 0*pavo1 p_scpt ~~ 0*pavo0 p_scpr ~~ 0*pavo1 p_scpr ~~ 0*pavo0 p_ccpr ~~ 0*pavo1 p_ccpr ~~ 0*pavo0 " posint_avo_mod3_m <- sem(model = posint_avo_mod3, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_avo_mod <- posint_avo_mod2 posint_avo_mod_m <- posint_avo_mod2_m posint_avo_mod <- " p_ccpr ~ pravo1 #p pavo1 ~ pravo1 pavo0 ~pravo0 pravo1 ~~ pravo0 pavo1 ~~ pavo0 p_ccpt ~~ p_ccpr p_ccpr ~~ 0*pavo1 p_ccpr ~~ 0*pavo0 p_ccpt ~ 0*pavo0 p_ccpt ~ 0*pavo1 p_ccpt ~ 0*pravo0 p_ccpt ~ 0*pravo1 " posint_avo_mod_m <- sem(model = posint_avo_mod, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anova(posint_avo_allfree_m, posint_avo_apfixed_m, posint_avo_afixed_m, posint_avo_pfixed_m, posint_avo_aonly_m, posint_avo_ponly_m, posint_avo_mod2_m, posint_avo_mod_m) # favors ponly (which by frequentist measures fits well), greater model_list <- c(posint_avo_allfree_m, posint_avo_apfixed_m, posint_avo_afixed_m, posint_avo_pfixed_m, posint_avo_aonly_m, posint_avo_ponly_m, posint_avo_mod_m) # favors ponly (which by frequentist measures fits well), greater syn_model_list <- c(posint_avo_allfree, posint_avo_apfixed, posint_avo_afixed, posint_avo_pfixed, posint_avo_aonly, posint_avo_ponly, posint_avo_mod) # favors ponly (which by frequentist measures fits well), greater syn_model_list_full <- c(syn_model_list_full, syn_model_list) df <- mapply(pull_fitmeasures, model_list, syn_model_list, list(dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.))) ) if(class(df) == "list") {df <- as.data.frame(do.call(rbind, df)) } else {df <- as.data.frame(t(df))} df <- df%>% mutate_all(funs(as.numeric(.))) df$mname <- "posint_avo" fulldf <- bind_rows(fulldf, df) # Process Model for Posint Anx -------------------------------------------- posint_anx_allfree <- " p_scpt ~ panx1 # actor p_scpt ~ pranx1 # actor p_scpt ~panx0 #partner p_scpt ~pranx0 #p p_scpr ~ panx1 #p p_scpr ~ pranx1 #p p_scpr ~ panx0 #a p_scpr ~ pranx0 #a p_ccpt ~ panx1 #a p_ccpt ~ pranx1 #a p_ccpt ~ panx0 #p p_ccpt ~ pranx0 #p p_ccpr ~ panx1 #p p_ccpr ~ pranx1 #p p_ccpr ~ panx0 # a p_ccpr ~ pranx0 #a pranx1 ~~ pranx0 panx1~~panx0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr panx1 ~ pranx1 panx0 ~pranx0 " posint_anx_allfree_m <- sem(model = posint_anx_allfree, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_anx_afixed <- " p_scpt ~ a*panx1 # actor p_scpt ~ b*pranx1 # actor p_scpt ~panx0 #partner p_scpt ~pranx0 #p p_scpr ~ panx1 #p p_scpr ~ pranx1 #p p_scpr ~ a*panx0 #a p_scpr ~ b*pranx0 #a p_ccpt ~ c*panx1 #a p_ccpt ~ d*pranx1 #a p_ccpt ~ panx0 #p p_ccpt ~ pranx0 #p p_ccpr ~ panx1 #p p_ccpr ~ pranx1 #p p_ccpr ~ c*panx0 # a p_ccpr ~ d*pranx0 #a pranx1 ~~ pranx0 panx1~~panx0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr panx1 ~ pranx1 panx0 ~pranx0 " posint_anx_afixed_m <- sem(model = posint_anx_afixed, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_anx_pfixed <- " p_scpt ~ panx1 # actor p_scpt ~ pranx1 # actor p_scpt ~a*panx0 #partner p_scpt ~b*pranx0 #p p_scpr ~ a*panx1 #p p_scpr ~ b*pranx1 #p p_scpr ~ panx0 #a p_scpr ~ pranx0 #a p_ccpt ~ panx1 #a p_ccpt ~ pranx1 #a p_ccpt ~ c*panx0 #p p_ccpt ~ d*pranx0 #p p_ccpr ~ c*panx1 #p p_ccpr ~ d*pranx1 #p p_ccpr ~ panx0 # a p_ccpr ~ pranx0 #a pranx1 ~~ pranx0 panx1~~panx0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr panx1 ~ pranx1 panx0 ~pranx0 " posint_anx_pfixed_m <- sem(model = posint_anx_pfixed, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_anx_apfixed <- " p_scpt ~ a*panx1 # actor p_scpt ~ b*pranx1 # actor p_scpt ~c*panx0 #partner p_scpt ~d*pranx0 #p p_scpr ~ c*panx1 #p p_scpr ~ d*pranx1 #p p_scpr ~ a*panx0 #a p_scpr ~ b*pranx0 #a p_ccpt ~ e*panx1 #a p_ccpt ~ f*pranx1 #a p_ccpt ~ g*panx0 #p p_ccpt ~ h*pranx0 #p p_ccpr ~ g*panx1 #p p_ccpr ~ h*pranx1 #p p_ccpr ~ e*panx0 # a p_ccpr ~ f*pranx0 #a pranx1 ~~ pranx0 panx1~~panx0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr panx1 ~ pranx1 panx0 ~pranx0 " posint_anx_apfixed_m <- sem(model = posint_anx_apfixed, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_anx_aonly <- " p_scpt ~ panx1 # actor p_scpt ~ pranx1 # actor p_scpr ~ panx0 #a p_scpr ~ pranx0 #a p_ccpt ~ panx1 #a p_ccpt ~ pranx1 #a p_ccpr ~ panx0 # a p_ccpr ~ pranx0 #a pranx1 ~~ pranx0 panx1~~panx0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr panx1 ~ pranx1 panx0 ~pranx0 " posint_anx_aonly_m <- sem(model = posint_anx_aonly, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_anx_ponly <- " p_scpt ~panx0 #partner p_scpt ~pranx0 #p p_scpr ~ panx1 #p p_scpr ~ pranx1 #p p_ccpt ~ panx0 #p p_ccpt ~ pranx0 #p p_ccpr ~ panx1 #p p_ccpr ~ pranx1 #p pranx1 ~~ pranx0 panx1~~panx0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr panx1 ~ pranx1 panx0 ~pranx0 " posint_anx_ponly_m <- sem(model = posint_anx_ponly, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_anx_mod <- " p_scpt ~ c*panx1 # actor p_scpr ~ c*pranx1 #p p_ccpt ~ b*panx1 #a p_ccpt ~ a*pranx1 #a p_ccpr ~ b*panx0 # a p_ccpr ~ a*pranx0 #a pranx1 ~~ pranx0 panx1~~panx0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr panx1 ~ pranx1 panx0 ~pranx0 " posint_anx_mod_m <- sem(model = posint_anx_mod, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_anx_mod2 <- " p_scpt ~ a*pranx1 #+ pranx0 # actor p_scpr ~ a*pranx1 #+ pranx0 #p p_ccpt ~ pranx1 #+ pranx0 #a #p_ccpt ~ pranx1 #a p_ccpr ~ pranx0 #+ pranx1 # a #p_ccpr ~ pranx0 #a pranx1 ~~ pranx0 #panx1~~panx0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr #panx1 ~ pranx1 #panx0 ~pranx0 #p_scpt ~~ 0*panx1 p_scpt ~~ 0*pranx0 #p_scpr ~~ 0*pranx1 p_scpr ~~ 0*pranx0 #p_ccpr ~~ 0*pranx1 p_ccpr ~~ 0*pranx0 p_ccpt ~~ 0*pranx0 " posint_anx_mod2_m <- sem(model = posint_anx_mod2, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_anx_mod3 <- " p_scpt ~ a*panx1 + panx0 # actor p_scpr ~ a*panx1 + panx0 #p p_ccpt ~ panx1 #+ panx0 #a p_ccpr ~ panx0# + panx1 # a panx1~~panx0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr " posint_anx_mod3_m <- sem(model = posint_anx_mod3, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_anx_mod <- " p_ccpt ~ b*panx1 #a p_ccpt ~ a*pranx1 #a p_ccpr ~ b*panx0 # a p_ccpr ~ a*pranx0 #a pranx1 ~~ pranx0 panx1~~panx0 p_ccpt ~~ p_ccpr panx1 ~ pranx1 panx0 ~pranx0 " posint_anx_mod_m <- sem(model = posint_anx_mod, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anova(posint_anx_allfree_m, posint_anx_apfixed_m, posint_anx_afixed_m, posint_anx_pfixed_m, posint_anx_aonly_m, posint_anx_ponly_m, posint_anx_mod_m) # favors modified version of model model_list <- c(posint_anx_allfree_m, posint_anx_apfixed_m, posint_anx_afixed_m, posint_anx_pfixed_m, posint_anx_aonly_m, posint_anx_ponly_m, posint_anx_mod_m) # favors modified version of model syn_model_list <- c(posint_anx_allfree, posint_anx_apfixed, posint_anx_afixed, posint_anx_pfixed, posint_anx_aonly, posint_anx_ponly, posint_anx_mod) # favors modified version of model syn_model_list_full <- c(syn_model_list_full, syn_model_list) df <- mapply(pull_fitmeasures, model_list, syn_model_list, list(dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.))) ) if(class(df) == "list") {df <- as.data.frame(do.call(rbind, df)) } else {df <- as.data.frame(t(df))} df <- df%>% mutate_all(funs(as.numeric(.))) df$mname <- "posint_anx" fulldf <- bind_rows(fulldf, df) # Process Model for Posint Sec -------------------------------------------- posint_sec_allfree <- " p_scpt ~ psec1 # actor p_scpt ~ prsec1 # actor p_scpt ~psec0 #partner p_scpt ~prsec0 #p p_scpr ~ psec1 #p p_scpr ~ prsec1 #p p_scpr ~ psec0 #a p_scpr ~ prsec0 #a p_ccpt ~ psec1 #a p_ccpt ~ prsec1 #a p_ccpt ~ psec0 #p p_ccpt ~ prsec0 #p p_ccpr ~ psec1 #p p_ccpr ~ prsec1 #p p_ccpr ~ psec0 # a p_ccpr ~ prsec0 #a prsec1 ~~ prsec0 psec1~~psec0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr psec1 ~ prsec1 psec0 ~prsec0 " posint_sec_allfree_m <- sem(model = posint_sec_allfree, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_sec_afixed <- " p_scpt ~ a*psec1 # actor p_scpt ~ b*prsec1 # actor p_scpt ~psec0 #partner p_scpt ~prsec0 #p p_scpr ~ psec1 #p p_scpr ~ prsec1 #p p_scpr ~ a*psec0 #a p_scpr ~ b*prsec0 #a p_ccpt ~ c*psec1 #a p_ccpt ~ d*prsec1 #a p_ccpt ~ psec0 #p p_ccpt ~ prsec0 #p p_ccpr ~ psec1 #p p_ccpr ~ prsec1 #p p_ccpr ~ c*psec0 # a p_ccpr ~ d*prsec0 #a prsec1 ~~ prsec0 psec1~~psec0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr psec1 ~ prsec1 psec0 ~prsec0 " posint_sec_afixed_m <- sem(model = posint_sec_afixed, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_sec_pfixed <- " p_scpt ~ psec1 # actor p_scpt ~ prsec1 # actor p_scpt ~a*psec0 #partner p_scpt ~b*prsec0 #p p_scpr ~ a*psec1 #p p_scpr ~ b*prsec1 #p p_scpr ~ psec0 #a p_scpr ~ prsec0 #a p_ccpt ~ psec1 #a p_ccpt ~ prsec1 #a p_ccpt ~ c*psec0 #p p_ccpt ~ d*prsec0 #p p_ccpr ~ c*psec1 #p p_ccpr ~ d*prsec1 #p p_ccpr ~ psec0 # a p_ccpr ~ prsec0 #a prsec1 ~~ prsec0 psec1~~psec0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr psec1 ~ prsec1 psec0 ~prsec0 " posint_sec_pfixed_m <- sem(model = posint_sec_pfixed, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_sec_apfixed <- " p_scpt ~ a*psec1 # actor p_scpt ~ b*prsec1 # actor p_scpt ~c*psec0 #partner p_scpt ~d*prsec0 #p p_scpr ~ c*psec1 #p p_scpr ~ d*prsec1 #p p_scpr ~ a*psec0 #a p_scpr ~ b*prsec0 #a p_ccpt ~ e*psec1 #a p_ccpt ~ f*prsec1 #a p_ccpt ~ g*psec0 #p p_ccpt ~ h*prsec0 #p p_ccpr ~ g*psec1 #p p_ccpr ~ h*prsec1 #p p_ccpr ~ e*psec0 # a p_ccpr ~ f*prsec0 #a prsec1 ~~ prsec0 psec1~~psec0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr psec1 ~ prsec1 psec0 ~prsec0 " posint_sec_apfixed_m <- sem(model = posint_sec_apfixed, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_sec_aonly <- " p_scpt ~ psec1 # actor p_scpt ~ prsec1 # actor p_scpr ~ psec0 #a p_scpr ~ prsec0 #a p_ccpt ~ psec1 #a p_ccpt ~ prsec1 #a p_ccpr ~ psec0 # a p_ccpr ~ prsec0 #a prsec1 ~~ prsec0 psec1~~psec0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr psec1 ~ prsec1 psec0 ~prsec0 " posint_sec_aonly_m <- sem(model = posint_sec_aonly, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_sec_ponly <- " p_scpt ~psec0 #partner p_scpt ~prsec0 #p p_scpr ~ psec1 #p p_scpr ~ prsec1 #p p_ccpt ~ psec0 #p p_ccpt ~ prsec0 #p p_ccpr ~ psec1 #p p_ccpr ~ prsec1 #p prsec1 ~~ prsec0 psec1~~psec0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr psec1 ~ prsec1 psec0 ~prsec0 " posint_sec_ponly_m <- sem(model = posint_sec_ponly, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_sec_mod <- " p_scpt ~ 0*psec1 # actor p_scpt ~ prsec1 # actor p_scpt ~0*psec0 #partner p_scpt ~0*prsec0 #p p_scpr ~ psec1 #p p_scpr ~ 0*prsec1 #p p_scpr ~ 0*psec0 #a p_scpr ~ 0*prsec0 #a p_ccpt ~ 0*psec1 #a p_ccpt ~ 0*prsec1 #a p_ccpt ~ 0*psec0 #p p_ccpt ~ prsec0 #p p_ccpr ~ 0*psec1 #p p_ccpr ~ prsec1 #p p_ccpr ~ 0*psec0 # a p_ccpr ~ prsec0 #a prsec1 ~~ prsec0 psec1~~psec0 p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr psec1 ~ prsec1 psec0 ~prsec0 " posint_sec_mod_m <- sem(model = posint_sec_mod, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) posint_sec_mod <- " p_ccpt ~ 0*psec1 #a p_ccpt ~ 0*prsec1 #a p_ccpt ~ 0*psec0 #p p_ccpt ~ prsec0 #p p_ccpr ~ 0*psec1 #p p_ccpr ~ prsec1 #p p_ccpr ~ 0*psec0 # a p_ccpr ~ prsec0 #a prsec1 ~~ prsec0 psec1~~psec0 p_ccpt ~~ p_ccpr psec1 ~ prsec1 psec0 ~prsec0 " posint_sec_mod_m <- sem(model = posint_sec_mod, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) anova(posint_sec_allfree_m, posint_sec_apfixed_m, posint_sec_afixed_m, posint_sec_pfixed_m, posint_sec_aonly_m, posint_sec_ponly_m, posint_sec_mod_m) model_list <- c(posint_sec_allfree_m, posint_sec_apfixed_m, posint_sec_afixed_m, posint_sec_pfixed_m, posint_sec_aonly_m, posint_sec_ponly_m, posint_sec_mod_m) # fsecrs ponly (which by frequentist measures fits well), greater syn_model_list <- c(posint_sec_allfree, posint_sec_apfixed, posint_sec_afixed, posint_sec_pfixed, posint_sec_aonly, posint_sec_ponly, posint_sec_mod) # favors ponly (which by frequentist measures fits well), greater syn_model_list_full <- c(syn_model_list_full, syn_model_list) df <- mapply(pull_fitmeasures, model_list, syn_model_list, list(dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.))) ) if(class(df) == "list") {df <- as.data.frame(do.call(rbind, df)) } else {df <- as.data.frame(t(df))} df <- df%>% mutate_all(funs(as.numeric(.))) df$mname <- "posint_sec" fulldf <- bind_rows(fulldf, df) ordering <- c("allfree", "afixed", "pfixed", "apfixed", "aonly", "ponly", "mod") fulldf <- fulldf %>% group_by(mname) %>% mutate(model_v = ordering) %>% ungroup() %>% mutate(analysis_name = paste0(mname, "_", model_v)) names(syn_model_list_full) <- as.vector(fulldf$analysis_name) save(syn_model_list_full, file ="../output/bsem_process/model_strings.RData") df_order <- data.frame(mname = c("negint_avo", "negint_anx", "negint_sec", "posint_avo", "posint_anx", "posint_sec"), model_type = 1:length(unique(fulldf$mname))) fulldf <- left_join(fulldf, df_order) fulldf <- group_by(fulldf, model_type) %>% mutate(mnumber = 1:length(V1)) %>% ungroup() fulldf <- arrange(fulldf, fulldf$model_type) write.csv(fulldf, "../output/bsem_process/fit_indices_allprocess_models.csv", row.names= FALSE) # Combined Models -- not nested within others ----------------------------- posnegint_avo_mod <- " #positive interaction regressions p_scpt ~pravo0 #partner p_scpr ~ pravo1 #p p_ccpr ~ pravo1 #p p_scpt ~~ 0*pavo1 p_scpt ~~ 0*pavo0 p_scpr ~~ 0*pavo1 p_scpr ~~ 0*pavo0 p_ccpr ~~ 0*pavo1 p_ccpr ~~ 0*pavo0 p_ccpt ~ 0*pavo0 p_ccpt ~ 0*pavo1 p_ccpt ~ 0*pravo0 p_ccpt ~ 0*pravo1 #negint regressions pavo0 ~ scpr pavo1 ~ a*ccpt ccpt ~ c*pravo1 scpr ~ pravo1 ccpr ~ c*pravo1 pavo1 ~ 0*scpt pavo0 ~ 0*ccpr scpt ~ 0*pravo1 scpt ~ 0*pravo0 scpr ~ 0*pravo0 ccpr ~ 0*pravo0 pavo1 ~ pravo1 pavo0 ~pravo0 #state covariation pravo1 ~~ pravo0 pavo1~~pavo0 #posint covariation p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr #negint covariation scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr #posnegint covariation p_scpt ~ scpt p_scpr ~ scpr #indirect paths ac:=a*c " posnegint_avo_mod_m <- sem(model = posnegint_avo_mod, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) runBSEM(modsyntax(dat =dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), posnegint_avo_mod)) posnegint_anx_mod <- " #posint regressions p_scpt ~ cc*panx1 # actor p_scpr ~ cc*pranx1 #p p_ccpt ~ bb*panx1 #a p_ccpt ~ aa*pranx1 #a p_ccpr ~ bb*panx0 # a p_ccpr ~ aa*pranx0 #a #negint regressions panx1 ~ f*ccpt panx1 ~ scpr panx0 ~ ccpt panx0 ~ scpr panx0 ~ f*ccpr scpt ~ a*pranx0 scpt ~ b*pranx1 scpr ~ a*pranx0 scpr ~ b*pranx1 ccpt ~ h*pranx1 ccpt ~ d*pranx0 ccpr ~ d*pranx1 ccpr ~ h*pranx0 panx1~pranx1 panx0 ~ pranx0 #state covariation pranx1 ~~ pranx0 panx1~~panx0 #negint covariation scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr panx1~~0*scpt panx0~~0*scpt #posint covariation p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr #posnegint covariation p_scpr ~ scpr p_scpt ~ 0*scpt p_scpt ~ 0*ccpt p_scpt ~ 0*scpr p_scpt ~ 0*ccpr p_ccpt ~ 0*scpt p_ccpt ~ 0*ccpt p_ccpt ~ 0*scpr p_ccpt ~ 0*ccpr p_ccpr ~ 0*scpt p_ccpr ~ 0*ccpt p_ccpr ~ 0*scpr p_ccpr ~ 0*ccpr p_scpr ~ 0*ccpt p_scpr ~ 0*scpt p_scpr ~ 0*ccpr " posnegint_anx_mod_m <- sem(model = posnegint_anx_mod, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) runBSEM(modsyntax(dat =dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), posnegint_anx_mod)) # trying to reduce the number of parameters - omitting sc from model; go with mod2 because preserves paths present and/of interest in simpler model and increases K:n ratio posnegint_anx_mod2 <- " #posint regressions p_ccpt ~ bb*panx1 #a p_ccpt ~ aa*pranx1 #a p_ccpr ~ bb*panx0 # a p_ccpr ~ aa*pranx0 #a #negint regressions panx1 ~ f*ccpt panx0 ~ ccpt panx0 ~ f*ccpr ccpt ~ h*pranx1 ccpt ~ d*pranx0 ccpr ~ d*pranx1 ccpr ~ h*pranx0 panx1~pranx1 panx0 ~ pranx0 #state covariation pranx1 ~~ pranx0 panx1~~panx0 #negint covariation ccpt ~~ ccpr #posint covariation p_ccpt ~~ p_ccpr #posnegint covariation p_ccpt ~ 0*ccpt p_ccpt ~ 0*ccpr p_ccpr ~ 0*ccpt p_ccpr ~ 0*ccpr " posnegint_anx_mod2_m <- sem(model = posnegint_anx_mod2, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) runBSEM(modsyntax(dat =dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), posnegint_anx_mod2)) posnegint_avo_mod2 <- " #positive interaction regressions p_ccpr ~ pravo1 #p p_ccpr ~~ 0*pavo1 p_ccpr ~~ 0*pavo0 p_ccpt ~ 0*pavo0 p_ccpt ~ 0*pavo1 p_ccpt ~ 0*pravo0 p_ccpt ~ 0*pravo1 #negint regressions pavo1 ~ a*ccpt ccpt ~ c*pravo1 ccpr ~ c*pravo1 pavo0 ~ 0*ccpr ccpr ~ 0*pravo0 pavo1 ~ pravo1 pavo0 ~pravo0 #state covariation pravo1 ~~ pravo0 pavo1~~pavo0 #posint covariation p_ccpt ~~ p_ccpr #negint covariation ccpt ~~ ccpr #posnegint covariation p_ccpr ~ 0*ccpr p_ccpt ~ 0*ccpt p_ccpr ~ 0*ccpt p_ccpt ~ 0*ccpr #indirect paths ac:=a*c " posnegint_avo_mod2_m <- sem(model = posnegint_avo_mod2, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) runBSEM(modsyntax(dat =dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), posnegint_avo_mod2)) posnegint_sec_mod <- " #posint regressions p_scpt ~ 0*psec1 # actor p_scpt ~ prsec1 # actor p_scpt ~0*psec0 #partner p_scpt ~0*prsec0 #p p_scpr ~ psec1 #p p_scpr ~ 0*prsec1 #p p_scpr ~ 0*psec0 #a p_scpr ~ 0*prsec0 #a p_ccpt ~ 0*psec1 #a p_ccpt ~ 0*prsec1 #a p_ccpt ~ 0*psec0 #p p_ccpt ~ prsec0 #p p_ccpr ~ 0*psec1 #p p_ccpr ~ prsec1 #p p_ccpr ~ 0*psec0 # a p_ccpr ~ prsec0 #a #negint regressions psec1 ~ e*scpt psec1 ~ f*ccpt psec1 ~ 0*scpr psec1 ~ 0*ccpr psec0 ~ a*scpt psec0 ~ b*ccpt psec0 ~ 0*scpr psec0 ~ 0*ccpr scpt ~ g*prsec1 scpt ~ h*prsec0 ccpt ~ 0*prsec1 ccpt ~ 0*prsec0 scpr ~ 0*prsec1 scpr ~0*prsec0 ccpr ~ h*prsec1 ccpr ~ 0*prsec0 psec1~prsec1 psec0 ~ prsec0 #state covariation prsec1 ~~ prsec0 psec1~~psec0 #posint covariation p_scpt ~~ p_ccpt p_scpt ~~ p_scpr p_scpt ~~ p_ccpr p_ccpt ~~ p_scpr p_ccpt ~~ p_ccpr p_scpr ~~ p_ccpr #negint covariation scpt ~~ ccpt scpt ~~ scpr scpt ~~ ccpr ccpt ~~ scpr ccpt ~~ ccpr scpr ~~ ccpr #posnegint covariation p_scpr ~ scpr p_scpt ~ scpt p_scpt ~ 0*ccpt p_scpt ~ 0*scpr p_scpt ~ 0*ccpr p_ccpt ~ 0*scpt p_ccpt ~ 0*ccpt p_ccpt ~ 0*scpr p_ccpt ~ 0*ccpr p_ccpr ~ 0*scpt p_ccpr ~ 0*ccpt p_ccpr ~ 0*scpr p_ccpr ~ 0*ccpr p_scpr ~ 0*ccpt p_scpr ~ 0*scpt p_scpr ~ 0*ccpr " posnegint_sec_mod_m <- sem(model = posnegint_sec_mod, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) runBSEM(modsyntax(dat =dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), posnegint_sec_mod)) posnegint_sec_mod2 <- " #posint regressions p_ccpt ~ 0*psec1 #a p_ccpt ~ 0*prsec1 #a p_ccpt ~ 0*psec0 #p p_ccpt ~ prsec0 #p p_ccpr ~ 0*psec1 #p p_ccpr ~ prsec1 #p p_ccpr ~ 0*psec0 # a p_ccpr ~ prsec0 #a #negint regressions psec1 ~ f*ccpt psec1 ~ 0*ccpr psec0 ~ b*ccpt psec0 ~ 0*ccpr ccpt ~ 0*prsec1 ccpt ~ 0*prsec0 ccpr ~ h*prsec1 ccpr ~ 0*prsec0 psec1~prsec1 psec0 ~ prsec0 #state covariation prsec1 ~~ prsec0 psec1~~psec0 #posint covariation p_ccpt ~~ p_ccpr #negint covariation ccpt ~~ ccpr #posnegint covariation p_ccpt ~ 0*ccpt p_ccpt ~ 0*ccpr p_ccpr ~ 0*ccpt p_ccpr ~ 0*ccpr " posnegint_sec_mod2_m <- sem(model = posnegint_sec_mod2, data = dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), missing = "ML",estimator = "MLR", meanstructure = TRUE, mimic = "Mplus", conditional.x = FALSE) runBSEM(modsyntax(dat =dplyr::mutate_at(posnegint_personality, vars(starts_with("p_")), list(~100*.)), posnegint_sec_mod2)) # so psec0 ~ ccpt goes from sig to marginal (.025 to .028) and ccpr ~ prsec1 goes from .024 to .036. But other effects remain. End up with 25 additional free parameters too... Ask Michael but feels like should still go with the simpler model SINCE adding additional parameters syn_comb_models <- c(posnegint_avo_mod, posnegint_avo_mod2,posnegint_anx_mod,posnegint_anx_mod2, posnegint_sec_mod, posnegint_sec_mod2) names(syn_comb_models) <- c("posnegint_avo_mod", "posnegint_avo_mod2","posnegint_anx_mod","posnegint_anx_mod2", "posnegint_sec_mod", "posnegint_sec_mod2") save(syn_comb_models, file = "../output/bsem_process/model_comb_strings.RData") ## Summary of findings from process results # Baseline avoidance in patient predicts contrarian in both patient and partner during negative interaction and contrarianism during the positive interaction for the partner. Contrarianism is sticky with patient where it subsequently is associated with heightened feels of attachment avoidance in patient. #Baseline momentary anxiety predicts within person tendency to be contrarian during the positive interaction and marginally so in the negative interaction. This is true in both patients and partners. Within person effect such that exhibiting dependency during the interaction amplifies anxiety (being contrarian CAN lead to decreases in anxiety too, not just weaker increases).
566202ed1c8769f5ad66f66c9118f800f26a6830
ef572bd2b0515892d1f59a073b8bf99f81d6a734
/data-raw/update_cached_map_datapack_cogs.R
3bdd2f4eda1c99d04a387d4149aa3829bb28f290
[ "CC0-1.0" ]
permissive
pepfar-datim/datapackr
5bc604caa1ae001b6c04e1d934c0c613c59df1e6
9275632673e45948db6846513a53c1436cfc0e47
refs/heads/master
2023-08-30T23:26:48.454382
2023-08-11T13:01:57
2023-08-11T13:01:57
170,350,211
9
7
CC0-1.0
2023-09-11T21:53:24
2019-02-12T16:19:47
R
UTF-8
R
false
false
1,229
r
update_cached_map_datapack_cogs.R
# Load PSNUs into package from DATIM #### library(magrittr) library(datapackr) # Point to DATIM login secrets #### secrets <- Sys.getenv("SECRETS_FOLDER") %>% paste0(., "cop-test.json") datimutils::loginToDATIM(secrets) # Processing datapack_cogs <- datapackr::datapack_cogs datapack_cogs$COP22 <- datimutils::getMetadata(categoryOptionGroups, fields = "id,name,categoryOptions[id,name]", # nolint "groupSets.id:eq:hdEmBvPF3iq", d2_session = d2_default_session) datapack_cogs$COP23 <- datimutils::getMetadata(categoryOptionGroups, fields = "id,name,categoryOptions[id,name]", # nolint "groupSets.id:eq:CIqgMytqbMA", d2_session = d2_default_session) datapack_cogs$COP24 <- # Patch before MER 3.0 deployment: datapack_cogs$COP23 # datimutils::getMetadata(categoryOptionGroups, # fields = "id,name,categoryOptions[id,name]", # nolint # "groupSets.id:eq:CIqgMytqbMA", # d2_session = d2_default_session) save(datapack_cogs, file = "./data/datapack_cogs.rda", compress = "xz")
91d889ea878a9b28d6c06ecc0e1c0abec2e7add0
6be70ffdb95ed626d05b5ef598b842c5864bac4d
/old/senate_party_calls_replicate_figures_emIRT_only.R
2c458e2313bd3927b81feb88c1111310d53d268b
[]
no_license
Hershberger/partycalls
c4f7a539cacd3120bf6b0bfade327f269898105a
8d9dc31dd3136eae384a8503ba71832c78139870
refs/heads/master
2021-09-22T17:54:29.106667
2018-09-12T21:16:56
2018-09-12T21:16:56
null
0
0
null
null
null
null
UTF-8
R
false
false
4,906
r
senate_party_calls_replicate_figures_emIRT_only.R
library(partycalls) library(data.table) options(stringsAsFactors = FALSE) # load data for analysis load("data/senator_year_data_emIRT_only.RData") senator_year_data <- senator_year_data[senator_year_data$drop == 0] # whoheeds13 <- readstata13::read.dta13( # "inst/extdata/who-heeds-replication-archive.dta") # setDT(new_whoheeds13) # setDT(whoheeds13) # new_whoheeds13 <- merge(new_whoheeds13, whoheeds13, by = c("congress", "icpsr")) # setDT(new_whoheeds13) # # regression formulas and functions # f.meddist <- new_pirate100 ~ new_distance_from_floor_median + # responsiveness_noncalls + vote_share * pres_vote_share + south13 + female + # afam + latino + up_for_reelection + seniority + freshman + retiree + # best_committee + leader + power_committee + chair f.extremism <- responsiveness_party_calls ~ ideological_extremism + responsiveness_noncalls + vote_share * pres_vote_share + south13 + female + afam + latino + up_for_reelection + seniority + freshman + retiree + best_committee + leader + power_committee + chair # To see a regression from a particular congress, use these functions: # fm.meddist <- function(i, j) { # summary(lm(f.meddist, # data=subset(senator_year_data, congress==i & majority==j)), # vcov=vcovHC(type="HC1")) # } fm.extremism <- function(i, j) { summary(lm(f.extremism, data=subset(senator_year_data, congress==i & majority==j)), vcov=vcovHC(type="HC1")) } # Uncomment to use # fm.meddist(93, 1) # <- produces regression results for Distance from the # Median Model for majority party in 93rd Congress; # change 1 to 0 for minority party # Produce results for Figure 2 B <- SE <- data.frame(row.names=93:112) # B$meddist.maj <- do.call(c, lapply(93:112, function(x) # fm.meddist(x, 1)$coef[2, 1])) # B$meddist.min <- do.call(c, lapply(93:112, function(x) # fm.meddist(x, 0)$coef[2, 1])) B$extremism.maj <- do.call(c, lapply(93:112, function(x) fm.extremism(x, 1)$coef[2, 1])) B$extremism.min <- do.call(c, lapply(93:112, function(x) fm.extremism(x, 0)$coef[2, 1])) # SE$meddist.maj <- do.call(c, lapply(93:112, function(x) # fm.meddist(x, 1)$coef[2, 2])) # SE$meddist.min <- do.call(c, lapply(93:112, function(x) # fm.meddist(x, 0)$coef[2, 2])) SE$extremism.maj <- do.call(c, lapply(93:112, function(x) fm.extremism(x, 1)$coef[2, 2])) SE$extremism.min <- do.call(c, lapply(93:112, function(x) fm.extremism(x, 0)$coef[2, 2])) pdf(file="plots/who-heeds-figure2-senate_emIRT_only.pdf", ## RENAME width=4, height = 8, family="Times") layout(matrix(1:2, 2, 1, byrow=TRUE)) par(mar=c(2.5, 4, 2, 0.3) + 0.1, font.lab=2) x <- (93:112)[-12] x.ticks <- c(94, 99, 104, 109) y.ticks <- c(-12, 0, 12, 24, 36) # b <- B$meddist.maj[-12] # se <- SE$meddist.maj[-12] # plot(0, 0, type='n', ylim=c(-6, 36), xlim=c(93, 109), # cex.lab=1.15, xaxt="n", yaxt="n", xlab="", ylab="Majority Party") # axis(1, x.ticks, cex.axis=1.1, labels=FALSE, xpd=TRUE) # axis(2, y.ticks, cex.axis=1.1, labels=TRUE) # abline(h=0, col="gray", xpd=FALSE) # title(main="Distance from Floor Median", cex.main=1.15, line=0.75, font.main=2) # points(x, b, pch=19, col="black", cex=.8) # segments(x, b-qnorm(.750)*se, x, b+qnorm(.750)*se, lwd=2) # segments(x, b-qnorm(.975)*se, x, b+qnorm(.975)*se, lwd=.9) b <- B$extremism.maj[-12] se <- SE$extremism.maj[-12] plot(0, 0, type='n', ylim=c(-18, 42), xlim=c(93, 112), cex.lab=1.15, xaxt="n", yaxt="n", xlab="", ylab="") axis(1, x.ticks, cex.axis=1.1, labels=TRUE) axis(2, y.ticks, cex.axis=1.1, labels=TRUE) abline(h=0, col="gray", xpd=FALSE) title(main="Ideological Extremism", cex.main=1.15, line=0.75, font.main=2) points(x, b, pch=19, col="black", cex=.8) segments(x, b-qnorm(.750)*se, x, b+qnorm(.750)*se, lwd=2) segments(x, b-qnorm(.975)*se, x, b+qnorm(.975)*se, lwd=.9) # b <- B$meddist.min[-12] # se <- SE$meddist.min[-12] # plot(0, 0, type='n', ylim=c(-6, 36), xlim=c(93, 109), # cex.lab=1.15, xaxt="n", yaxt="n", xlab="", ylab="Minority Party") # axis(1, x.ticks, cex.axis=1.1, labels=TRUE, xpd=TRUE) # axis(2, y.ticks, cex.axis=1.1, labels=TRUE) # abline(h=0, col="gray", xpd=FALSE) # title(main="", cex.main=1.15, line=0.75, font.main=2) # points(x, b, pch=19, col="black", cex=.8) # segments(x, b-qnorm(.750)*se, x, b+qnorm(.750)*se, lwd=2) # segments(x, b-qnorm(.975)*se, x, b+qnorm(.975)*se, lwd=.9) b <- B$extremism.min[-12] se <- SE$extremism.min[-12] plot(0, 0, type='n', ylim=c(-18, 42), xlim=c(93, 112), cex.lab=1.15, xaxt="n", yaxt="n", xlab="", ylab="") axis(1, x.ticks, cex.axis=1.1, labels=TRUE, xpd=TRUE) axis(2, y.ticks, cex.axis=1.1, labels=TRUE) abline(h=0, col="gray", xpd=FALSE) title(main="", cex.main=1.15, line=0.75, font.main=2) points(x, b, pch=19, col="black", cex=.8) segments(x, b-qnorm(.750)*se, x, b+qnorm(.750)*se, lwd=2) segments(x, b-qnorm(.975)*se, x, b+qnorm(.975)*se, lwd=.9) # NAME FIGURE WITH CLASSIFICATION METHOD IN TEX CAPTION dev.off()
7722403a336a399bd19c2208149d259764073cb8
727e491d1d19394960d52f732e367f37be038956
/dieroller/dieroller.Rcheck/00_pkg_src/dieroller/R/hello.R
35e2345e0f7a968fc2f454eb8a51cb0acd9431d7
[]
no_license
JustinRiverNg/Computing-Data
a0a3ddd9a0ae11699bdf3efe34cda7dc45b369fd
4ff7415cb09b5148fadb51310b27dbdd1746603b
refs/heads/master
2020-03-30T10:34:10.423755
2018-04-27T18:12:36
2018-04-27T18:12:36
151,125,755
0
0
null
null
null
null
UTF-8
R
false
false
7,881
r
hello.R
# Hello, world! # # This is an example function named 'hello' # which prints 'Hello, world!'. # # You can learn more about package authoring with RStudio at: # # http://r-pkgs.had.co.nz/ # # Some useful keyboard shortcuts for package authoring: # # Build and Reload Package: 'Cmd + Shift + B' # Check Package: 'Cmd + Shift + E' # Test Package: 'Cmd + Shift + T' #1) Object "die" #' @title Die Creation #' @description Creates a die of object class "die" #' @param sides a vector of length 6 representing the sides of the die #' @param prob a vector of length 6 with sum of 1 representing the probability of rolling each respective side #' @return A data table expressing each side of the die and its respective probabilities die <- function(sides = c("1", "2", "3", "4", "5", "6"), prob = c(1/6, 1/6, 1/6, 1/6, 1/6, 1/6)) { check_sides(sides) check_prob(prob) res <- list(sides = sides, prob = prob) class(res) <- "die" return(res) } #' @title Print Die Method #' @description Print method for objects of class "die" #' @param x a "die" object #' @return A data table expressing each side of the die and its respective probabilities print.die <- function(x) { cat('object "die"\n\n') cd <- data.frame( side = x$sides, prob = x$prob ) print(cd) invisible(x) } #' @title Check Probability Function #' @description Checks that the vector of probabilities is valid #' @param x a vector of probabilties #' @return True if the vectors of probabilities is of length 6, sums to 1, and that none of the probabilities is less than 0 or greater than 1. Else, error check_prob <- function(prob) { if(length(prob) !=6 | !is.numeric(prob)) { stop("\n'prob' must be a numeric vector of length 6") } if(any(prob < 0) | any(prob > 1)) { stop("\n'prob' values must be between 0 and 1") } if(sum(prob) !=1) { stop("\n'prob' values must be between 0 and 1") } TRUE } #' @title Check Sides Function #' @description Checks that the vector of sides is of length 6 #' @param x A vector of sides #' @return True if the vector contains 6 values. Else, error check_sides <- function(sides) { if (length(sides) != 6) { stop("\n'sides' must be on length 6") } } fair_die <- die() fair_die weird_die <- die(sides = c('i', 'ii', 'iii', 'iv', 'v', 'vi')) weird_die loaded_die <- die(prob = c(0.075, 0.1, 0.125, 0.15, 0.20, 0.35)) loaded_die bad_die <- die(sides = c('a', 'b', 'c', 'd', 'e')) bad_die2 <- die(sides = c('a', 'b', 'c', 'd', 'e', 'f'), prob = c(0.2, 0.1, 0.1, 0.1, 0.5, 0.1)) practice_die <- die(sides = c('1', '2', '3', '4', '5', '6'), prob = c(0, 0, 0, .34, .33, .33)) #2) Object "roll" #' @title Check Times Function #' @description Checks that the number of times of rolling is valid #' @param times an integer of number of times to roll #' @return TRUE if times is an integer >= 0. Else, error check_times <- function(times) { if (times <= 0 | !is.numeric(times)) { stop("\n'times' must be a positive integer") } else { TRUE } } #' @title Roll #' @description Computes the results of rolling a specified die a specificied number of times #' @param z a die of class "die" #' @param times number of times the die is being rolled #' @return The results from rolling the die the specified number of times roll <- function(z, times = 1) { check_times(times) if(class(z) !="die") { stop("\nroll() requires an object 'die'") } rolls <- sample(z$sides, size = times, replace = TRUE, prob = z$prob) res <- list( sides = z$sides, rolls = rolls, prob = z$prob, total = length(rolls)) class(res) <- "roll" res } #' @title Print Die Method #' @description A print method for the roll function #' @param q a roll function #' @return A transformed version of the results from the roll function print.roll <- function(q) { cat('object "roll"\n') print(q$rolls) } set.seed(123) fair50 <- roll(fair_die, times = 50) fair50 names(fair50) fair50$rolls fair50$sides fair50$prob fair50$total str_die <- die( sides = c('a', 'b', 'c', 'd', 'e', 'f'), prob = c(0.075, 0.1, 0.125, 0.15, 0.20, 0.35)) set.seed(123) str_rolls <- roll(str_die, times = 20) names(str_rolls) str_rolls #3) Summary Method for "Roll" Objects #' @title Roll Summary #' @description Gives the summary of a sample of rolls. #' @param w a "roll" object that contains a sample of rolls with a specified die #' @return A data table listing a summary of the sample summary.roll <- function(w) { if(class(w) !="roll") { stop("\nsummary() requires an object 'roll'") } side <- w$sides count <- as.data.frame(table(w$rolls))[ ,2] prop <- (count/w$total) freqs <- data.frame(side, count, prop) res2 <- list(freqs = freqs) class(res2) <- "summary.roll" res2 } #' @title Print Summary Roll #' @description A print method for summary.roll #' @param e a summary.roll function #' @return A modified data table listing a summary of the sample print.summary.roll <- function(e) { cat('summary "roll" \n\n') print(as.data.frame(e$freqs)) } set.seed(123) fair_50rolls <- roll(fair_die, times = 50) fair50_sum <- summary(fair_50rolls) fair50_sum class(fair50_sum) names(fair50_sum) fair50_sum$freqs #4) Plot method for "roll" objects one_freqs <- function(x) { (cumsum(x$rolls == x$sides[1]) / 1:x$total)[x$total] } two_freqs <- function(x) { (cumsum(x$rolls == x$sides[2]) / 1:x$total)[x$total] } three_freqs <- function(x) { (cumsum(x$rolls == x$sides[3]) / 1:x$total)[x$total] } four_freqs <- function(x) { (cumsum(x$rolls == x$sides[4]) / 1:x$total)[x$total] } five_freqs <- function(x) { (cumsum(x$rolls == x$sides[5]) / 1:x$total)[x$total] } six_freqs <- function(x) { (cumsum(x$rolls == x$sides[6]) / 1:x$total)[x$total] } #' @title Frequencies #' @description Determines what relative frequency to call upon #' @param x the roll function #' @param side the number of side to call upon #' @return The relative frequency of the called upon side frequencies <- function(x, side = 1) { if(side == 1) { return(one_freqs(x)) } if(side == 2) { return(two_freqs(x)) } if(side == 3) { return(three_freqs(x)) } if(side == 4) { return(four_freqs(x)) } if(side == 5) { return(five_freqs(x)) } if(side == 6) { return(six_freqs(x)) } } #' @title Plot Roll #' @description Creates a bar plot of a roll function #' @param x a sample of rolls #' @return A barplot for the sample of rolls plot.roll <- function(x) { barplot(c(frequencies(x), frequencies(x, 2), frequencies(x, 3), frequencies(x, 4), frequencies(x, 5), frequencies(x, 6)), as.numeric(x$side), type = 'n' , ylim = c(0,.2), las = 1, xlab = "sides of die" , bty = 'n', ylab = sprintf("relative frequencies") , names.arg = c(x$side[1], x$side[2], x$side[3], x$side[4], x$side[5], x$side[6])) } plot(fair_50rolls) #5) Additional Methods "[.roll" <- function(x, i) { x$rolls[i] } set.seed(123) fair500 <- roll(fair_die, times = 500) fair500[500] "[<-.roll" <- function(x, i, value) { x$rolls[i] <- value return(x$rolls) } fair500[500] <- 1 fair500 fair500[500] summary(fair500) #5) Additional Methods "[.roll" <- function(x, i) { x$rolls[i] } set.seed(123) fair500 <- roll(fair_die, times = 500) fair500[500] "[<-.roll" <- function(x, i, value) { x$rolls[i] <- value return(x$rolls) } fair500[500] <- 1 fair500 fair500[500] "+.roll" <- function(obj, incr) { if (length(incr) != 1 | incr <= 0) { stop("\ninvalid increament (must be positive)") } more_rolls <- roll(obj$x, times = incr) rolls <- sample(x$sides, size = times, replace = TRUE, prob = x$prob) res <- list( sides = x$sides, rolls = rolls, prob = x$prob, total = length(rolls)) class(res) <- "roll" res } fair600 <- fair500 + 100
334141a545dd8c654fe3bee70856ff9fb2a18ba0
0b5a137ce9998b30efd1a2b3061712951602f4c0
/analysis/fit_model.R
10329eb427475f05efe3e618fad22b753f043fe9
[]
no_license
jsphillips2/midge_pi
0c272ba3acdef5faddb999240251382ea917d41b
33e28ff1a250620f201299feadb67a6a33ea8b9e
refs/heads/master
2022-12-01T13:36:36.001157
2020-07-28T13:54:10
2020-07-28T13:54:10
277,593,334
0
0
null
null
null
null
UTF-8
R
false
false
2,578
r
fit_model.R
#========== #========== Preliminaries #========== # load packages library(tidyverse) library(rstan) source("analysis/model_fn.R") # stan settings rstan_options(auto_write = TRUE) options(mc.cores = parallel::detectCores()-2) # import data data <- read_csv("data/metabolism_2015.csv") # process data dd <- data %>% filter(trial=="a") %>% mutate( rateo2 = 15*(do_f - do_i)/(100*duration), day = as.numeric(date) - min(as.numeric(date)) + 3, time = as.numeric(as.factor(day))-1, temp = (temp_i + temp_f)/2 ) %>% rename(par = light) %>% select(core, rack, date, day, time, par, midge, rateo2, temp) %>% na.omit() %>% filter(rateo2 > -3) # data frame for summary dd_sum <- dd %>% mutate(id = interaction(time, midge)) %>% split(.$id) %>% lapply(function(x) { x %>% tidyr::expand(par = seq(min(par), max(par), length.out = 100)) %>% mutate(time = unique(x$time), midge = unique(x$midge)) }) %>% bind_rows() #========== #========== Fit model #========== # model form forms <- c("both","midge_b","midge_a","none") form <- forms[1] if(form == "both") {b = formula(~ 1 + time * midge) a = formula(~ 1 + time * midge) r = formula(~ 1 + time * midge)} if(form == "midge_b") {b = formula(~ 1 + time * midge) a = formula(~ 1 + time) r = formula(~ 1 + time * midge)} if(form == "midge_a") {b = formula(~ 1 + time) a = formula(~ 1 + time * midge) r = formula(~ 1 + time * midge)} if(form == "none") {b = formula(~ 1 + time) a = formula(~ 1 + time) r = formula(~ 1 + time * midge)} # package data data_list <- model_fn(b_ = b, a_ = a, r_ = r, dd_ = dd, dd_sum_ = dd_sum) # MCMC specifications chains <- 6 iter <- 4000 adapt_delta <- 0.9 max_treedepth <- 10 # fit model fit <- stan(file = "analysis/midge_pi.stan", data = data_list, seed=2e3, chains = chains, iter = iter, control = list(adapt_delta = adapt_delta, max_treedepth = max_treedepth)) # summary of fit fit_summary <- summary(fit, probs=c(0.16, 0.5, 0.84))$summary %>% {as_tibble(.) %>% mutate(var = rownames(summary(fit)$summary))} # export write_rds(list(b = b, a = a, r = r, data_list = data_list, fit = fit, fit_summary = fit_summary), paste0("analysis/model_fit_ii/",form,".rds"))
7cc5954d2799faec76769c7ae25ca5dd11bfc3db
1dc421a198c86a888f2029ce96d09924aac6cab2
/R/testIndSpeedglm.R
f79b939f052f93648e27825b5a645c5a13fa5487
[]
no_license
JokerWhy233/MXM
519b8216a1a2a965a8e43531fd52fb0a7c460f86
035673338ed6647239a4859981918ddf3b8ce38e
refs/heads/master
2021-08-22T14:54:05.597447
2017-11-30T10:41:38
2017-11-30T10:41:38
null
0
0
null
null
null
null
UTF-8
R
false
false
8,790
r
testIndSpeedglm.R
testIndSpeedglm = function(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, target_type = 0, robust = FALSE) { # TESTINDSPEEDGLM Conditional independence test for large sample sized data (tens and hundreds of thousands) for normal, binary discrete or ordinal class variables # provides a p-value PVALUE for the null hypothesis: X independent by target # given CS. The pvalue is calculated by comparing a logistic model based # on the conditioning set CS against a model containing both X and CS. # The comparison is performed through a chi-square test with one degree # of freedom on the difference between the deviances of the two models. # TESTINDSPEEDGLM requires the following inputs: # target: a vector containing the values of the target variable. # target must be a vector with percentages, binay data, numerical values or integers # dataset: a numeric data matrix containing the variables for performing # the conditional independence test. They can be mixed variables, either continous or categorical # xIndex: the index of the variable whose association with the target # must be tested. Can be any type of variable, either continous or categorical. # csIndex: the indices of the variables to condition on. They can be mixed variables, either continous or categorical # target_Type: the type of the target # target_type == 1 (normal target) # target_type == 2 (binary target) # target_type == 3 (discrete target) # default target_type=0 # this method returns: the pvalue PVALUE, the statistic STAT and a control variable FLAG. # if FLAG == 1 then the test was performed succesfully #cast factor into numeric vector target = as.numeric( as.vector(target) ); csIndex[which(is.na(csIndex))] = 0 if ( hash ) { csIndex2 = csIndex[which(csIndex!=0)] csIndex2 = sort(csIndex2) xcs = c(xIndex,csIndex2) key = paste(as.character(xcs) , collapse=" "); if (is.null(stat_hash[[key]]) == FALSE) { stat = stat_hash[[key]]; pvalue = pvalue_hash[[key]]; flag = 1; results <- list(pvalue = pvalue, stat = stat, flag = flag, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } #if the test cannot performed succesfully these are the returned values pvalue = log(1); stat = 0; flag = 0; #if the xIndex is contained in csIndex, x does not bring any new #information with respect to cs if (!is.na( match(xIndex, csIndex) ) ) { if ( hash ) { #update hash objects stat_hash$key <- 0;#.set(stat_hash , key , 0) pvalue_hash$key <- log(1);#.set(pvalue_hash , key , 1) } results <- list(pvalue = log(1), stat = 0, flag = 1, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } #check input validity if (xIndex < 0 || csIndex < 0) { message(paste("error in testIndSpeedglm : wrong input of xIndex or csIndex")) results <- list(pvalue = pvalue, stat = stat, flag = flag, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } #xIndex = unique(xIndex); #csIndex = unique(csIndex); #extract the data x = dataset[ , xIndex]; cs = dataset[ , csIndex]; #if x or target is constant then there is no point to perform the test # if ( Rfast::Var( as.numeric(x) ) == 0 ) { # if ( hash ) { #update hash objects # stat_hash$key <- 0; #.set(stat_hash , key , 0) # pvalue_hash$key <- log(1); #.set(pvalue_hash , key , 1) # } # results <- list(pvalue = log(1), stat = 0, flag = 1, stat_hash=stat_hash, pvalue_hash=pvalue_hash); # return(results); # } #remove NAs-zeros from cs #csIndex = csIndex[csIndex!=0] if(length(cs) == 0 || is.na(cs) ) cs = NULL; #if x = any of the cs then pvalue = log(1) and flag = 1. #That means that the x variable does not add more information to our model due to an exact copy of this in the cs, so it is independent from the target if ( length(cs) != 0 ) { if ( is.null(dim(cs)[2]) ) { #cs is a vector if ( identical(x, cs) ) { #if(!any(x == cs) == FALSE) if ( hash ) { #update hash objects stat_hash$key <- 0; #.set(stat_hash , key , 0) pvalue_hash$key <- log(1); #.set(pvalue_hash , key , 1) } results <- list(pvalue = log(1), stat = 0, flag = 1 , stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } else { #more than one var for (col in 1:dim(cs)[2]) { if ( identical(x, cs[, col]) ) { #if(!any(x == cs) == FALSE) if ( hash ) { #update hash objects stat_hash$key <- 0; #.set(stat_hash , key , 0) pvalue_hash$key <- log(1); #.set(pvalue_hash , key , 1) } results <- list(pvalue = log(1), stat = 0, flag = 1 , stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } } } #binomial or multinomial target? yCounts = length( unique(target) ); if (yCounts == 2) { target_type = 1; } else if ( identical(floor(target), target) ) { target_type = 2 } else target_type = 3 #if the conditioning set (cs) is empty, we use the t-test on the coefficient of x. if (length(cs) == 0) { if ( target_type == 3 ) { fit2 = speedglm::speedlm( target ~ x, weights = wei, data = as.data.frame(x) ) if ( any( is.na(coef(fit2)) ) ) { stat = 0 pvalue = log(1) flag = 1; } else { suma = summary(fit2)[[ 13 ]] stat = suma[1] dof = suma[3] pvalue = pf(stat, 1, dof, lower.tail = FALSE, log.p = TRUE) flag = 1; } } else if (target_type == 1){ fit2 = speedglm::speedglm(target ~ x, weights = wei, data = as.data.frame(x), family = binomial(logit) ) stat = fit2$nulldev - fit2$deviance dof = length( coef(fit2) ) - 1 pvalue = pchisq(stat, dof, lower.tail = FALSE, log.p = TRUE) flag = 1; } else { fit2 = speedglm::speedglm(target ~ x, weights = wei, data = as.data.frame(x), family = poisson(log) ) stat = fit2$nulldev - fit2$deviance dof = length( coef(fit2) ) - 1 pvalue = pchisq(stat, dof, lower.tail = FALSE, log.p = TRUE) flag = 1; } } else { if ( target_type == 3 ) { fit1 = speedglm::speedlm( target ~ dataset[, csIndex], data = as.data.frame( dataset[, c(csIndex, xIndex)] ), weights = wei ) fit2 = speedglm::speedlm( target ~., data = as.data.frame( dataset[, c(csIndex, xIndex)] ), weights = wei ) d1 = length( coef(fit1) ) d2 = length( coef(fit2) ) df1 = d2 - d1 df2 = length(target) - d2 stat = ( (fit1$RSS - fit2$RSS)/df1 ) / ( fit2$RSS /df2 ) pvalue = pf(stat, df1, df2, lower.tail = FALSE, log.p = TRUE) flag = 1; } else if (target_type == 1) { fit1 = speedglm::speedglm( target ~ dataset[, csIndex], data = as.data.frame( dataset[, c(xIndex, csIndex)] ), family = binomial(logit), weights = wei ) fit2 = speedglm::speedglm( target ~ ., data = as.data.frame( dataset[, c(xIndex, csIndex)] ), family = binomial(logit), weights = wei ) stat = fit1$deviance - fit2$deviance dof = length( coef(fit2) ) - length( coef(fit1) ) pvalue = pchisq(stat, dof, lower.tail = FALSE, log.p = TRUE) flag = 1; } else { fit1 = speedglm::speedglm( target ~ dataset[, csIndex], data = as.data.frame( dataset[, c(xIndex, csIndex)] ), family = poisson(log), weights = wei ) fit2 = speedglm::speedglm( target ~ ., data = as.data.frame( dataset[, c(xIndex, csIndex)] ), family = poisson(log), weights = wei ) stat = fit1$deviance - fit2$deviance dof = length( coef(fit2) ) - length( coef(fit1) ) pvalue = pchisq(stat, dof, lower.tail = FALSE, log.p = TRUE) flag = 1; } } #update hash objects if( hash ) { stat_hash$key <- stat;#.set(stat_hash , key , stat) pvalue_hash$key <- pvalue;#.set(pvalue_hash , key , pvalue) } #last error check if ( is.na(pvalue) || is.na(stat) ) { pvalue = log(1); stat = 0; flag = 0; } else { #update hash objects if( hash ) { stat_hash[[key]] <- stat;#.set(stat_hash , key , stat) pvalue_hash[[key]] <- pvalue;#.set(pvalue_hash , key , pvalue) } } results <- list(pvalue = pvalue, stat = stat, flag = flag, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); }
94e5857e3b152851644083bb8737371274f5fe63
aff8c05c8d8c6f7ac6b95d535aa3a00576c14798
/fuzzycmeans/fuzzycmeans.R
8d928cf9bcbd094afbb4f2a258832bcef0a0dffb
[]
no_license
coppolalab/Chandran_pipeline
6905263d043bd34c82e4d5a0deda9744d6d2f16a
84fbf25398deb9e2e47ad2df7bdbdcc6f87d988e
refs/heads/master
2021-01-22T22:13:22.137333
2017-03-20T00:52:41
2017-03-20T00:52:41
85,520,556
0
0
null
null
null
null
UTF-8
R
false
false
4,717
r
fuzzycmeans.R
#String operations library(stringr) #Reading and writing tables library(readr) library(openxlsx) #For plotting library(ggplot2) #For microarray stuff library(Biobase) library(matrixStats) library(abind) library(lumi) library(lumiHumanAll.db) library(annotate) library(sva) library(peer) library(limma) #Longitudinal analysis library(Mfuzz) #Plotting library(Cairo) library(WGCNA) library(heatmap.plus) library(flashClust) enableWGCNAThreads() #Data arrangement library(reshape2) library(plyr) library(dplyr) library(tidyr) library(doBy) #Functional programming library(magrittr) library(purrr) library(functional) library(vadr) saveRDS.gz <- function(object,file,threads=parallel::detectCores()) { con <- pipe(paste0("pigz -p",threads," > ",file),"wb") saveRDS(object, file = con) close(con) } readRDS.gz <- function(file,threads=parallel::detectCores()) { con <- pipe(paste0("pigz -d -c -p",threads," ",file)) object <- readRDS(file = con) close(con) return(object) } csel.repeat <- function(eset, m, crange, max.runs, csel.mat = matrix(), count.runs = 0) { csel.out <- cselection(eset, m = m, crange = crange, repeats = 5, visu = FALSE) if (count.runs == 0) { csel.return <- csel.out } else { csel.return <- rbind(csel.mat, csel.out) } count.runs <- count.runs + 1 print(count.runs) if (count.runs < max.runs) { csel.repeat(eset, m, crange, max.runs, csel.return, count.runs) } else { return(csel.return) } } dmin.repeat <- function(eset, m, crange, max.runs, dmin.mat = vector(), count.runs = 0) { dmin.out <- Dmin(eset, m = m, crange = crange, repeats = 5, visu = FALSE) if (count.runs == 0) { dmin.return <- dmin.out } else { dmin.return <- rbind(dmin.mat, dmin.out) } count.runs <- count.runs + 1 if (count.runs < max.runs) { dmin.repeat(eset, m, crange, max.runs, dmin.return, count.runs) } else { return(dmin.return) } } match.exact <- mkchain(map_chr(paste %<<<% "^" %<<% c("$", sep = "")), paste(collapse = "|")) intensities.mean <- readRDS.gz("../dtw/save/intensities.means.rda") intensities.tgdox <- intensities.mean$Tg.DOX tgdox.betr.genes <- read.xlsx("../betr/tgdox.out.xlsx") %>% select(Symbol) tgdox.timecourse.genes <- read.xlsx("../timecourse/tgdox.out.xlsx") %>% select(Symbol) longnet.tgdox <- readRDS.gz("../longnet/save/ica.tgdox.rda") ica.tgdox <- readRDS.gz("../longnet/save/ica.tgdox.rda") tgdox.genes <- c(unlist(tgdox.betr.genes), unlist(tgdox.timecourse.genes)) %>% unique %>% match.exact #tgdox.genes <- match.exact(ica.tgdox) tgdox.cluster <- intensities.tgdox[grepl(tgdox.genes, rownames(intensities.tgdox)),] tgdox.cluster <- intensities.tgdox[match(longnet.tgdox, rownames(intensities.tgdox)),] tgdox.eset <- ExpressionSet(assayData = as.matrix(tgdox.cluster)) %>% standardise m.estimate <- mestimate(tgdox.eset) csel.runs <- csel.repeat(tgdox.eset, m = m.estimate, crange = 4:20, max.runs = 5) csel.ratio <- (4:20) - colMeans(csel.runs) dmin.runs <- dmin.repeat(tgdox.eset, m = m.estimate, crange = seq(4, 40, 4), max.runs = 5) seed.mfuzz <- function(eset, c.num, m, mfuzz.list = list(), iter.count = 0) { if (iter.count < 250) { mfuzz.new <- mfuzz(eset, c = c.num, m = m) iter.count <- iter.count + 1 print(iter.count) mfuzz.add <- mfuzz.new$membership colnames(mfuzz.add) <- paste("X", 1:c.num, sep = "") mfuzz.list[[iter.count]] <- mfuzz.add seed.mfuzz(eset = eset, c.num = c.num, m = m, mfuzz.list = mfuzz.list, iter.count = iter.count) } else { return(mfuzz.list) } } cluster.tgdox7 <- seed.mfuzz(eset = tgdox.eset, c.num = 4, m = m.estimate) median.tgdox7 <- melt(cluster.tgdox7) %>% dcast(Var1 ~ Var2, median) cluster.tgdox13 <- seed.mfuzz(eset = tgdox.eset, c.num = 13, m = m.estimate) median.tgdox13 <- melt(cluster.tgdox13) %>% dcast(Var1 ~ Var2, median) cluster.tgdox14 <- seed.mfuzz(eset = tgdox.eset, c.num = 14, m = m.estimate) median.tgdox14 <- melt(cluster.tgdox14) %>% dcast(Var1 ~ Var2, median) cluster.tgdox <- mfuzz(tgdox.eset, c = 7, m = m.estimate) mfuzz.plot(tgdox.eset, cl = cluster.tgdox, mfrow = c(4,4), time.labels = 1:4) #cluster.filter <- (cluster.patient$membership > 0.4) %>% apply(1, any) #cluster.filtered <- cluster.patient$membership[cluster.filter,] #patient.members <- apply(cluster.patient$membership, 1, which.max) patient.df <- data.frame(Symbol = names(cluster.patient$cluster), Cluster = cluster.patient$cluster) write.xlsx(patient.df, "./patient.cmeans.xlsx") partcoef.tgdox <- partcoef(tgdox.eset) permut.timeseries <- function()
23e9d58f3ada650c4cc1d8e9f3b3b1b73e70850d
b6e7d568d3c01b5fb2ee63a8c4594efc995e37c3
/R/msrep.R
e9da95c6fef6ad34a9feb034ebb1472ec6f2917c
[]
no_license
cran/longit
4b87d6851d600a900f59b5e4ebd09f1d1e725a7e
2aa442df666057b016cc191b5da3e182dda3eacc
refs/heads/master
2023-04-08T05:09:29.130163
2021-04-15T07:00:05
2021-04-15T07:00:05
358,312,090
0
0
null
null
null
null
UTF-8
R
false
false
580
r
msrep.R
#' @title longitudinal data #' #' @description Longitudinal observation on single variable at different timepoints. Observations arranged in a column as the patient with corresponding column of ID. #' @usage data(msrep) #' @format A \code{tibble} with 7 columns which are : #' \describe{ #' \item{Subject}{Patient ID} #' \item{Gender}{Categorical numeric variable, 1 if Males and 0 if female} #' \item{Age}{Time or age at which observations were taken from every subjects} #' \item{x1,...,x4}{Columns stating number of observations at age 18,10,12 and 14}} #' "msrep"
9c281d9e44c2e9f52f9bd5dc3b10f26c7be5d005
f2bcc38a5ece9b14a3d8b68c5d4a09edff06314d
/man/Seq.Rd
c42e2c811247151c7ec36bbc3170080006a3d33d
[ "Apache-2.0" ]
permissive
charlieccarey/monarchr.biolink
8eb618c9c61091ac3371e7d67636520a07d3db6b
5b488a06cedcafc9df44368e2d665555bc5cd53d
refs/heads/master
2020-03-09T08:40:56.748770
2018-04-11T04:33:54
2018-04-11T04:33:54
128,694,973
0
0
null
null
null
null
UTF-8
R
false
true
681
rd
Seq.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Seq.r \docType{data} \name{Seq} \alias{Seq} \title{Seq Class} \format{An object of class \code{R6ClassGenerator} of length 24.} \usage{ Seq } \description{ Seq Class } \section{Fields}{ \describe{ \item{\code{id}}{} \item{\code{label}}{} \item{\code{categories}}{} \item{\code{types}}{} \item{\code{description}}{} \item{\code{consider}}{} \item{\code{deprecated}}{} \item{\code{replaced_by}}{} \item{\code{synonyms}}{} \item{\code{xrefs}}{} \item{\code{taxon}}{} \item{\code{md5checksum}}{} \item{\code{residues}}{} \item{\code{alphabet}}{} \item{\code{seqlen}}{} }} \keyword{datasets}
b5de92a0fa9796eadd12ad1f26e2e2eb30b67176
72341bedc0e8951ced5f1afa53239d7ee02b03b1
/split.R
e0a3517e2d629fc9744ecdcb3fd830846ef0c7c7
[]
no_license
vippro169/Load-profile-simulator
e9cba74dc2d9bb4172836fdd697f7bdfbf2e9174
c80aeb38fb67059206955307d9db78b125db874b
refs/heads/master
2021-09-13T11:35:26.326489
2017-11-26T04:51:35
2017-11-26T04:51:35
111,104,055
0
1
null
null
null
null
UTF-8
R
false
false
1,122
r
split.R
setwd('~/Documents/Project 1/household 1/01_plugs_csv/01/06') filename <- list.files(pattern = "*.csv") for(i in 1:length(filename)){ power <- read.csv(filename[i]) time <- seq(ISOdate(2017,11,7), by='sec', length.out = 86399) smr <- data.frame(unclass(summary(power))) preference <- power[,1] preference[preference <= 20] = 0 a <- data.frame(unclass(rle(preference))) #preference <- round(preference$X49.2516/10)*10 listOfSignature <- split(a,cumsum(a$lengths>100), cumsum(a$values==0)) for(l in 1:length(listOfSignature)){ listOfSignature[[l]]$lengths[listOfSignature[[l]]$values == 0 && listOfSignature[[l]]$lengths > 100] = 1 } outpath=paste('~/Documents/Project 1/household 1/01_plugs_csv/Output/app_6',sep='') setwd(outpath) for(j in 1:length(listOfSignature)){ tmp <- inverse.rle(listOfSignature[[j]]) savename <- paste('6__',filename[i],'__filenum_',j,'.csv', sep='') write.csv(tmp, file = savename) } setwd('~/Documents/Project 1/household 1/01_plugs_csv/01/06') # tmp <- inverse.rle(listOfSignature[[1]]) # plot(tmp, type='l', ylim=c(0,600)) }
65b345974ac63d9d915815a535be763133073b8a
abedec3e252d97868aea5b3385a77313ae26a92f
/baby_names02.R
6128e229d267fd910e6d688ec033a35353f83f13
[]
no_license
dk81/R_projects
b4129a88ab48060727cde75810d69baa2e50e5f3
f55ba52f4864593bc3970bc9de22f9b96f02ec43
refs/heads/master
2022-03-13T23:45:35.582464
2022-03-06T16:33:59
2022-03-06T16:33:59
140,731,173
5
0
null
null
null
null
UTF-8
R
false
false
6,831
r
baby_names02.R
# Sideways Bar Graph # Analyzing Baby Names Part 2: # A Bar Graph Approach library(babynames) # Baby Names dataset: library(ggplot2) # Data visualization library(data.table) # For data wrangling and manipulation # Save the babynames data into baby_data: baby_data <- data.table(babynames) # Preview the data: head(baby_data); tail(baby_data) # Structure of data: str(baby_data) # Change column names: colnames(baby_data) <- c("Year", "Sex", "Name", "Count", "Proportion") ### -------------------------------------- ## Finding The Top 20 Baby Names: # Sort names from most popular to least popular (adds duplicates too): sorted_names <- baby_data[ , .(Name.Count = sum(Count)), by = Name] sorted_names <- sorted_names[order(-Name.Count)] # Preview: head(sorted_names, n = 20) top_twenty_babynames <- sorted_names[1:20, ] # Preview: top_twenty_babynames # Ggplot Bar Graph: ggplot(top_twenty_babynames, aes(x = Name, y = Name.Count)) + geom_bar(stat = "identity") + labs(x = "Name \n", y = "\n Count \n", title = "Top 20 Baby Names") + theme(plot.title = element_text(hjust = 0.5), axis.title.x = element_text(face="bold", colour="#FF7A33", size = 12, vjust = 1), axis.title.y = element_text(face="bold", colour="#FF7A33", size = 12), axis.text.x = element_text(angle = 90, vjust = 0.1, hjust = 0.1), legend.title = element_text(face="bold", size = 10)) # Ggplot Sideways Bar Graph: ggplot(top_twenty_babynames, aes(x = Name, y = Name.Count)) + geom_bar(stat = "identity") + coord_flip() + labs(x = "Name \n", y = "\n Count \n", title = "Top 20 Baby Names") + theme(plot.title = element_text(hjust = 0.5), axis.title.x = element_text(face="bold", colour="#FF7A33", size = 12, vjust = 1), axis.title.y = element_text(face="bold", colour="#FF7A33", size = 12), axis.text.x = element_text(angle = 90, vjust = 0.1, hjust = 0.1), legend.title = element_text(face="bold", size = 10)) # Ggplot Sideways Bar Graph (Scaled): ggplot(top_twenty_babynames, aes(x = Name, y = Name.Count/1000000)) + geom_bar(stat = "identity") + coord_flip() + scale_y_continuous(breaks=seq(0, 6, 1)) + labs(x = "Name \n", y = "\n Count (Millions) \n", title = "Top 20 Baby Names") + theme(plot.title = element_text(hjust = 0.5), axis.title.x = element_text(face="bold", colour="#FF7A33", size = 12, vjust = 1), axis.title.y = element_text(face="bold", colour="#FF7A33", size = 12), axis.text.x = element_text(vjust = 0.1, hjust = 0.1), legend.title = element_text(face="bold", size = 10)) # Getting The Sorted Bar Graph In ggplot2: # We have the sorted top 20 baby names but ggplot would not recognize this # ordering. # To have ggplot recognize this ordering, we have these 20 names # as factors in the order of the most popular female # name to the 20th most popular female name # http://rstudio-pubs-static.s3.amazonaws.com/7433_4537ea5073dc4162950abb715f513469.html top_twenty_babynames$Name <- factor(top_twenty_babynames$Name, levels = top_twenty_babynames$Name[order(top_twenty_babynames$Name.Count)]) # Ggplot Sideways Bar Graph (Fixed & Sorted): ggplot(top_twenty_babynames, aes(x = Name, y = Name.Count/1000000)) + geom_bar(stat = "identity") + coord_flip() + scale_y_continuous(breaks=seq(0, 6, 1)) + geom_text(aes(label = round(Name.Count/1000000, 3)), hjust = 1.2, colour = "white", fontface = "bold") + labs(x = "Name \n", y = "\n Count (Millions) \n", title = "The Twenty Most Popular Baby Names") + theme(plot.title = element_text(hjust = 0.5), axis.title.x = element_text(face="bold", colour="#FF7A33", size = 12, vjust = 1), axis.title.y = element_text(face="bold", colour="#FF7A33", size = 12), axis.text.x = element_text(vjust = 0.1, hjust = 0.1), legend.title = element_text(face="bold", size = 10)) #------------------------- ### Male Baby Names: male_babynames <- baby_data[Sex == "M" , .(Name.Count = sum(Count)), by = Name][order(-Name.Count)] head(male_babynames , n = 20) # Order male baby names in descending order by Count: # Reference: http://www.statmethods.net/management/sorting.html male_babynames <- male_babynames[order(-Name.Count), ] head(male_babynames, n = 20) # Eliminate weird row numbers: #rownames(male_babynames) <- NULL # Top 20 Male Baby Names: toptwenty_m <- male_babynames[1:20, ] toptwenty_m toptwenty_m$Name <- factor(toptwenty_m$Name, levels = toptwenty_m$Name[order(toptwenty_m$Name.Count)]) # Ggplot Sideways Bar Graph (Fixed & Sorted): ggplot(toptwenty_m, aes(x = Name, y = Name.Count/1000000)) + geom_bar(stat = "identity") + coord_flip() + scale_y_continuous(breaks=seq(0, 6, 1)) + geom_text(aes(label = round(Name.Count/1000000, 3)), hjust = 1.2, colour = "white", fontface = "bold") + labs(x = "Name \n", y = "\n Count (Millions) \n", title = "The Twenty Most Popular \n Male Baby Names \n") + theme(plot.title = element_text(hjust = 0.5), axis.title.x = element_text(face="bold", colour="#FF7A33", size = 12, vjust = 1), axis.title.y = element_text(face="bold", colour="#FF7A33", size = 12), axis.text.x = element_text(vjust = 0.1, hjust = 0.1), legend.title = element_text(face="bold", size = 10)) #----------------------------------------- # Getting the Top 20 Female Baby Names: female_babynames <- baby_data[Sex == "F" , .(Name.Count = sum(Count)), by = Name][order(-Name.Count)] head(female_babynames , n = 20) # Order female baby names in descending order by Count: # Reference: http://www.statmethods.net/management/sorting.html female_babynames <- female_babynames[order(-Name.Count), ] head(female_babynames, n = 20) # Eliminate weird row numbers: #rownames(male_babynames) <- NULL # Top 20 Female Baby Names: toptwenty_f <- female_babynames[1:20, ] toptwenty_f toptwenty_f$Name <- factor(toptwenty_f$Name, levels = toptwenty_f$Name[order(toptwenty_f$Name.Count)]) # Ggplot Sideways Bar Graph (Fixed & Sorted): ggplot(toptwenty_f, aes(x = Name, y = Name.Count/1000000)) + geom_bar(stat = "identity") + coord_flip() + scale_y_continuous(breaks=seq(0, 6, 1)) + geom_text(aes(label = round(Name.Count/1000000, 3)), hjust = 1.2, colour = "white", fontface = "bold") + labs(x = "Name \n", y = "\n Count (Millions) \n", title = "The Twenty Most Popular \n Female Baby Names") + theme(plot.title = element_text(hjust = 0.5), axis.title.x = element_text(face="bold", colour="#FF7A33", size = 12, vjust = 1), axis.title.y = element_text(face="bold", colour="#FF7A33", size = 12), axis.text.x = element_text(vjust = 0.1, hjust = 0.1), legend.title = element_text(face="bold", size = 10))
da428483de4c57b4a9763d492de1b4cd5154eb9c
074d650201fbf5c15482e7a733e5f2a0e6330dcd
/NetLogo R Analyses/Spacial Statistics.R
160fd885d986aa5e0bf9c4be03c3bcd780d18539
[]
no_license
smwoodman/Bee-Lab-Thesis
b2944b0bbda8fa05c1ba1abb616577695213a3c3
87c4219bcc68f2c4ac1859715142aaed5654dc4f
refs/heads/master
2023-05-01T21:21:08.467938
2021-05-21T00:09:20
2021-05-21T00:09:20
50,375,952
0
1
null
null
null
null
UTF-8
R
false
false
3,117
r
Spacial Statistics.R
# Sam Woodman # Analysis of spacial statistic R # General, Desne, and Sparse Specific Testing library(dplyr) setwd("~/Google Drive/Semester 8/Thesis/NetLogo+R GitHub/BehaviorSpace Data/R Value/") ### General Testing g.data <- read.csv("Bees R extra_sparse testing1-table.csv", header = TRUE, skip = 6) ## Filter data by dense and sparse data.e.sparse <- filter(g.data, g.data$resource_density == "\"extra_sparse\"") data.e.sparse.r <- data.e.sparse$R data.e.sparse$grp <- (floor((data.e.sparse$X.run.number.-1) / 7)) + 1 data.e.sparse <- data.e.sparse %>% filter(c1_mult >= c2_mult) ## Divide data into groups .03 away from: R = 0.4, 0.6, 0.8, 1.0 # Extra-sparse data.e.sparse.4 <- data.e.sparse %>% filter(abs(R - 0.4) <= 0.07) data.e.sparse.6 <- data.e.sparse %>% filter(abs(R - 0.6) <= 0.03) table(data.e.sparse.6$grp) temp.6 <- which.max(table(data.e.sparse.6$grp)) es.idx.6 <- (7 * as.numeric(names(temp.6))) data.e.sparse.8 <- data.e.sparse %>% filter(abs(R - 0.8) <= 0.03) table(data.e.sparse.8$grp) temp.8 <- which.max(table(data.e.sparse.8$grp)) es.idx.8 <- (7 * as.numeric(names(temp.8))) ### Dense Testing d.data.all <- read.csv("Bees R dense testing-table.csv", header = TRUE, skip = 6)[-c(6,7,9)] d.data.all$grp <- (floor((d.data.all$X.run.number.-1) / 20)) + 1 d.data <- d.data.all %>% filter(c1_mult > c2_mult) ## Divide data into groups d.num away from: R = 0.4, 0.6, 0.8 d.num <- 0.03 d.data.4 <- d.data %>% filter(abs(R - 0.4) <= d.num) temp.4 <- which.max(table(d.data.4$grp)) table(d.data.4$grp) d.idx.4 <- (20 * as.numeric(names(temp.4))) d.data.all[d.idx.4,] # Best sequence is d.data.all[3941:3960,] d.data.6 <- d.data %>% filter(abs(R - 0.6) <= d.num) temp.6 <- which.max(table(d.data.6$grp)) table(d.data.6$grp) d.idx.6 <- 20 * as.numeric(names(temp.6)) d.data.all[d.idx.6,] # Best sequence is d.data.all[2221:2240,] d.data.8 <- d.data %>% filter(abs(R - 0.8) <= d.num) temp.8 <- which.max(table(d.data.8$grp)) table(d.data.8$grp) d.idx.8 <- 20 * as.numeric(names(temp.8)) d.data.all[d.idx.8,] # Best sequence is d.data.all[821:840,] ### Sparse Testing #s.data.all <- read.csv("Bees R sparse testing_10rep-table.csv", header = TRUE, skip = 6)[-c(6,7,9)] #s.data.all <- read.csv("Bees R sparse testing_10rep_detailed-table.csv", header = TRUE, skip = 6) s.data.all <- read.csv("Bees R sparse testing_1500_2-table.csv", header = TRUE, skip = 6) s.data.all$grp <- (floor((s.data.all$X.run.number.-1) / 4)) + 1 s.data <- s.data.all %>% filter(c1_mult > c2_mult) s.num <- 0.03 ## Divide data into groups s.num away from: R = 0.4, 0.6, 0.8 s.data.4 <- s.data %>% filter(abs(R - 0.4) <= s.num) temp.4 <- which.max(table(s.data.4$grp)) table(s.data.4$grp) s.idx.4 <- (4 * as.numeric(names(temp.4))) s.data.all[s.idx.4,] s.data.6 <- s.data %>% filter(abs(R - 0.6) <= s.num) temp.6 <- which.max(table(s.data.6$grp)) table(s.data.6$grp) s.idx.6 <- 4 * as.numeric(names(temp.6)) s.data.all[s.idx.6,] s.data.8 <- s.data %>% filter(abs(R - 0.8) <= s.num) temp.8 <- which.max(table(s.data.8$grp)) table(s.data.8$grp) s.idx.8 <- 4 * as.numeric(names(temp.8)) s.data.all[s.idx.8,]
47426d3f488d8a71d89632133776d65fab14ecc2
63ce3e48f2217972353de20d58bf2a56d58a31b0
/R/some.R
54c8ecf46ed1846ff16b6441974e253ae0bcaed1
[]
no_license
cran/car
6c8c284a58be9798daa0407f65cd5dd1fc808d34
d67a2f5ed4013c8766e8d3e827dcaf6aaaf7f0fa
refs/heads/master
2023-04-06T03:29:23.872258
2023-03-30T09:40:02
2023-03-30T09:40:02
17,694,945
8
20
null
2022-06-06T07:18:20
2014-03-13T04:11:37
R
UTF-8
R
false
false
776
r
some.R
# adapted from head() and tail() # 3/10/2017: S. Weisberg modified to add an argument 'cols' # cols = num will display only the first num cols some <- function(x, ...) UseMethod("some") some.default <- function(x, n=10, ...){ len <- length(x) ans <- x[sort(sample(len, min(n, len)))] if (length(dim(x)) == 1) array(ans, n, list(names(ans))) else ans } some.matrix <- function(x, n=10, cols=NULL, ...){ nr <- nrow(x) nc <- ncol(x) cols <- if(is.null(cols)) 1:nc else cols x[sort(sample(nr, min(n, nr))), cols, drop = FALSE] } some.data.frame <- function(x, n=10, cols=NULL, ...){ nr <- nrow(x) nc <- ncol(x) cols <- if(is.null(cols)) 1:nc else cols x[sort(sample(nr, min(n, nr))), cols, drop=FALSE] }
dc56a85d7d36a36a3e0f32f4da2f80b6b2d23301
55a2bdd215a66d17bf5e170019cb8de960de760d
/mymain.R
488bff2c1ad9a98eea927780d9dbec93588202ba
[]
no_license
yvonnechanlove97/Movie-Review
8569f102f690a5f5ed03efa4354b3d8ee350ef91
89c3568044b903dea7679139adff0b54b71716aa
refs/heads/master
2020-12-13T12:44:03.257227
2020-02-18T19:52:46
2020-02-18T19:52:46
234,420,103
0
0
null
null
null
null
UTF-8
R
false
false
3,870
r
mymain.R
rm(list=ls()) library(text2vec) library(magrittr) library(glmnet) #get data all = read.table("data.tsv",stringsAsFactors = F,header = T) all$review = gsub('<.*?>', ' ', all$review) splits = read.table("splits.csv", header = T) s = 3 # Here we get the 3rd training/test split. myvocab=as.matrix(read.table("myVocab.txt")) train = all[-which(all$new_id%in%splits[,s]),] test = all[which(all$new_id%in%splits[,s]),] #build the vocabulary prep_fun = tolower tok_fun = word_tokenizer train_tokens = train$review %>% prep_fun %>% tok_fun it_train = itoken(train_tokens, ids = train$new_id, progressbar = FALSE) it_test = test$review %>% prep_fun %>% tok_fun %>% itoken(ids = test$new_id, progressbar = FALSE) stop_words2 = c('a','about', 'above','after','again','against','ain','all','am','an','and','any', 'are','aren',"aren't",'as','at','be','because','been','before', 'being','below','between','both','but','by','can','couldn',"couldn't", 'd','did','didn',"didn't",'do','does','doesn',"doesn't", 'doing','don',"don't",'down','during','each','few','for','from', 'further','had','hadn',"hadn't",'has','hasn',"hasn't", 'have','haven',"haven't",'having','he','her','here','hers', 'herself','him','himself','his','how','i','if','in','into','is', 'isn',"isn't",'it',"it's",'its','itself','just','ll','m','ma', 'me','mightn',"mightn't",'more','most','mustn',"mustn't", 'my','myself','needn',"needn't",'no','nor','not','now', 'o','of','off','on','once','only','or','other','our', 'ours','ourselves','out','over','own','re','s', 'same','shan',"shan't",'she',"she's", 'should',"should've",'shouldn',"shouldn't",'so','some', 'such','t','than','that',"that'll",'the','their', 'theirs','them','themselves','then','there','these', 'they','this','those','through','to','too','under', 'until','up','ve','very','was','wasn',"wasn't",'we','were', 'weren',"weren't",'what','when','where','which', 'while','who','whom','why','will','with','won', "won't",'wouldn',"wouldn't",'y','you',"you'd","you'll", "you're","you've",'your','yours','yourself','yourselves' ) vocab=create_vocabulary(it_train,ngram = c(1L,4L),stopwords = stop_words2) #clean train vocab pruned_vocab = prune_vocabulary(vocab, term_count_min = 5, doc_proportion_max = 0.5, doc_proportion_min = 0.001) vectorizer = vocab_vectorizer(pruned_vocab) dtm_train = create_dtm(it_train, vectorizer) dtm_test = create_dtm(it_test, vectorizer) train_x=dtm_train[,which(colnames(dtm_train)%in%myvocab)] test_x=dtm_test[,which(colnames(dtm_test)%in%myvocab)] #ridge NFOLDS = 10 mycv = cv.glmnet(x=train_x, y=train$sentiment, family='binomial',type.measure = "auc", nfolds = NFOLDS, alpha=0) myfit = glmnet(x=train_x, y=train$sentiment, lambda = mycv$lambda.min, family='binomial', alpha=0) logit_pred = predict(myfit, test_x, type = "response") glmnet:::auc(test$sentiment, logit_pred) write.table(result,"mysubmission.txt",row.names=FALSE, col.names = c('new_id','prob'), sep=", ") #result=cbind(test$new_id,logit_pred) #write.table(result,"Result_3.txt",row.names=FALSE, col.names = c('new_id','prob'), sep=", ") #final_vocab2=words[id] #write.table(final_vocab2,"myVocab1.txt",row.names=FALSE, col.names=FALSE,sep=", ") #three #3 0.9609737 #2 0.9635941 #1 0.9643016
87a7b183c2f42c7f07258dd02b328c7415a690e6
2e7fcffe2b532125bdc6662db16363ee36696df8
/RepRes_Peer_Assessment_1.r
7802225a7cdb113fd4a49c628e7ddecfb0bfde18
[]
no_license
megerex/RepData_PeerAssessment1
802ef20c7c64d8a32821cbcb7dea9f1c94cbf5e7
5ecb62b522354e694a8c24ac6702ebbbf6edba5a
refs/heads/master
2020-05-29T11:55:16.073065
2015-05-14T13:59:49
2015-05-14T13:59:49
35,497,221
0
0
null
2015-05-12T15:43:04
2015-05-12T15:43:04
null
UTF-8
R
false
false
1,521
r
RepRes_Peer_Assessment_1.r
my.data <- read.csv(file="activity.csv", header=TRUE, sep=",", na.string="NA") my.data$date <- as.Date(my.data$date) my.data.aveSteps <- aggregate(formula = steps ~ date, data = my.data, FUN = mean) require(ggplot2) ggplot(data=my.data.aveSteps, aes(x=date, y=steps)) + geom_histogram(stat="identity", fill="lightblue", colour="black") my.data.aveIntervalSteps <- aggregate(formula = steps ~ interval, data = my.data, FUN = mean) my.data.maxIntervalSteps <- my.data.aveIntervalSteps[which.max(my.data.aveIntervalSteps$steps),] DailySteps.mean <- mean(my.data.aveSteps$steps) DailySteps.median <- median(my.data.aveSteps$steps) my.data.sansNA <- my.data for (index in 1:nrow(my.data.sansNA)){ if(is.na(my.data.sansNA$steps[index])){ my.data.sansNA$steps[index]<- my.data.aveIntervalSteps$steps[my.data.aveIntervalSteps$interval == my.data.sansNA$interval[index]] } } is.weekday <- function(date) { day.test <- weekdays(date) if (day.test %in% c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")) return("weekday") else if (day.test %in% c("Saturday", "Sunday")) return("weekend") else stop("invalid date") } my.data.sansNA$wday <- sapply(my.data.sansNA$date, FUN=is.weekday) my.data.wday.aveIntervalSteps <- aggregate(formula = steps ~ interval + wday, data = my.data.sansNA, FUN = mean) ggplot(data=my.data.wday.aveIntervalSteps, aes(x=interval, y=steps)) + facet_grid(wday ~ . ) + geom_line(colour="red", size=0.5) + xlab("5-min interval") + ylab("average steps taken")
e24aeebc182541bed949e7761d51b1a101b05a44
ca26b58313dc16a137f31f45e39aefe0a1a8f1ba
/rprog-data-ProgAssignment3-data/rankhospital.R
1f121f24ff966b30b20401dd6dad4ed95fa50850
[]
no_license
ChuckChekuri/datasciencecoursera
06c4a95ef37c4fde39ab55dc98de615be98f56cf
8e81a42c3a1a43372390aa44fdb35bafa21c08fd
refs/heads/master
2020-05-23T10:06:24.413977
2017-04-08T14:18:33
2017-04-08T14:19:12
80,387,047
0
0
null
null
null
null
UTF-8
R
false
false
1,040
r
rankhospital.R
rankhospital = function(state, outcome, rank) { data <- read.csv("outcome-of-care-measures.csv", colClasses = "character") states <- unique(data$State) if (!state %in% states) stop("invalid state") outcomes <- c("heart attack", "heart failure", "pneumonia") if (!outcome %in% outcomes ) stop("invalid outcome") # Hopital.Name - col 2 # get the column number based on passed in outcome # columns for the mortality rates in the same order as outcomes m_cols <- c(11,17,23) outcol <-m_cols[which(outcomes == outcome)] # subset the data by state and select hospital and metric df <- data[data$State == state, c(2,outcol)] # convert the character to number df[,2] <- suppressWarnings(as.numeric(df[,2])) # remove the NAs df <- na.omit(df) # order the hospitals by mortality rate df <- df[order(df[,2],df[,1]),] # return Hospital Name if (rank == "best") rank <- 1 if (rank == "worst") rank <- nrow(df) if (suppressWarnings(is.na(as.numeric(rank)))) stop("invalid rank") if (rank > nrow(df) ) NA else df[rank,1] }
006fe86376259fba85bd2d7d9e6a2dc9db7fa9a3
cd0e51bf6d007e8f540f22833d8e6ce2d4bba92f
/man/poisson.process.Rd
1652fd76a39d1d55edb379c39732072d06c292a2
[ "MIT" ]
permissive
David-Statistics/Clancy-Functions
07daef7b20f2064e25f42bf987bba6243855cd27
2921e42a14f1cd39c5208d5772ebdbb915bb6d03
refs/heads/master
2021-05-04T06:46:31.702577
2016-11-30T19:21:19
2016-11-30T19:21:19
70,514,224
0
0
null
null
null
null
UTF-8
R
false
true
819
rd
poisson.process.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/poisson.process.r \name{poisson.process} \alias{poisson.process} \title{Interarrival times and arrival times of a poisson process} \usage{ poisson.process(rate = 1, events = NULL, time.running = NULL) } \arguments{ \item{rate}{The rate/intensity of the arrivals in the poisson process} \item{events}{The number of events in the process (or \code{NULL} if defining the cut off point by the time)} \item{time.running}{The amount of time for the process to run (or \code{NULL} if defining the cut off by the number of events)} } \value{ An numeric matrix with 2 columns. The first column contains the interarrival times and the second contains the arrival times. } \description{ Interarrival times and arrival times of a poisson process }
fdbc7be148ef51f37de157586c2a330f54ba5f31
03d20ec52ea429d2bffdefa849044ab6d0ad7481
/03_stop_frisk/scripts/stop_and_frisk.R
4e000dd92f4633cb09c0abbd2cd7809b2f2d1f92
[]
no_license
GWarrenn/dc_data
3f679b28aa02f1cec7b9e887d66087d44ed40d7c
15b358d77210644dcdd908ef05d6e95930fbf62e
refs/heads/master
2021-11-17T07:36:55.337352
2021-09-30T21:44:56
2021-09-30T21:44:56
98,127,130
0
0
null
null
null
null
UTF-8
R
false
false
58,317
r
stop_and_frisk.R
## Author: August Warren ## Description: Analysis of DC Stop and Frisk Data ## Date: 9/6/2018 ## Status: Published ## Specs: R version 3.3.2 (2016-10-31) ################################### ## ## Load packages ## ################################### library(ggplot2) library(dplyr) library(gdata) library(rgdal) library(sp) library(rgeos) library(geosphere) library(ggmap) library(reshape2) library(ggthemes) library(zoo) library(ggridges) library(lubridate) library(fuzzyjoin) library(tidyverse) library(tweenr) library(scales) library(stargazer) library(viridis) source("03_stop_frisk/scripts/mygg_animate.r") ################################### ## ## Load Stop and Frisk Data ## Provided by MPD: https://mpdc.dc.gov/publication/stop-and-frisk-data-and-explanatory-notes ## ################################### stop_frisk_1 <- read.xls("data/crime/SF_Field Contact_02202018.xls",sheet = 1) stop_frisk_2017 <- read.xls("data/crime/SF_Field Contact_CY2017.xls",sheet = 1) stop_frisk_1 <- rbind(stop_frisk_1,stop_frisk_2017) stop_frisk_1$REASON.FOR.STOP <- "N/A" stop_frisk_1$time_of_day <- format(round(strptime(stop_frisk_1$Report_taken_date_EST, "%m/%d/%Y %I:%M %p"), units="hours"), format="%H:%M") stop_frisk_1$day_of_month <- format(strptime(stop_frisk_1$Report_taken_date_EST, "%m/%d/%Y %I:%M %p"), "%d") stop_frisk_1$month <- format(as.Date(stop_frisk_1$Report_taken_date_EST,"%m/%d/%Y"), "%m") stop_frisk_1$year_month <- as.Date(paste0(stop_frisk_1$month,"/","01/",as.numeric(stop_frisk_1$Year),sep=""),"%m/%d/%Y") ## add in 2017 data stop_frisk_2 <- read.xls("data/crime/SF_Field Contact_02202018.xlsx",sheet = 2, quote = "") stop_frisk_2017 <- read.xls("data/crime/SF_Field Contact_CY2017.xls",sheet = 2, quote = "") ## add 2017 data stop_frisk_2 <- rbind(stop_frisk_2,stop_frisk_2017) stop_frisk_2 <- as.data.frame(sapply(stop_frisk_2, function(x) gsub("\"", "", x))) cols <- colnames(stop_frisk_2) for (c in cols) { fixed <- gsub(pattern = "X.|.$", replacement = "", x = c) names(stop_frisk_2)[names(stop_frisk_2)==c] <- fixed } stop_frisk_2 <- stop_frisk_2 %>% rename(Report_taken_date_EST = Report.taken.date, Incident_Type = FIELD.CONTACT.TYPE, Subject_Race = Race, Subject_Sex = Sex, Subject_Ethnicity = Ethnicity, Incident.Location.PSA = PSA, Incident.Location.District = District, Block.Address = Block.address) stop_frisk_2$time_of_day <- format(round(strptime(stop_frisk_2$Report_taken_date_EST, "%Y-%m-%d %H:%M"),units="hours"), "%H:%M") stop_frisk_2$day_of_month <- format(strptime(stop_frisk_2$Report_taken_date_EST, "%Y-%m-%d %H:%M"), "%d") stop_frisk_2$month <- format(as.Date(stop_frisk_2$Report_taken_date_EST,"%Y-%m-%d"), "%m") stop_frisk_2$year_month <- as.Date(paste0(stop_frisk_2$month,"/","01/",as.numeric(as.character(stop_frisk_2$Year)),sep=""),"%m/%d/%Y") stop_frisk_total <- rbind(stop_frisk_1) stop_frisk_total$id <- seq.int(nrow(stop_frisk_total)) ################################### ## ## Matching incident block address in stop & frisk file to DC block data ## in order to obtain incident lattitude and longitude ## h/t to Mahkah Wu for the idea and doing the hard: https://github.com/mahkah/dc_stop_and_frisk ## ################################### stop_frisk_matched <- read.csv(url("https://raw.githubusercontent.com/mahkah/dc_stop_and_frisk/master/transformed_data/SF_Field%20Contact_locations.csv")) stop_frisk_matched <- stop_frisk_matched %>% filter(block_match == "Matched" & cause == "Unknown") %>% rename(Age = subject_age, Subject_Ethnicity = subject_ethnicity, Subject_Gender = subject_gender, Subject_Race = subject_race) stop_frisk_matched$time_of_day <- format(round(strptime(stop_frisk_matched$incident_date, "%Y-%m-%d %H:%M"), units="hours"), format="%H:%M") stop_frisk_matched$day_of_month <- format(strptime(stop_frisk_matched$incident_date, "%Y-%m-%d %H:%M"), "%d") stop_frisk_matched$month <- format(as.Date(stop_frisk_matched$incident_date,"%Y-%m-%d %H:%M"), "%m") stop_frisk_matched$year_month <- as.Date(paste0(as.numeric(stop_frisk_matched$month),"/","01/",as.numeric(stop_frisk_matched$year),sep=""),"%m/%d/%Y") ################################### ## ## Top-level descriptives ## ################################### ## add in non-forcible for analysis stop_frisk_all_stops <- rbind(stop_frisk_1,stop_frisk_2) ## standard funciton to add demos to all forcible, matched lat/long forcible, forcible & non-forcible stops add_demos <- function(data_frame){ data_frame$race_ethn <- ifelse(data_frame$Subject_Ethnicity=='Hispanic Or Latino','Hispanic/Latino', data_frame$Subject_Race) data_frame$race_ethn <- as.character(data_frame$Subject_Race) data_frame$race_ethn[data_frame$Subject_Ethnicity == "Hispanic Or Latino"] <- "Hispanic/Latino" data_frame$juvenile <- ifelse(data_frame$Age == "Juvenile","Juvenile","Adult") data_frame$juvenile[data_frame$Age == "Unknown" | data_frame$Age == ""] <- "Unknown" return(data_frame) } stop_frisk_total <- add_demos(stop_frisk_total) ## all forcible stop & frisks stop_frisk_matched <- add_demos(stop_frisk_matched) ## forcible stops mapped to lat/long stop_frisk_all_stops <- add_demos(stop_frisk_all_stops) ## both forcible & non-forcible stops ## what are the historical patterns of stop and frisk? -- monthly ts stop_frisk_monthly <- stop_frisk_total %>% group_by(year_month) %>% summarise (n = n()) %>% arrange(year_month) %>% mutate(monthly = rollsum(n, k = 12, na.pad = TRUE, align = "right")) monthly_sf <- ggplot(stop_frisk_monthly,aes(x=year_month,y=n,group=1)) + geom_point(size=2) + geom_smooth(method = lm,size=2) + #geom_vline(aes(xintercept = as.numeric(as.Date(dmy("2/1/2015")))), col = "black") + #stat_smooth(aes(x=year_month, y=n), method = lm, formula = y ~ poly(x, 10), se = TRUE,size=2) + theme_fivethirtyeight() + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5)) + ylab('Number of Stop and Frisks') + xlab("Month") + ggtitle("Total Number of Stop and Frisks per Month") + scale_x_date(date_breaks = "6 months", date_labels = "%m/%y") ggsave(plot = monthly_sf, "03_stop_frisk/images/01_monthly_sf.png", w = 10.67, h = 8,type = "cairo-png") ## hourly ts by race percentage stop_frisk_hourly <- stop_frisk_total %>% filter(!is.na(stop_frisk_total$time_of_day)) %>% group_by(time_of_day) %>% summarise (n = n()) %>% mutate(freq=n/sum(n)) stop_frisk_total$hour <- format(round(strptime(stop_frisk_total$Report_taken_date_EST, "%m/%d/%Y %H:%M"),units="hours"), "%H") stop_frisk_total$mins <- format(round(strptime(stop_frisk_total$Report_taken_date_EST, "%m/%d/%Y %H:%M"),units="mins"), "%M") stop_frisk_total$mins_past_midnight <- (as.numeric(stop_frisk_total$hour) * 60) + as.numeric(stop_frisk_total$mins) ggplot(data = filter(stop_frisk_total,race_ethn %in% c("White","Black","Hispanic/Latino")), aes(mins_past_midnight,group=race_ethn,fill=race_ethn)) + geom_density(alpha = 0.5) stop_frisk_hourly$race_ethn <- "Total" stop_frisk_hourly <- stop_frisk_hourly[c("race_ethn", "time_of_day", "n","freq")] stop_frisk_hourly_race <- stop_frisk_total %>% filter(race_ethn %in% c("White","Black","Hispanic/Latino")) %>% group_by(race_ethn,time_of_day) %>% summarise (n = n()) %>% mutate(freq=n/sum(n)) stop_frisk_hourly_comb <- rbind(as.data.frame(stop_frisk_hourly_race),as.data.frame(stop_frisk_hourly)) stop_frisk_hourly_comb$time_of_day <- factor(stop_frisk_hourly_comb$time_of_day,levels=c("07:00","08:00","09:00","10:00","11:00","12:00","13:00", "14:00","15:00","16:00","17:00","18:00","19:00","20:00", "21:00","22:00","23:00","00:00","01:00","02:00","03:00", "04:00","05:00","06:00")) stop_frisk_hourly_comb_plot <- ggplot(stop_frisk_hourly_comb, aes(x=time_of_day, y=freq, color=race_ethn,group=race_ethn)) + geom_line(size=2) + theme_fivethirtyeight() + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5)) + ylab('Percentage of Stop and Frisk Incidents') + xlab("Time of Day") + ggtitle("Total Stop and Frisk Incidents by Time of Day & Race/Ethnicity") + scale_y_continuous(labels = scales::percent) + scale_color_discrete(name="Legend") ggsave(plot = stop_frisk_hourly_comb_plot, "03_stop_frisk/images/02_time_of_day_sf.png", w = 10.67, h = 8,type = "cairo-png") ## percent of juvenile stops by race stop_frisk_total$juvenile <- ifelse(stop_frisk_total$Age == "Juvenile","Juveniles", "Adults") sf_age_race <- stop_frisk_total %>% filter(race_ethn %in% c("White","Black","Hispanic/Latino")) %>% group_by(race_ethn,juvenile,Subject_Sex) %>% summarise(count = n()) %>% mutate(freq=count/sum(count)) sf_age_race$race_ethn <- factor(sf_age_race$race_ethn,levels=c("White","Black","Hispanic/Latino")) sf_race_youths <- ggplot(sf_age_race,aes(x=juvenile,y=freq,fill=juvenile)) + geom_bar(stat="identity") + facet_wrap(~race_ethn) + geom_text(aes(x=juvenile,y=freq,label=percent(round(freq,2))),data=sf_age_race, position=position_dodge(width=0.9), vjust=-0.5,size=5) + theme_fivethirtyeight() + scale_y_continuous(labels=scales::percent,limits=c(0,1)) + theme(axis.title = element_text(), plot.title = element_text(hjust = 0.5), axis.text = element_text(size=12), strip.text = element_text(size=16)) + labs(title = "Proportion of Juvenile vs. Adult Stops by Race/Ethnicity", x = '', y ="", fill="Legend") ggsave(plot = sf_race_youths, "03_stop_frisk/images/sf_race_youths.png", w = 10.67, h = 8,type = "cairo-png") ## average age of stop and frisk by race sf_ages <- stop_frisk_total %>% filter(Age != "Juvenile") sf_ages$Age <- as.double(as.character(sf_ages$Age)) sf_age_stats <- sf_ages %>% filter(!is.na(sf_ages$Age)) %>% group_by(race_ethn) %>% summarise(mean = mean(Age), median = median(Age), min = min(Age), max = max(Age), iqr = IQR(Age)) white <- sf_ages %>% filter(race_ethn=="White") ##23 black <- sf_ages %>% filter(race_ethn=="Black") #18 hisp <- sf_ages %>% filter(race_ethn=="Hispanic/Latino") #18 sf_age_dist$race_ethn <- factor(sf_age_dist$race_ethn,levels=c("White","Black","Hispanic/Latino")) sf_age_dist <- ggplot(filter(sf_ages, race_ethn %in% c("White","Black","Hispanic/Latino")), aes(x = Age, y = race_ethn)) + geom_density_ridges() + theme_fivethirtyeight() + theme(axis.title = element_text(), plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5)) + labs(x="Age", y="", title="Age of Stop and Frisk Incidents by Race/Ethnicity among Adults") ggsave(plot = sf_age_dist, "03_stop_frisk/images/04_sf_age_dist.png", w = 10.67, h = 8,type = "cairo-png") ## what are the most cited reasons for non-forcible stops? stop_frisk_all_stops$reason <- ifelse(grepl("Suspicious",stop_frisk_all_stops$REASON.FOR.STOP), "Suspicious Vehicles/Persons/Activities",stop_frisk_all_stops$REASON.FOR.STOP) reasons_for_stop <- stop_frisk_all_stops %>% filter(!reason %in% c("N/A") & race_ethn %in% c("White","Black","Hispanic/Latino","Asian")) %>% group_by(race_ethn,reason) %>% summarise(n = n()) %>% mutate(freq = n/sum(n)) reasons_for_stop <- reasons_for_stop %>% filter(race_ethn %in% c("White", "Black", "Hispanic/Latino")) reasons_for_stop$race_ethn <- factor(reasons_for_stop$race_ethn, levels = c("White", "Black", "Hispanic/Latino")) reason_for_stop_plot <- ggplot(reasons_for_stop,aes(x=reason, y=freq)) + geom_bar(stat = "identity") + geom_text(aes(label=percent(round(freq,2))), hjust=-.1, position=position_dodge(.5)) + coord_flip() + theme_fivethirtyeight() + facet_wrap(~race_ethn) + scale_y_continuous(labels=scales::percent,limits=c(0,.5)) + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5)) + labs(title = "Reason for Field Contact Report by Race", subtitle = "among all non-forcible stops", x = 'Reason For Stop', y ="") ggsave(plot = reason_for_stop_plot, "03_stop_frisk/images/reason_for_stop.png", w = 10.67, h = 8,type = "cairo-png") ## race breakdown by forcible/non-forcible stops stop_frisk_all_stops$contact_type <- ifelse(stop_frisk_all_stops$REASON.FOR.STOP=="N/A","Forcible","Non-forcible") race_contact <- stop_frisk_all_stops %>% group_by(contact_type,race_ethn) %>% summarise(n=n()) %>% mutate(freq=n/sum(n)) %>% filter(race_ethn %in% c("White","Black","Hispanic/Latino")) race_contact_plot <- ggplot(race_contact,aes(x=race_ethn, y=freq,fill=race_ethn)) + geom_bar(stat="identity") + geom_text(aes(label=percent(freq)), vjust=-.5, position=position_dodge(.5), size=5) + theme_fivethirtyeight() + facet_grid(~contact_type) + scale_y_continuous(labels=scales::percent,limits=c(0,1)) + scale_x_discrete(limits=c("White","Black","Hispanic/Latino")) + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5)) + xlab("") + ylab("") + ggtitle("Subject Race/Ethnicity by Contact Type")+ scale_fill_discrete(name="Legend",limits=c("White","Black","Hispanic/Latino")) ggsave(plot = race_contact_plot, "03_stop_frisk/images/race_contact.png", w = 10.67, h = 8,type = "cairo-png") gender_race <- stop_frisk_total %>% filter(race_ethn %in% c("White","Black","Hispanic/Latino")) %>% group_by(race_ethn,Subject_Sex) %>% summarise(n=n()) %>% mutate(freq=n/sum(n)) gender_race_plot <- ggplot(gender_race,aes(x=Subject_Sex, y=freq,fill=Subject_Sex)) + geom_bar(stat="identity") + geom_text(aes(label=percent(freq)), vjust=-.5, position=position_dodge(.5), size=5) + theme_fivethirtyeight() + facet_wrap( ~ race_ethn) + scale_y_continuous(labels=scales::percent,limits=c(0,1)) + scale_x_discrete(limits=c("Male","Female")) + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5), strip.text = element_text(size = 12)) + xlab("") + ylab("") + ggtitle("Gender of Stop and Frisks by Race/Ethnicity")+ scale_fill_discrete(name="Legend",limits=c("Male","Female")) ggsave(plot = gender_race_plot, "03_stop_frisk/images/gender_race.png", w = 10.67, h = 8,type = "cairo-png") ## gender/race breakdown by forcible/non-forcible gender_race <- stop_frisk_all_stops %>% filter(race_ethn %in% c("White","Black","Hispanic/Latino")) %>% group_by(race_ethn,contact_type,Subject_Sex) %>% summarise(n=n()) %>% mutate(freq=n/sum(n)) gender_race_plot <- ggplot(gender_race,aes(x=Subject_Sex, y=freq,fill=Subject_Sex)) + geom_bar(stat="identity") + geom_text(aes(label=percent(freq)), vjust=-.5, position=position_dodge(.5), size=5) + theme_fivethirtyeight() + facet_grid(contact_type ~ race_ethn) + scale_y_continuous(labels=scales::percent,limits=c(0,1)) + scale_x_discrete(limits=c("Male","Female")) + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5)) + xlab("") + ylab("") + ggtitle("Gender by Race/Ethnicity & Contact Type")+ scale_fill_discrete(name="Legend",limits=c("Male","Female")) ggsave(plot = gender_race_plot, "03_stop_frisk/images/gender_race_contact.png", w = 10.67, h = 8,type = "cairo-png") ################################### ## ## Matching incidents to neighborhoods using DC neighborhood shapefile ## provided by DC OpenData ## h/t: https://gis.stackexchange.com/questions/133625/checking-if-points-fall-within-polygon-shapefile ## ################################### ## neighborhoods dc_neighborhoods <- readOGR("data/shapefiles", layer="Neighborhood_Clusters") coordinates(stop_frisk_matched) <- ~ X + Y neighborhoods <- levels(dc_neighborhoods$NBH_NAMES) nbh_sf_df <- data.frame() for (n in neighborhoods) { print(paste("Classifying stop and frisk incidents in",n)) test <- data.frame() cluster <- dc_neighborhoods[dc_neighborhoods$NBH_NAMES == n , ] proj4string(stop_frisk_matched) <- proj4string(cluster) test <- stop_frisk_matched[complete.cases(over(stop_frisk_matched, cluster)), ] test_df <- as.data.frame(test) try(test_df$neighborhood <- n) nbh_sf_df <- rbind(nbh_sf_df,test_df) } ################################### ## ## Calculate race/age breakdowns of stop and frisk at neighborhood level ## ################################### ## neighborhoods nbh_sf_tot <- nbh_sf_df %>% group_by(neighborhood) %>% summarise (n = n()) %>% mutate(freq=n/sum(n)) nbh_sf_tot$demo_group <- "Total" nbh_sf_tot$subgroup <- "Total" nbh_sf_race <- nbh_sf_df %>% group_by(neighborhood,race_ethn) %>% summarise (n = n()) %>% mutate(freq=n/sum(n)) %>% rename(subgroup = race_ethn) nbh_sf_race$demo_group <- "Race/Ethnicity" nbh_sf_age <- nbh_sf_df %>% group_by(neighborhood,juvenile) %>% summarise (n = n()) %>% mutate(freq=n/sum(n)) %>% rename(subgroup = juvenile) nbh_sf_age$demo_group <- "Age" nbh_sf_demos <- dplyr::bind_rows(nbh_sf_tot,nbh_sf_age,nbh_sf_race) additional_cluster_info <- read.csv("data/shapefiles/Neighborhood_Clusters.csv") nbh_sf_demos <- merge(nbh_sf_demos,additional_cluster_info,by.x="neighborhood",by.y="NBH_NAMES") ################################### ## ## Process Census data ## ################################### census_data_original <- read.csv("data/census/comp_table_cltr00_pop.csv") census_data_tot <- census_data_original %>% select(CLUSTER_TR2000,TotPop_2010) %>% melt(id.vars = c("CLUSTER_TR2000")) census_data_tot$TotPop_2010 <- census_data_tot$value census_data <- census_data_original %>% select(CLUSTER_TR2000,TotPop_2010,PctPopUnder18Years_2010, PctBlackNonHispBridge_2010,PctWhiteNonHispBridge_2010,PctHisp_2010) census_data <- melt(census_data, id.vars = c("CLUSTER_TR2000","TotPop_2010")) census_data <- rbind(census_data,census_data_tot) census_data$pop <- ifelse(census_data$variable == "TotPop_2010",census_data$TotPop_2010, census_data$TotPop_2010 * (census_data$value/100)) census_data <- census_data %>% mutate(variable = recode(census_data$variable, PctPopUnder18Years_2010 = "Juvenile", PctBlackNonHispBridge_2010 = "Black", PctWhiteNonHispBridge_2010 = "White", PctHisp_2010 = "Hispanic/Latino", TotPop_2010 ="Total")) %>% rename(census_value = value) nbh_racial_summary <- census_data_original %>% select(CLUSTER_TR2000,PctBlackNonHispBridge_2010,PctHisp_2010,PctAsianPINonHispBridge_2010) nbh_racial_summary$pct_non_white <- nbh_racial_summary$PctBlackNonHispBridge_2010 + nbh_racial_summary$PctHisp_2010 + nbh_racial_summary$PctAsianPINonHispBridge_2010 nbh_racial_summary$non_white_bins <- cut(nbh_racial_summary$PctBlackNonHispBridge_2010, c(0,25,50,75,95,100)) nbh_racial_summary <- merge(nbh_racial_summary,additional_cluster_info,by.x="CLUSTER_TR2000",by.y="NAME") levels(nbh_racial_summary$non_white_bins) <- c("0-25%","25-50%","50-75%","75-95%","95-100%") nbh_black_summary <- ggplot(nbh_racial_summary,aes(x=reorder(NBH_NAMES,PctBlackNonHispBridge_2010),y=PctBlackNonHispBridge_2010/100,fill=non_white_bins)) + geom_bar(stat='identity') + geom_text(aes(x=reorder(NBH_NAMES,PctBlackNonHispBridge_2010),y=PctBlackNonHispBridge_2010/100, label=percent(round(PctBlackNonHispBridge_2010/100,2))),data=nbh_racial_summary, position=position_dodge(width=0.9), hjust=-0.1,size=3) + theme_fivethirtyeight() + coord_flip() + labs(title = "DC Neighborhood Racial Composition", subtitle="Proportion of Black Residents by Neighborhood as of 2010 Census ", x="",y="Neighborhood Percent of Black Residents", fill = "Neighborhood % Black") + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5,size = 10)) + scale_y_continuous(labels=scales::percent) + guides(fill=guide_legend(nrow=2,byrow=TRUE)) ggsave(plot = nbh_black_summary, "03_stop_frisk/images/nbh_racial_profiles.png", w = 10.67, h = 8,type = "cairo-png") ################################### ## ## Merge neighborhood-level census data to stop and frisk data ## ################################### nbh_sf_demos_census <- merge(nbh_sf_demos,census_data,by.x=c("NAME","subgroup"),by.y=c("CLUSTER_TR2000","variable")) ################################### ## ## Plot stop and frisk and census ## ################################### overall_change <- stop_frisk_total %>% group_by(Year) %>% summarise(count = n()) overall_change$Year <- paste0("year_",overall_change$Year) overall_change$ix <- "Total" overall_change <- dcast(overall_change, ix ~ Year,value.var = "count") overall_change$change_2017_2010 <- (overall_change$year_2017 / overall_change$year_2010) - 1 ## percent change in stop & frisk by nh racial composition 2010 - 2017 yearly_nbh_counts <- nbh_sf_df %>% group_by(year,neighborhood) %>% summarise(n=n()) yearly_nbh_counts$year <- paste0("year_",yearly_nbh_counts$year) # reshape to wide yearly_nbh_counts_wide <- dcast(yearly_nbh_counts, neighborhood ~ year) # merge in census data yearly_nbh_counts_wide <- merge(yearly_nbh_counts_wide,additional_cluster_info,by.x="neighborhood",by.y="NBH_NAMES") yearly_nbh_counts_wide <- merge(yearly_nbh_counts_wide,census_data_original,by.x=c("NAME"),by.y=c("CLUSTER_TR2000")) yearly_nbh_counts_wide$pct_non_white <- yearly_nbh_counts_wide$PctAsianPINonHispBridge_2010 + yearly_nbh_counts_wide$PctBlackNonHispBridge_2010 + yearly_nbh_counts_wide$PctHisp_2010 yearly_nbh_counts_wide$black_bins <-cut(yearly_nbh_counts_wide$PctBlackNonHispBridge_2010, c(0,25,50,75,95,100)) yearly_nbh_counts_wide$change_2017_2010 <- (yearly_nbh_counts_wide$year_2017 / yearly_nbh_counts_wide$year_2010) - 1 change_by_racial_bins <- yearly_nbh_counts_wide %>% group_by(black_bins) %>% summarise(avg_change = mean(change_2017_2010), n= n()) levels(change_by_racial_bins$black_bins) <- c("0-25%","25-50%","50-75%","75-95%","95-100%") change_in_sf <- ggplot(change_by_racial_bins,aes(x=black_bins,y=avg_change)) + geom_bar(stat='identity') + theme_fivethirtyeight() + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5)) + ylab('Change in Total Stop and Frisk 2010 to 2017') + xlab("Neighborhood Percent of Black Residents") + ggtitle("Average Change in Stop and Frisk 2010 to 2017\nby Neighborhood Racial Composition") + geom_text(aes(x=black_bins,y=avg_change,label=percent(round(avg_change,2))),data=change_by_racial_bins, position=position_dodge(width=0.9), vjust=-0.5,size=5) + scale_y_continuous(labels=scales::percent) ggsave(plot = change_in_sf, "03_stop_frisk/images/change_in_sf.png", w = 10.67, h = 8,type = "cairo-png") # overall neighborhood stop and frisk nbh_sf_totals_census_adj <- nbh_sf_demos_census %>% filter(demo_group == "Total") %>% mutate(adj_sf = (n/pop) * 10000, group = 1:39) %>% select(group,adj_sf) %>% rename(value = adj_sf) nbh_names <- nbh_sf_demos_census %>% filter(demo_group == "Total") %>% mutate(group = 1:nrow(nbh_sf_totals_census_adj)) %>% select(neighborhood,group) nbh_sf_totals_census <- nbh_sf_demos_census %>% filter(demo_group == "Total") %>% mutate(group = 1:nrow(nbh_sf_totals_census_adj)) %>% select(group,n) %>% rename(value = n) #group = neighborhood) nbh_sf_totals_census$frame <- 1 nbh_sf_totals_census_adj$frame <- 2 # Interpolate data with tweenr ts <- list(nbh_sf_totals_census, nbh_sf_totals_census_adj,nbh_sf_totals_census_adj,nbh_sf_totals_census) tf <- tween_states(ts, tweenlength = 0.02, statelength = 0.001, ease = c('cubic-in-out'), nframes = 30) init_sort <- nbh_sf_totals_census %>% arrange(-value) %>% mutate(rank = 1:nrow(nbh_sf_totals_census)) %>% select(rank,group) tf <- merge(tf,nbh_names,by="group") tf <- merge(tf,init_sort,by="group") ## h/t to: https://stackoverflow.com/questions/45569659/plot-titles-when-using-gganimate-with-tweenr tf$type <- ifelse(tf$frame > 1.5,"per 10,000 people","") # Make a barplot with frame p <- ggplot(tf, aes(x=reorder(neighborhood,-rank), y=value, fill=value, frame= .frame,ttl=type)) + geom_bar(stat='identity', position = "identity") + coord_flip() + theme_fivethirtyeight() + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5)) + labs(x="Neighborhood",y="Total Stop & Frisk",title="Total Stop and Frisk",fill="Total Stop & Frisk") mygg_animate(p,filename = "03_stop_frisk/images/05_nbh_sf.gif",interval = 0.1, title_frame=T,ani.height=768,ani.width=1024) # overall racial sf & census breakdowns # process 2018 census data from https://www.census.gov/quickfacts/fact/table/DC#viewtop census_race <- read.csv("data/census/QuickFacts Apr-22-2018.csv",nrows = 20) census_race <- slice(census_race, 13:19) %>% select(Fact,District.of.Columbia) %>% rename(value = District.of.Columbia, variable = Fact) census_race$variable <- gsub("([A-Za-z]+).*", "\\1", census_race$variable) census_race$value <- gsub("%", "", census_race$value) census_race <- census_race %>% filter(variable %in% c("White","Black","Hispanic","Asian")) census_race$variable[census_race$variable=="Hispanic"] <- "Hispanic/Latino" sf_race <- stop_frisk_total %>% group_by(race_ethn) %>% summarise (n = n()) %>% mutate(freq=(n/sum(n))*100) %>% rename(variable = race_ethn, value = freq) %>% select(variable,value) %>% filter(variable %in% c("White","Black","Hispanic/Latino","Asian")) sf_race$type <- 'Stop & Frisk' census_race$type <- 'Census' census_sf_race <- rbind(sf_race,census_race) census_sf_race$value <- as.numeric(as.character(census_sf_race$value))/100 census_sf_race$type <- factor(census_sf_race$type, levels=c("Census","Stop & Frisk")) census_sf_race_plot <- ggplot(census_sf_race,aes(x=variable,y=as.numeric(value),fill=variable)) + geom_bar(stat = "identity",position = "stack") + theme_fivethirtyeight() + theme(axis.title = element_text(), plot.title = element_text(hjust = 0.5), strip.text = element_text(size=12)) + ylab("") + xlab("Race") + ggtitle("Stop and Frisk - Census Racial Comparison") + scale_x_discrete(limits = c("White","Black","Hispanic/Latino","Asian")) + scale_y_continuous(labels=scales::percent,limits=c(0,1)) + geom_text(aes(x=variable,y=value,label=percent(round(value,2))),data=census_sf_race, position=position_dodge(width=0.9), vjust=-0.5,size=5) + scale_fill_discrete(name="Legend") + facet_wrap(~type) ggsave(plot = census_sf_race_plot, "03_stop_frisk/images/03_census_sf_race.png", w = 10.67, h = 8,type = "cairo-png") ## scatter plot of neighborhood racial composition and percent of stop and frisk by race ## label petworth? nbh_sf_race_plot <- ggplot(data=filter(nbh_sf_demos_census,demo_group %in% c("Race/Ethnicity")),aes(x=freq,y=census_value)) + geom_point(aes(size=n,color=subgroup),alpha=.7) + scale_x_continuous(limits = c(0, 1),labels = scales::percent) + geom_point(data=subset(nbh_sf_demos_census,neighborhood == "Columbia Heights, Mt. Pleasant, Pleasant Plains, Park View" & demo_group %in% c("Race/Ethnicity")), aes(size=n),colour="black",pch=21) + geom_text(data=subset(nbh_sf_demos_census,neighborhood == "Columbia Heights, Mt. Pleasant, Pleasant Plains, Park View" & demo_group %in% c("Race/Ethnicity")), aes(label=paste0("Columbia Heights\n(",subgroup,")")), hjust="center", vjust = -.5, size=4) + scale_y_continuous(limits = c(0, 100)) + geom_abline(intercept = 0,slope = 100) + geom_hline(yintercept = 50) + geom_vline(xintercept = .5) + theme_fivethirtyeight() + labs(x = "Stop and Frisk Racial Makeup (%)", y = "Neighborhood Racial Makeup (%)") + ggtitle("Neighborhood Population vs. Neighborhood Stop and Frisk") + scale_color_discrete(name="Race") + theme(plot.title = element_text(hjust = 0.5),axis.title = element_text()) + scale_size(name = "Total Stop and Frisk") + theme(legend.position="bottom", legend.box = "horizontal") ggsave(plot = nbh_sf_race_plot, "03_stop_frisk/images/06_nbh_sf_race.png", w = 10.67, h = 10.67,type = "cairo-png") nbh_sf_demos_census$diff <- (nbh_sf_demos_census$census_value/100) - nbh_sf_demos_census$freq ## difference of neighborhood racial composition and percent of stop and frisk by race plot_diff <- function(racial_group,output_file) { race_pct <- nbh_sf_demos_census %>% filter(subgroup == racial_group) %>% select(NAME,neighborhood,census_value) %>% rename(pct = census_value) %>% mutate(pct = pct/100) nbh_sf_demos_census <- merge(nbh_sf_demos_census,race_pct) nbh_diff_race <- ggplot(data=filter(nbh_sf_demos_census,subgroup %in% c(racial_group) & demo_group != "Total"), aes(x = reorder(neighborhood, -diff), y = as.numeric(diff))) + geom_point(aes(size=n,color=pct),alpha=.7,stat='identity') + coord_flip() + geom_hline(yintercept = 0) + theme_fivethirtyeight() + labs(title = "Difference in Stop and Frisk Rate & Population", subtitle = paste("among", racial_group,"Residents (2010 - 2017)"), y = 'Stop & Frisk - Population', x="Neighborhood",size="Total Stop & Frisk",color=paste("Neighborhood %",racial_group)) + theme(plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5,size=12), text = element_text(size=10)) + scale_y_continuous(labels=scales::percent) + scale_color_viridis(labels = percent) + geom_segment(aes(y = 0, x = neighborhood, yend = diff, xend = neighborhood), color = "black") ggsave(plot = nbh_diff_race, paste0("03_stop_frisk/images/",output_file,".png"), w = 10.67, h = 8,type = "cairo-png") } plot_diff("Black","07_nbh_diff_black") plot_diff("White","07a_nbh_diff_white") plot_diff("Hispanic/Latino","07b_nbh_diff_hisp") ## stop & frisk & census pop among blacks by neighborhood white percentage nbh_white <- nbh_sf_demos_census %>% filter(subgroup %in% c("White") & demo_group != "Total") %>% select(neighborhood,census_value) %>% rename(nbh_white_pct = census_value) new_df <- nbh_sf_demos_census %>% filter(subgroup %in% c("Black") & demo_group != "Total") %>% mutate(adj_census = census_value/100) %>% select(neighborhood,adj_census,freq) %>% rename(nbh_black_pct = adj_census, black_sf = freq) new_df_l <- melt(new_df) num_stops <- nbh_sf_demos_census %>% filter(subgroup %in% c("Black") & demo_group != "Total") %>% select(neighborhood,n) new_df_l <- merge(new_df_l,nbh_white,by="neighborhood") new_df_l <- merge(new_df_l,num_stops,by="neighborhood") new_df <- merge(new_df,nbh_white,by="neighborhood") new_df$indicator <- ifelse(new_df$black_sf > new_df$nbh_black_pct,"Higher","Lower") group.colors <- c("Higher" = "#FF0000", "Lower" = "#008000", "Black Stop & Frisk Percentage" = cols[1], "Black Census Percentage" = cols[3]) gg_color_hue <- function(n) { hues = seq(15, 375, length = n + 1) hcl(h = hues, l = 65, c = 100)[1:n] } n = 4 cols = gg_color_hue(n) levels(new_df_l$variable) <- c("Black Census Percentage","Black Stop & Frisk Percentage") test <- ggplot(data=new_df_l, aes(x = as.numeric(nbh_white_pct/100), y = as.numeric(value)), color = variable) + geom_point(aes(size=n,color=variable),alpha=.5,stat='identity') + coord_flip() + geom_segment(data = new_df, aes(y = nbh_black_pct, x = as.numeric(nbh_white_pct/100), yend = black_sf, xend = as.numeric(nbh_white_pct/100), color=indicator), size = 1, alpha = .2) + scale_color_manual(values = group.colors) + theme_fivethirtyeight() + labs(title = "Neighborhood Difference in Stop & Frisk Rate & Population", subtitle = "among Black Residents (2012 - 2017)", y = 'Neighborhood Black Stop & Frisk & Population', x="Neighborhood White Percentage",size="Total Stop & Frisk") + theme(plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5), axis.title = element_text()) + scale_x_continuous(limits = c(0, .85),labels = scales::percent) + scale_y_continuous(limits = c(0, 1),labels = scales::percent) ggsave(plot = test, "03_stop_frisk/images/test.png", w = 10.67, h = 8,type = "cairo-png") ################################### ## ## Tying in crime data ## ################################### coordinates(stop_frisk_matched) <- ~ LONGITUDE + LATITUDE years = c(2012,2013,2014,2015,2016) crime_all_years = data.frame() for (y in years) { crime <- readOGR(paste("data/shapefiles/Crime_Incidents_in_",y,".shp",sep = ""), layer=paste("Crime_Incidents_in_",y,"",sep = "")) neighborhoods <- levels(dc_neighborhoods$NBH_NAMES) new_df <- data.frame() for (n in neighborhoods) { print(paste("Classifying crimes incidents in",n)) test <- data.frame() cluster <- dc_neighborhoods[dc_neighborhoods$NBH_NAMES == n, ] proj4string(crime) <- proj4string(cluster) test <- crime[complete.cases(over(crime, cluster)), ] test_df <- as.data.frame(test) try(test_df$neighborhood <- n) new_df <- rbind(new_df,test_df) } new_df$month <- format(as.Date(new_df$REPORT_DAT,"%Y-%m-%d"), "%m") new_df$Year <- format(as.Date(new_df$REPORT_DAT,"%Y-%m-%d"), "%Y") new_df$year_month <- as.Date(paste0(new_df$month,"/","01/",as.numeric(new_df$Year),sep=""),"%m/%d/%Y") crime_neighborhood <- new_df %>% group_by(neighborhood,Year) %>% summarise(crime = n()) crime_neighborhood$year <- y crime_all_years <- rbind(crime_all_years,as.data.frame(crime_neighborhood)) } crime_total_years_all_dc <- crime_all_years %>% group_by(year) %>% summarise(total_crime = sum(crime)) crime_avg_years <- crime_all_years %>% group_by(year,neighborhood) %>% summarise(tot_crime_yr = sum(crime)) crime_avg_years <- crime_avg_years %>% group_by(neighborhood) %>% summarise(crime = mean(tot_crime_yr)) ## By year nbh_sf_yearly <- nbh_sf_df %>% group_by(year,neighborhood) %>% summarise (stop_frisks = n()) nbh_sf_yearly$prev_year <- as.numeric(as.character(nbh_sf_yearly$year)) - 1 nbh_sf_yearly <- merge(nbh_sf_yearly,crime_all_years, by.x = c("neighborhood","prev_year"), by.y = c("neighborhood","year")) ## relationship between previous year in crime and current year stop and frisk crime_frisk_yearly <- ggplot(data=nbh_sf_yearly,aes(x=crime,y=stop_frisks)) + geom_point() + geom_point(data=subset(nbh_sf_yearly,neighborhood == "Ivy City, Arboretum, Trinidad, Carver Langston" & year == "2014"), colour="red") + geom_smooth(method='glm',formula=y~x) + geom_text(data=subset(nbh_sf_yearly,neighborhood == "Ivy City, Arboretum, Trinidad, Carver Langston" & year == "2014"), aes(label=paste0("Ivy City (",year,")")), hjust=1.1, size=4,colour="black") + theme_fivethirtyeight() + labs(y = "Number Stop and Frisks in Subsequent Year", x = "Number of Crimes Reported in Year") + ggtitle("Crime Incidents vs. Stop and Frisk Incidents in Subsequent Year\nby Neighborhood") + theme(plot.title = element_text(hjust = 0.5),axis.title = element_text()) ggsave(plot = crime_frisk_yearly, "03_stop_frisk/images/08_crime_frisks.png", w = 10.67, h = 8,type = "cairo-png") ## crime-only modelling nbh_sf_avg <- nbh_sf_yearly %>% group_by(neighborhood) %>% summarise(avg_sf = mean(stop_frisks), avg_prev_yr_crime = mean(crime)) nbh_sf_avg <- merge(nbh_sf_avg,additional_cluster_info,by.y="NBH_NAMES",by.x="neighborhood") nbh_sf_avg <- merge(nbh_sf_avg,census_data_original,by.x="NAME",by.y="CLUSTER_TR2000") nbh_sf_avg$pct_non_white <- nbh_sf_avg$PctAsianPINonHispBridge_2010 + nbh_sf_avg$PctBlackNonHispBridge_2010 + nbh_sf_avg$PctHisp_2010 nbh_sf_avg$non_white_bins <-cut(nbh_sf_avg$pct_non_white, c(0,10,20,30,40,50,60,70,80,90,100)) nbh_sf_avg$black_bins <- cut(nbh_sf_avg$PctBlackNonHispBridge_2010, c(0,25,50,75,95,100)) yearly_model <- lm(formula = avg_sf ~ avg_prev_yr_crime, data = nbh_sf_avg) stargazer(yearly_model,align = TRUE, out="03_stop_frisk/images/models.htm") ## crime & race model nbh_sf_yearly <- merge(nbh_sf_yearly,additional_cluster_info,by.y="NBH_NAMES",by.x="neighborhood") nbh_sf_yearly <- merge(nbh_sf_yearly,census_data_original,by.x="NAME",by.y="CLUSTER_TR2000") nbh_sf_yearly$pctnonwhite <- nbh_sf_yearly$PctAsianPINonHispBridge_2010 + nbh_sf_yearly$PctBlackNonHispBridge_2010 + nbh_sf_yearly$PctHisp_2010 nbh_sf_avg$coll_bins <-cut(nbh_sf_avg$pct_non_white, c(0,10,40,60,90,100)) nbh_sf_avg$black_bins <- cut(nbh_sf_avg$PctBlackNonHispBridge_2010, c(0,25,50,75,95,100)) yearly_model_w_race <- lm(formula = avg_sf ~ avg_prev_yr_crime + black_bins, data = nbh_sf_avg) stargazer(yearly_model,yearly_model_w_race,align = TRUE, out="03_stop_frisk/images/models_w_race.htm") nbh_sf_yearly$predicted_w_race <- predict(yearly_model_w_race) nbh_sf_yearly$coll_bins <-cut(nbh_sf_yearly$pctnonwhite, c(0,10,40,60,90,100)) nbh_sf_yearly$black_bins <- cut(nbh_sf_yearly$PctBlackNonHispBridge_2010, c(0,25,50,75,95,100)) levels(nbh_sf_yearly$coll_bins) <- c("0-10%","10-40%","40-60%","60-90%","90-100%") levels(nbh_sf_yearly$black_bins) <- c("0-25%","25-50%","50-75%","75-95%","95-100%") crime_frisk_yearly_race <- ggplot(data=nbh_sf_yearly,aes(x=crime,y=stop_frisks,color=black_bins)) + geom_point(aes(color=black_bins)) + geom_smooth(method = lm,size=2,se = F) + geom_point(data=subset(nbh_sf_yearly,neighborhood == "Ivy City, Arboretum, Trinidad, Carver Langston" & year == "2014"), colour="red",pch=21) + geom_text(data=subset(nbh_sf_yearly,neighborhood == "Ivy City, Arboretum, Trinidad, Carver Langston" & year == "2014"), aes(label=paste0("Ivy City (",year,")")), hjust=1.1, size=4,colour="black") + theme_fivethirtyeight() + labs(x = "Number of Crimes Reported in Year", y = "Number Stop and Frisks in Subsequent Year", color = "Neighborhood % Black Residents") + ggtitle("Crime Incidents vs. Stop and Frisk Incidents\nby Neighborhood Racial Composition") + theme(plot.title = element_text(hjust = 0.5),axis.title = element_text()) ggsave(plot = crime_frisk_yearly_race, "03_stop_frisk/images/crime_frisk_yearly_race.png", w = 10.67, h = 8,type = "cairo-png") ## looking at crime-only residulas by neighborhood racial composition nbh_sf_avg$predicted <- predict(yearly_model) nbh_sf_avg$residuals <- residuals(yearly_model) residuals_nbh_race <- nbh_sf_avg %>% group_by(neighborhood,PctBlackNonHispBridge_2010) %>% summarise(avg_residuals = mean(residuals)) crime_model_residuals <- ggplot(residuals_nbh_race, aes(x = PctBlackNonHispBridge_2010, y = avg_residuals)) + geom_smooth() + geom_point() + geom_point(data=subset(residuals_nbh_race,neighborhood == "Ivy City, Arboretum, Trinidad, Carver Langston"), colour="red") + geom_text(data=subset(residuals_nbh_race,neighborhood == "Ivy City, Arboretum, Trinidad, Carver Langston"), aes(label="Ivy City (2010-2017)"), hjust=1.1, size=4,colour="black") + geom_hline(yintercept = 0) + annotate("text", label = "More stop and frisk than model predicted", x = 15, y = 95, size = 4, colour = "red") + annotate("text", label = "Less stop and frisk than model predicted", x = 15, y = -65, size = 4, colour = "dark green") + theme_fivethirtyeight() + labs(x = "Neighborhood Percent of Black Residents", y = "Model Residual") + ggtitle("Linear Model Residuals by Neighborhood Racial Composition") + theme(plot.title = element_text(hjust = 0.5),axis.title = element_text()) ggsave(plot = crime_model_residuals, "03_stop_frisk/images/09_crime_model_residuals.png", w = 10.67, h = 8,type = "cairo-png") ## total stop and frisk counts by neighborhood race from census nbh_sf_df <- merge(nbh_sf_df,additional_cluster_info,by.x="neighborhood",by.y="NBH_NAMES") nbh_sf_df_census <- merge(nbh_sf_df,census_data_original,by.x=c("NAME"),by.y=c("CLUSTER_TR2000")) nbh_sf_df_census$pct_non_white <- nbh_sf_df_census$PctAsianPINonHispBridge_2010 + nbh_sf_df_census$PctBlackNonHispBridge_2010 + nbh_sf_df_census$PctHisp_2010 nbh_sf_df_census$non_white_bins <-cut(nbh_sf_df_census$pct_non_white, c(0,10,20,30,40,50,60,70,80,90,100)) nbh_sf_df_census$black_bins <-cut(nbh_sf_df_census$PctBlackNonHispBridge_2010, c(0,25,50,75,95,100)) total_sf_nbh_race <- nbh_sf_df_census %>% group_by(year,black_bins) %>% summarise (sf = n()) avg_sf_nbh_race <- total_sf_nbh_race %>% group_by(black_bins) %>% summarise (avg_sf = mean(sf)) crime_w_census <- merge(crime_avg_years,additional_cluster_info,by.y="NBH_NAMES",by.x="neighborhood") crime_w_census <- merge(crime_w_census,census_data_original,by.x="NAME",by.y="CLUSTER_TR2000") crime_w_census <- crime_w_census %>% select(NAME,neighborhood,PctBlackNonHispBridge_2010,PctHisp_2010, PctAsianPINonHispBridge_2010,TotPop_2010,crime) crime_w_census$pct_non_white <- crime_w_census$PctAsianPINonHispBridge_2010 + crime_w_census$PctBlackNonHispBridge_2010 + crime_w_census$PctHisp_2010 crime_w_census$non_white_bins <-cut(crime_w_census$pct_non_white, c(0,10,20,30,40,50,60,70,80,90,100)) crime_w_census$black_bins <-cut(crime_w_census$PctBlackNonHispBridge_2010, c(0,25,50,75,95,100)) crime_w_census <- crime_w_census %>% group_by(black_bins) %>% summarise (crime = mean(crime),pop=mean(TotPop_2010)) crime_sf_race_bins <- merge(crime_w_census,avg_sf_nbh_race,by="black_bins") crime_sf_race_bins$adj_sf <- (crime_sf_race_bins$avg_sf / crime_sf_race_bins$pop) * 100 crime_sf_race_bins$adj_crime <- (crime_sf_race_bins$crime / crime_sf_race_bins$pop) * 100 crime_sf_race_l <- melt(crime_sf_race_bins, id.vars=c("black_bins")) %>% subset(variable %in% c("adj_sf","adj_crime")) levels(crime_sf_race_l$variable) <- c("crime","pop","","Average Stop and Frisk","Average Crime") levels(crime_sf_race_l$black_bins) <- c("0-25%","25-50%","50-75%","75-95%","95-100%") sf_crime_nbh_race <- ggplot(crime_sf_race_l,aes(x=black_bins,y=value,fill=variable,group=as.character(variable))) + geom_bar(stat="identity", position="dodge") + geom_text(aes(label = round(value,2)), position = position_dodge(0.9),vjust=-.5,size=5) + theme_fivethirtyeight() + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5)) + ylab('Crime & Stop and Frisk per 100 people') + xlab("Neighborhood Percent of Black Residents") + scale_fill_discrete(name="Legend") + ggtitle("Average Yearly Stop and Frisk vs. Crime per 100 Residents") ggsave(plot = sf_crime_nbh_race, "03_stop_frisk/images/10_sf_crime_nbh_race.png", w = 10.67, h = 8,type = "cairo-png") ## crime data w/ race crimes_race <- read.csv("data/crime/crimes_anon.csv",stringsAsFactors = F) crimes_race <- crimes_race %>% filter(!is.na(longitude)) dc_neighborhoods <- readOGR("data/shapefiles", layer="Neighborhood_Clusters") coordinates(crimes_race) <- ~ longitude + latitude neighborhoods <- levels(dc_neighborhoods$NBH_NAMES) nbh_crimes_df <- data.frame() for (n in neighborhoods) { print(paste("Classifying crimes incidents in",n)) test <- data.frame() cluster <- dc_neighborhoods[dc_neighborhoods$NBH_NAMES == n , ] proj4string(crimes_race) <- proj4string(cluster) test <- crimes_race[complete.cases(over(crimes_race, cluster)), ] test_df <- as.data.frame(test) try(test_df$neighborhood <- n) nbh_crimes_df <- rbind(nbh_crimes_df,test_df) } ## pulling in neighborhood-level census census_nbh_pct_black <- census_data %>% filter(variable %in% c("Black","Hispanic/Latino","White")) census_nbh_pct_w <- dcast(census_nbh_pct_black,CLUSTER_TR2000 ~ variable,value.var = "census_value") census_nbh_pct_black$bins <- cut(census_nbh_pct_w$Black, c(0,10,40,60,80,100)) nbh_crimes_df$race_ethn <- ifelse(as.character(nbh_crimes_df$ethnicity)=='Hispanic Or Latino','Hispanic/Latino', as.character(nbh_crimes_df$race)) nbh_crimes_df$race_ethn[nbh_crimes_df$ethnicity == "Hispanic Or Latino"] <- "Hispanic/Latino" ## calculate neighborhood-level crimes by race crimes_by_race_nbh <- nbh_crimes_df %>% group_by(neighborhood,race_ethn) %>% summarise(crimes=n()) %>% filter(race_ethn %in% c("White","Black","Hispanic/Latino")) ## calculate neighborhood-level stop and frisks by race stops_by_race_nbh <- nbh_sf_df %>% filter(year == 2017) %>% group_by(neighborhood,race_ethn) %>% summarise(stop_frisks=n()) %>% filter(race_ethn %in% c("White","Black","Hispanic/Latino")) ## merge arrests & stop and frisk then census stops_crimes_nbh <- merge(crimes_by_race_nbh,stops_by_race_nbh,by=c("neighborhood","race_ethn"), all = T) additional_cluster_info <- read.csv("data/shapefiles/Neighborhood_Clusters.csv") stops_crimes_nbh <- merge(stops_crimes_nbh,additional_cluster_info,by.x="neighborhood",by.y="NBH_NAMES") stops_crimes_tracts_nbh <- merge(stops_crimes_nbh,census_nbh_pct_w,by.x="NAME",by.y="CLUSTER_TR2000") stops_crimes_tracts_nbh$adj_sf <- (stops_crimes_tracts_nbh$stop_frisks / stops_crimes_tracts_nbh$pop) * 100 stops_crimes_tracts_nbh$adj_crimes <- (stops_crimes_tracts_nbh$crimes / stops_crimes_tracts_nbh$pop) * 100 ## roll up neighborhoods and aggregate stop & frisk and arrests based on racial bins stops_crimes_nbh_census_bins <- stops_crimes_tracts_nbh %>% replace(is.na(.), 0) %>% group_by(bins,race_ethn) %>% summarise(total_crimes = sum(crimes), total_sf = sum(stop_frisks)) ## calculate crime to stop & frisk ratio stops_crimes_nbh_census_bins$arrest_to_stops <- stops_crimes_nbh_census_bins$total_sf / stops_crimes_nbh_census_bins$total_crimes stops_crimes_ratio <- ggplot(stops_crimes_nbh_census_bins,aes(x=bins,y=arrest_to_stops,color=race_ethn,group=as.character(race_ethn))) + geom_line(size=2) + theme_fivethirtyeight() + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5)) + ylab('Stop & Frisk to Crimes Ratio') + xlab("Neighborhood Racial Composition") + scale_x_discrete(labels = c("< 10% black","10 - 40% black","40 - 60% black","> 60% black","80 - 100% black")) + scale_color_discrete(name="Legend") + #scale_y_continuous(limits = c(0,2.5)) + ggtitle("2017 Stop & Frisk to 2016 Crimes Ratio") ggsave(plot = stops_crimes_ratio, "03_stop_frisk/images/stops_crimes_ratio.png", w = 10.67, h = 8,type = "cairo-png") ## re-creating stop and frisk by neighborhood percent using crime instead nbh_crimes_race <- nbh_crimes_df %>% group_by(neighborhood,race_ethn) %>% summarise (crime_n = n()) %>% mutate(crime_freq=crime_n/sum(crime_n)) %>% rename(subgroup = race_ethn) nbh_crime_race <- merge(nbh_crimes_race,nbh_sf_race,by=c("neighborhood","subgroup"),all=T) nbh_crime_race <- nbh_crime_race %>% replace(., is.na(.), 0) # adding neighborhood census data nbh_crime_race <- merge(additional_cluster_info,nbh_crime_race,by.y="neighborhood",by.x="NBH_NAMES") nbh_crime_race <- merge(nbh_crime_race,census_data,by.x=c("NAME","subgroup"),by.y=c("CLUSTER_TR2000","variable"),all.x=T) nbh_crime_sf_race_scatter <- ggplot(data=filter(nbh_crime_race,subgroup %in% c("White","Black","Hispanic/Latino")),aes(x=freq,y=crime_freq)) + geom_point(aes(size=n,color=subgroup),alpha=.7) + #geom_point(aes(size=census_value,color=subgroup),alpha=.7) + geom_point(data=subset(nbh_crime_race,NBH_NAMES == "Columbia Heights, Mt. Pleasant, Pleasant Plains, Park View" & subgroup %in% c("White","Black")), aes(size=n),colour="black",pch=21) + geom_text(data=subset(nbh_crime_race,NBH_NAMES == "Columbia Heights, Mt. Pleasant, Pleasant Plains, Park View" & subgroup %in% c("White","Black")), aes(label=paste0("Columbia Heights\n(",subgroup,")")), hjust="center", vjust = -.5, size=4) + geom_point(data=subset(nbh_crime_race,NBH_NAMES == "Columbia Heights, Mt. Pleasant, Pleasant Plains, Park View" & subgroup %in% c("Hispanic/Latino")), aes(size=n),colour="black",pch=21) + geom_text(data=subset(nbh_crime_race,NBH_NAMES == "Columbia Heights, Mt. Pleasant, Pleasant Plains, Park View" & subgroup %in% c("Hispanic/Latino")), aes(label=paste0("Columbia Heights\n(",subgroup,")")), hjust=-.1, vjust = .5, size=4) + scale_x_continuous(limits = c(0, 1),labels = scales::percent) + scale_y_continuous(limits = c(0, 1.0),labels = scales::percent) + geom_abline(intercept = 0,slope = 1) + geom_hline(yintercept = .5) + geom_vline(xintercept = .5) + theme_fivethirtyeight() + labs(x = "Neighborhood Stop and Frisk (2017)", y = "Neighborhood Crime (2016)") + ggtitle("Neighborhood Crime vs. Neighborhood Stop and Frisk") + scale_color_discrete(name="Legend") + #scale_size_continuous(name="Total Stop & Frisk") + scale_size_continuous(name="Neighborhood Population") + theme(plot.title = element_text(hjust = 0.5),axis.title = element_text()) + theme(legend.position="bottom", legend.box = "horizontal") ggsave(plot = nbh_crime_sf_race_scatter, "03_stop_frisk/images/11_nbh_crime_sf_race_scatter.png", w = 10.67, h = 10.67,type = "cairo-png") ###################################### ## ## plotting crime by census ## ###################################### nbh_crimes_race <- merge(additional_cluster_info,nbh_crimes_race,by.y="neighborhood",by.x="NBH_NAMES") nbh_crime_demos_census <- merge(nbh_crimes_race,census_data,by.x=c("NAME","subgroup"),by.y=c("CLUSTER_TR2000","variable")) nbh_crime_demos_census <- merge(nbh_crime_demos_census,nbh_sf_demos_census[ , c("NAME","subgroup","n")],by=c("NAME","subgroup")) crime_and_census_plot <- ggplot(data=filter(nbh_crime_demos_census,subgroup %in% c("White","Black","Hispanic/Latino")),aes(x=census_value/100,y=crime_freq)) + geom_point(aes(size=n,color=subgroup),alpha=.7) + #geom_point(aes(size=census_value,color=subgroup),alpha=.7) + scale_x_continuous(limits = c(0, 1),labels = scales::percent) + scale_y_continuous(limits = c(0, 1.0),labels = scales::percent) + geom_abline(intercept = 0,slope = 1) + geom_hline(yintercept = .5) + geom_vline(xintercept = .5) + theme_fivethirtyeight() + labs(x = "Neighborhood Population", y = "Percent of Crime") + ggtitle("Neighborhood Crime v. Census Population") + scale_color_discrete(name="Legend") + scale_size_continuous(name="Total Stop & Frisk") + theme(plot.title = element_text(hjust = 0.5),axis.title = element_text()) ggsave(plot = crime_and_census_plot, "03_stop_frisk/images/crime_and_census_plot.png", w = 10.67, h = 10.67,type = "cairo-png") nbh_crime_race$diff <- nbh_crime_race$freq - (nbh_crime_race$crime_freq) nbh_diff_crimes <- ggplot(data=filter(nbh_crime_race,subgroup %in% c("White","Black","Hispanic/Latino")), aes(x = reorder(NBH_NAMES, diff), y = as.numeric(diff))) + geom_point(aes(size=n,color=subgroup),alpha=.7,stat='identity') + labs(x = "Neighborhood", y = "Stop & Frisk - Population") + coord_flip() + ggtitle("Difference Between 2017 Stop and Frisk\n & 2016 Crime Rate by Race") + geom_hline(yintercept = 0) + theme_fivethirtyeight() + theme(plot.title = element_text(hjust = 0.5), text = element_text(size=10), legend.title = element_text(size=12), legend.text = element_text(size=12)) + scale_y_continuous(labels=scales::percent) + guides(color=guide_legend(title="Race/Ethnicity"), size=guide_legend(title="Total Stop and Frisk")) ggsave(plot = nbh_diff_crimes, "03_stop_frisk/images/12_nbh_diff_crimes.png", w = 10.67, h = 8,type = "cairo-png") ################################### ## ## poisson modelling ## ################################### stops_crimes_tracts_nbh$race_ethn <- factor(stops_crimes_tracts_nbh$race_ethn,levels = c("White","Black","Hispanic/Latino")) stops_crimes_tracts_nbh$black_bins <-cut(stops_crimes_tracts_nbh$Black, c(0,25,50,75,95,100)) stop_model <- glm(stop_frisks ~ race_ethn + Black, family=quasipoisson, offset=log(crimes), data = stops_crimes_tracts_nbh, subset=crimes>0 & stop_frisks>0) summary(stop_model) stargazer(stop_model,align = TRUE, out="03_stop_frisk/images/poisson.htm") coefs <- data.frame(stop_model$coefficients,check.rows = T) coefs$ix <- "index" coefs$values <- row.names(coefs) coefs_w <- dcast(coefs,ix ~ values, value.var = "stop_model.coefficients") neighborhoods_1 <- seq(0, 100, by=1) all <- expand.grid(neighborhoods_1) regression_output <- merge(all,coefs_w,by = NULL) regression_output$black_value <- regression_output$`(Intercept)` + regression_output$race_ethnBlack + regression_output$Var1 * regression_output$Black regression_output$hisp_value <- regression_output$`(Intercept)` + regression_output$`race_ethnHispanic/Latino` + regression_output$Var1 * regression_output$Black regression_output$white_value <- regression_output$`(Intercept)` + 0 + regression_output$Var1 * regression_output$Black ggtern(data = regression_output,aes(x=white,y=black,z=hisp)) + geom_point(size=1,aes(color=regression_output$black_value)) + theme_bw() + scale_color_gradient2(low = "blue", mid = "white", high = "red") Black = c(exp(coefs[1,1] + coefs[2,1] + 0), exp(coefs[1,1] + coefs[2,1] + coefs[4,1]), exp(coefs[1,1] + coefs[2,1] + coefs[5,1]), exp(coefs[1,1] + coefs[2,1] + coefs[6,1]), exp(coefs[1,1] + coefs[2,1] + coefs[7,1])) White = c(exp(coefs[1,1] + 0 + 0), exp(coefs[1,1] + 0 + coefs[4,1]), exp(coefs[1,1] + 0 + coefs[5,1]), exp(coefs[1,1] + 0 + coefs[6,1]), exp(coefs[1,1] + 0 + coefs[7,1])) Hispanic = c(exp(coefs[1,1] + coefs[3,1] + 0), exp(coefs[1,1] + coefs[3,1] + coefs[4,1]), exp(coefs[1,1] + coefs[3,1] + coefs[5,1]), exp(coefs[1,1] + coefs[3,1] + coefs[6,1]), exp(coefs[1,1] + coefs[3,1] + coefs[7,1])) labels <- c("0-25% black","25-50% black","50-75% black","75-95% black","95-100% black") results <- data.frame(labels, Black, White,Hispanic) results_l <- regression_output %>% select(Var1,black_value,white_value,hisp_value) results_l <- melt(results_l,id.vars = "Var1") levels(results_l$variable) <- c("Black","White","Hispanic/Latino") poisson_plot <- ggplot(data=results_l,aes(x=Var1/100,y=exp(as.numeric(value)),color=variable,group=as.character(variable))) + geom_line(size=2) + theme_fivethirtyeight() + theme(axis.title = element_text(),plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5)) + labs(title = "Estimated Stop and Frisk by Neighborhood Racial Composition", subtitle = "Poisson regression results using constant term + race parameters for each neighborhood composition", y = 'Stop and Frisks per Crime', x="Neighborhood Percent of Black Residents") + scale_color_discrete(name="Legend") + scale_x_continuous(labels=scales::percent) ggsave(plot = poisson_plot, "03_stop_frisk/images/13_poisson_plot.png", w = 10.67, h = 8,type = "cairo-png") ################################### ## ## exporting nbh data to csv for table ## ################################### nbh_sf_demos_census$census_percent <- nbh_sf_demos_census$census_value / 100 nbh_sf_demos_census$census_percent <- round(nbh_sf_demos_census$census_percent,2) output_sf <- dcast(data = nbh_sf_demos_census, neighborhood ~ subgroup, value.var = "freq") output_sf <- output_sf %>% rename(Total.stop_and_frisk = Total, Juvenile.stop_and_frisk = Juvenile, White.stop_and_frisk = White, Black.stop_and_frisk = Black, "Hispanic.Latino.stop_and_frisk" = "Hispanic/Latino") output_census <- dcast(data = nbh_sf_demos_census, neighborhood ~ subgroup, value.var = "census_percent") output_census <- output_census %>% rename(Total.census = Total, Juvenile.census = Juvenile, White.census = White, Black.census = Black, "Hispanic.Latino.census" = "Hispanic/Latino") output <- merge(output_sf,output_census,by=c("neighborhood")) output$Black.Diff <- output$Black.census - output$Black.stop_and_frisk output$Hispanic.Latino.Diff <- output$Hispanic.Latino.census - output$Hispanic.Latino.stop_and_frisk output$Juvenile.Diff <- output$Juvenile.census - output$Juvenile.stop_and_frisk output$White.Diff <- output$White.census - output$White.stop_and_frisk order_cols <- c("neighborhood","Black.stop_and_frisk","Black.census","Black.Diff", "Hispanic.Latino.stop_and_frisk","Hispanic.Latino.census","Hispanic.Latino.Diff", "Juvenile.stop_and_frisk","Juvenile.census","Juvenile.Diff","White.stop_and_frisk", "White.census","White.Diff") output <- output[, order_cols] write.csv(output, "03_stop_frisk/scripts/shiny/sf_nbh_summary.csv")