Dataset Viewer
Auto-converted to Parquet
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
327
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
41 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
646M
star_events_count
int64
0
40k
fork_events_count
int64
0
32.4k
gha_license_id
stringclasses
13 values
gha_event_created_at
timestamp[us]date
2012-09-05 15:55:17
2023-09-14 21:52:42
gha_created_at
timestamp[us]date
2008-05-25 01:21:32
2023-05-27 23:04:20
gha_language
stringclasses
57 values
src_encoding
stringclasses
24 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
7
9.18M
extension
stringclasses
1 value
filename
stringlengths
2
141
content
stringlengths
7
9.18M
bd81e37dfcf6b3cdb4c0bd715854b39667cedc7d
d6ff1e6257582f785915e3a0fad3d4896ebd9acb
/R_old/OVERALL_TRANSPIRATION.R
dd4c315e6edbe8f2886bcf7adad85997b5a0dd40
[]
no_license
RemkoDuursma/Kelly2015NewPhyt
355084d7d719c30b87200b75887f5521c270b1b5
447f263f726e68298ee47746b4de438fbc8fdebf
refs/heads/master
2021-01-15T13:02:00.392000
2015-09-08T04:56:15
2015-09-08T04:56:15
42,089,956
0
0
null
null
null
null
UTF-8
R
false
false
3,247
r
OVERALL_TRANSPIRATION.R
setwd("C:/Documents and Settings/Jeffrey Kelly/Desktop/EUC DATA/EUC OVERALL BIOMASS") PILBIOMASS<-read.csv("PILTRANSAA.csv",sep=",", header=TRUE) names(PILBIOMASS) str(PILBIOMASS) windows(width=8, height=4) #, pointsize=18) par(xaxs="i",yaxs="i") par(las=2) par(mar=c(4.5,4.5,1,1)) par(xaxs="i",yaxs="i") par(mfrow=c(1,2), cex.lab=1) #PIL par(las=1) with(PILBIOMASS,plot(E[ST=="PILAD"]~D[ST=="PILAD"],col="blue",pch=1, ylim=range(0,1.1*max(E)),xlim=range(0,1.05*max(D)), ylab="",xlab=expression(bold(Day)))) title(main="Eucalyptus pilularis", font.main=4,cex.main=1) with(PILBIOMASS,arrows(D[ST=="PILAD"], ESE[ST=="PILAD"], D[ST=="PILAD"], LSE[ST=="PILAD"] , length = .035, angle = 90, code = 3,col="blue")) #or with(PILBIOMASS,points(E[ST=="PILAND"]~D[ST=="PILAND"],col="blue",pch=16)) with(PILBIOMASS,arrows(D[ST=="PILAND"], ESE[ST=="PILAND"], D[ST=="PILAND"], LSE[ST=="PILAND"] , length = .035, angle = 90, code = 3,col="blue")) with(PILBIOMASS,points(E[ST=="PILED"]~D[ST=="PILED"],col="red",pch=1)) with(PILBIOMASS,arrows(D[ST=="PILED"], ESE[ST=="PILED"], D[ST=="PILED"], LSE[ST=="PILED"] , length = .035, angle = 90, code = 3,col="red")) with(PILBIOMASS,points(E[ST=="PILEND"]~D[ST=="PILEND"],col="red",pch=16)) with(PILBIOMASS,arrows(D[ST=="PILEND"], ESE[ST=="PILEND"], D[ST=="PILEND"], LSE[ST=="PILEND"] , length = .035, angle = 90, code = 3,col="red")) par(las=3) mtext(side = 2, text =expression(bold(Transpiration~~(l~week^-1))), line = 2.5,font=2, cex=1.0) legend("topleft", expression(aC[a]~-~W, aC[a]~-~D,eC[a]~-~W ,eC[a]~-~D), cex=0.75,bty="n", pch = c(16,1,16,1), col=c("blue","blue","red","red"), #xjust = .5, yjust = .5, ) par(las=1) setwd("C:/Documents and Settings/Jeffrey Kelly/Desktop/EUC DATA/EUC OVERALL BIOMASS") POPBIOMASS<-read.csv("POPTRANSAA.csv",sep=",", header=TRUE) names(POPBIOMASS) str(POPBIOMASS) #POP #bottom,left,top,right par(xaxs="i",yaxs="i") par(las=2) par(mar=c(4.5,1,1,4.5)) par(las=1) with(POPBIOMASS,plot(E[ST=="POPAD"]~D[ST=="POPAD"],col="blue",pch=1,yaxt="n", ylim=c(0, 1.1*max(E)),xlim=c(0,1.05*max(D)), ylab="",xlab=expression(bold(Day)))) title(main="Eucalyptus populnea", font.main=4,cex.main=1) with(POPBIOMASS,arrows(D[ST=="POPAD"], ESE[ST=="POPAD"], D[ST=="POPAD"], LSE[ST=="POPAD"] , length = .035, angle = 90, code = 3,col="blue")) axis(4,labels=TRUE,tcl=-0.5,cex.axis=1) #or with(POPBIOMASS,points(E[ST=="POPAND"]~D[ST=="POPAND"],col="blue",pch=16)) with(POPBIOMASS,arrows(D[ST=="POPAND"], ESE[ST=="POPAND"], D[ST=="POPAND"], LSE[ST=="POPAND"] , length = .035, angle = 90, code = 3,col="blue")) with(POPBIOMASS,points(E[ST=="POPED"]~D[ST=="POPED"],col="red",pch=1)) with(POPBIOMASS,arrows(D[ST=="POPED"], ESE[ST=="POPED"], D[ST=="POPED"], LSE[ST=="POPED"] , length = .035, angle = 90, code = 3,col="red")) with(POPBIOMASS,points(E[ST=="POPEND"]~D[ST=="POPEND"],col="red",pch=16)) with(POPBIOMASS,arrows(D[ST=="POPEND"], ESE[ST=="POPEND"], D[ST=="POPEND"], LSE[ST=="POPEND"] , length = .035, angle = 90, code = 3,col="red")) # looks great on screeen / printer dev.copy2pdf(file="somname.pdf") # looks great printed, or after printing MS to PDF # this is the one you paste in word dev.copy2eps(file="fig19.eps")
7e8c94c982763d3b9a74d47bf81ecba200e74f3e
a47ce30f5112b01d5ab3e790a1b51c910f3cf1c3
/A_github/sources/authors/2774/plotly/coord.R
c489eb9d4c358419e3fd6f91a129c297999fc8aa
[]
no_license
Irbis3/crantasticScrapper
6b6d7596344115343cfd934d3902b85fbfdd7295
7ec91721565ae7c9e2d0e098598ed86e29375567
refs/heads/master
2020-03-09T04:03:51.955000
2018-04-16T09:41:39
2018-04-16T09:41:39
128,578,890
5
0
null
null
null
null
UTF-8
R
false
false
2,359
r
coord.R
#' *** This won't be possible until plotly.js implements aspect ratios... *** #' #' #' Force the aspect ratio according to x and y scales #' #' #' #' When x and y are numeric variables measured on the same scale, #' #' or are related in some meaningful way, forcing the aspect ratio of the #' #' plot to be proportional to the ratio of a unit change in x versus y improves #' #' our ability to correctly perceive the data. #' #' #' #' @param p a plotly object #' #' @param ratio aspect ratio, expressed as y / x #' #' @export #' #' @examples #' #' #' #' canada <- map_data("world", "canada") #' #' #' #' canada %>% #' #' group_by(group) %>% #' #' plot_ly(x = ~long, y = ~lat, alpha = 0.2) %>% #' #' add_polygons(hoverinfo = "none", color = I("black")) %>% #' #' coord_fix() #' #' #' #' # works on (non-faceted) ggplot2 plots, too #' #' gg <- ggplot(canada, aes(long, lat, group = group)) + #' #' geom_polygon() + coord_fixed() #' #' #' #' gg %>% #' #' ggplotly() %>% #' #' coord_fix() #' #' #' #' coord_fix <- function(p, ratio = 1) { #' p <- plotly_build(p) #' # this won't work for subplots, or categorical data #' x <- grepl("^xaxis", names(p$x$layout)) #' y <- grepl("^yaxis", names(p$x$layout)) #' if (sum(x) > 1 || sum(y) > 1) { #' stop("Can not impose aspect ratio a plot with more than one x/y axis", call. = FALSE) #' } #' xDat <- unlist(lapply(p$x$data, "[[", "x")) #' yDat <- unlist(lapply(p$x$data, "[[", "y")) #' if (!is.numeric(xDat) || !is.numeric(yDat)) { #' stop("Must have numeric data on both x and y axes to enforce aspect ratios", call. = FALSE) #' } #' #' # warn about any pre-populated domains, they will get squashed #' xDom <- p$x$layout[["xaxis"]]$domain %||% c(0, 1) #' yDom <- p$x$layout[["yaxis"]]$domain %||% c(0, 1) #' if (!identical(yDom, c(0, 1)) || !identical(xDom, c(0, 1))) { #' warning( #' "coord_fix() won't respect prespecified axis domains (other than the default)", #' call. = FALSE #' ) #' } #' #' xRng <- range(xDat, na.rm = TRUE) #' yRng <- range(yDat, na.rm = TRUE) #' asp <- ratio * diff(yRng) / diff(xRng) #' if (asp < 1) { #' p$x$layout[["yaxis"]]$domain <- c(0 + asp / 2, 1 - asp / 2) #' } else { #' asp <- 1 / asp #' p$x$layout[["xaxis"]]$domain <- c(0 + asp / 2, 1 - asp / 2) #' } #' p #' }
87612036fd5fa980712ac1e05cfc398425c50685
86c0b4c6c1746ebf0441c62421748190d057067d
/plot/mass.R
20769a023b830ddef7c35ab7c099b5ac260e9f87
[ "MIT" ]
permissive
yufree/democode
372f0684c49505965b0ba5abe0675c2b6f7fb3da
0a332ac34a95677ce859b49033bdd2be3dfbe3c4
refs/heads/master
2022-09-13T11:08:55.152000
2022-08-28T23:09:00
2022-08-28T23:09:00
20,328,810
5
14
null
2017-01-06T16:07:25
2014-05-30T12:41:28
HTML
UTF-8
R
false
false
1,185
r
mass.R
source("http://bioconductor.org/biocLite.R") biocLite("mzR") library(mzR) all <- openMSfile('./FULL200.CDF') df <- header(all) bb <- peaks(all) aaaa <- sapply(bb,as.data.frame) oddvals <- seq(1, ncol(aaaa), by=2) aaaaa <- unlist(aaaa[oddvals]) ccc <- unique(c(aaaaa)) ccc <- ccc[order(ccc)] # bbb <- sapply(bb, "[",250:700) # ddd <- unique(c(bbb)) # dddd <- ddd[ddd<700] time <- df$retentionTime df2 <- matrix(0, nrow = length(ccc), ncol = length(time)) rownames(df2) <- ccc colnames(df2) <- time rm(aaaa) rm(aaaaa) rm(oddvals) rm(df) rm(all) gc() for(i in 1:length(time)){ temp <- bb[[i]] index <- which(ccc%in%temp[,1]) df2[index,i] <- temp[,2] } ddd <- as.integer(ccc) library(data.table) dt = data.table(df2) dt$fac <- ddd df3 <- dt[,lapply(.SD, sum), by=ddd ] df3 <- as.matrix(df3) df7 <- df3[,2000:3000] heatmap(df7) library(rARPACK) df4 <- svds(df3,2) df5 <- df4$u %*% diag(df4$d) %*% t(df4$v) rownames(df5) <- ddd colnames(df5) <- time df6 <- df5[,2000:3000] heatmap(df6) df8 <- as.data.frame(df5) df9 <- as.data.frame(t(df8)) rownames(df8) <- ddd colnames(df9) <- time write.table(df3,'df3.txt')
99a524e8baa9751bbd5db7787f3567c66a6e8bee
4450235f92ae60899df1749dc2fed83101582318
/ThesisRpackage/R/3Article_old/GSE42861_function.R
4e60f4de4028e99df28eb3e6e687f0b5409e866e
[ "MIT" ]
permissive
cayek/Thesis
c2f5048e793d33cc40c8576257d2c9016bc84c96
14d7c3fd03aac0ee940e883e37114420aa614b41
refs/heads/master
2021-03-27T20:35:08.500000
2017-11-18T10:50:58
2017-11-18T10:50:58
84,567,700
0
0
null
null
null
null
UTF-8
R
false
false
8,617
r
GSE42861_function.R
#' main experiment #' #' @export GSE42861_experiment <- function(s, save = TRUE) { # glm glm <- Method(name = "glm", hypothesis.testing.method = phenotypeWayReg_glm_score(family = binomial, factorized.X1 = TRUE), impute.genotype.method = imputeByMean(), nickname = "glm") # glm + 2 PCs glm_2PC <- PCAClassicLinearMethod(K = 2, center = TRUE, hypothesis.testing.method = phenotypeWayReg_glm_score(family = binomial, factorized.X1 = TRUE), nickname = "glm+2PCs", assumingStructure = FALSE) # glm + 6 pcs glm_6PC <- PCAClassicLinearMethod(K = 6, center = TRUE, hypothesis.testing.method = phenotypeWayReg_glm_score(family = binomial, factorized.X1 = TRUE), nickname = "glm+6PCs", assumingStructure = FALSE) # glm + 6 refactor glm_6refractor <- refractorMethod(K = 6, verbose = FALSE, t = 500, nickname = "glm+6refractor") # glm + 6 lfmm ridge glm_6lfmm.ridge <- RidgeLFMMMethod(K = 6, hypothesis.testing.method = phenotypeWayReg_glm_score(), lambda = 1e6, nickname = "glm+6lfmm") # lfmm ridge lfmm.ridge <- RidgeLFMMMethod(K = 6, hypothesis.testing.method = lm_zscore(gif = FALSE), lambda = 1e6, nickname = "lfmm ridge") # run exp exp <- ComparisonExperiment(s, glm, glm_2PC, glm_6PC, glm_6refractor, glm_6lfmm.ridge, lfmm.ridge) exp <- runExperiment(exp) # save exp if (save) { dumpExperiment(exp) } exp } #' @export GSE42861_plot <- function(exp) { # Rmk: i am only interested in pvalue1 and score1 other pavalue was not computed # with glm of lm # qqplot ggplot(exp$df.res %>% dplyr::filter(variable.name == "pvalue1")) + stat_qq(aes(sample = -log10(estimate)), distribution = stats::qexp, dparams = list(rate = log(10))) + geom_abline(slope = 1, intercept = 0) + facet_grid(method.name~.) + ggtitle("-log10(pvalue) qqplot") } #' @export GSE42861_get_RahmaniLoci <- function() { table <- tabulizer::extract_tables("~/Projects/Biblio/org-ref-pdfs/SF_Rahmani_2016.pdf", pages = 19, method = "data.frame")[[1]] table } ################################################################################ # Long running #' Run of PCA #' #' #' @export long_GSE42861_PCA <- function() { library(Article3Package) G.file <- "~/Projects/Data2016_2017/GSE42861/betanormalized_metylationlvl.filtered.rds" X.file <- "~/Projects/Data2016_2017/GSE42861/X.rds" s <- TrueSampler(G.file = G.file, X.file = X.file, outlier.file = NULL, n = NULL, L = NULL) exp <- HGDP_PCA(s, save = TRUE) } #' Run of LFMM #' #' #' @export long_GSE42861_LFMM <- function() { cl <- parallel::makeCluster(2) doParallel::registerDoParallel(cl) library(Article3Package) G.file <- "~/Projects/Data2016_2017/GSE42861/betanormalized_metylationlvl.filtered.rds" X.file <- "~/Projects/Data2016_2017/GSE42861/X.rds" s <- TrueSampler(G.file = G.file, X.file = X.file, outlier.file = NULL, n = NULL, L = NULL) lambdas <- c(1e-10, 1e0, 1e2, 1e10) Ks <- c(1,6,8,20) HGDB_runs(s, Ks = Ks, lambdas = lambdas, save = TRUE) } #' Run of GSE42861_experiment #' #' #' @export long_GSE42861_exp <- function() { library(Article3Package) G.file <- "~/Projects/Data2016_2017/GSE42861/betanormalized_metylationlvl.rds" X.file <- "~/Projects/Data2016_2017/GSE42861/X.rds" s <- TrueSampler(G.file = G.file, X.file = X.file, outlier.file = NULL, n = NULL, L = NULL) cl <- parallel::makeCluster(6) doParallel::registerDoParallel(cl) exp <- GSE42861_experiment(s, save = TRUE) exp } #' cross validation #' #' #' @export long_GSE42861_CrossVal <- function(cluster.nb = NULL, K = 6, G.file = "~/Projects/Data2016_2017/GSE42861/betanormalized_metylationlvl.filtered.rds", X.file = "~/Projects/Data2016_2017/GSE42861/X.rds", lambdas = c(1e-10, 1e0, 1e2, 1e10), rep = 5, missing.prop = 0.5, save = TRUE, bypass = FALSE) { KrakTest(bypass) if (!is.null(cluster.nb)) { cl <- parallel::makeCluster(cluster.nb) doParallel::registerDoParallel(cl) } s <- TrueSampler(G.file = G.file, X.file = X.file, outlier.file = NULL, n = NULL, L = NULL) dat <- sampl(s) m <- finalLfmmRdigeMethod(K = K, lambda = NULL) description <- paste0("long_GSE42861_CrossVal with K=", K, "and lambdas = ",paste(lambdas,collapse = '|')) exp <- Experiment(name = "long_GSE42861_CrossVal", description = description) exp$crossvalidation.res <- crossvalidation_kfold_missingvalue(m = m, dat = dat, rep = rep, missing.prop = missing.prop, lambdas = lambdas) # save exp if (save) { dumpExperiment(exp) } exp } #' cross validation #' #' #' @export long_GSE42861_lfmm_glm <- function(K.lfmm = 6, K.refactor = 6, G.file = "~/Projects/Data2016_2017/GSE42861/betanormalized_metylationlvl.filtered.rds", X.file = "~/Projects/Data2016_2017/GSE42861/X.rds", lambda = 1e-10, save = TRUE, bypass = FALSE, refactor = FALSE) { KrakTest(bypass) s <- TrueSampler(G.file = G.file, X.file = X.file, outlier.file = NULL, n = NULL, L = NULL) dat <- sampl(s) G <- dat$G X <- dat$X ## other co.var correction dat$G <- G dat$X <- X[,-1] m.lm <- finalLm() m.lm <- fit(m.lm, dat) m.lfmm <- finalLfmmRdigeMethod(K = K.lfmm, lambda = lambda) m.refactor <- finalRefactorMethod(K = K.refactor) description <- paste0("long_GSE42861_lfmm_glm with K=", K.lfmm, "and lambdas = ", lambda) exp <- Experiment(name = "long_GSE42861_lfmm_glm", description = description) # run of the method dat$G <- m.lm$epsilon dat$X <- X[,1, drop = FALSE] exp$m.lfmm <- fit(m.lfmm, dat) exp$m.refactor <- fit(m.refactor, dat) # hypothesis testing glm.aux <- function(m, name) { glm.func <- phenotypeWayReg_glm_score(family = binomial, factorized.X1 = TRUE) glm.res <- glm.func$fun(m, dat) df <- tibble(index = 1:length(glm.res$score), method.name = name, estimate = glm.res$score[1,], variable.name = "score") df <- tibble(index = 1:length(glm.res$pvalue), method.name = name, estimate = glm.res$pvalue[1,], variable.name = "pvalue") %>% rbind(df) df } exp$df.res <- rbind(glm.aux(exp$m.refactor, "refactor"), glm.aux(exp$m.lfmm, "lfmm")) # save exp if (save) { dumpExperiment(exp) } exp }
ac457a941d93eb56777aeb1bda10707ce8907e13
c54d1c0a3d81bddb25f3f55078f305ad6c15997b
/R/get_internal_tree.R
ffd29651c660f728d71fcc716d3ca033637fb637
[]
no_license
cran/genpathmox
dc065d3b5ea1c8632068fe3d9bfa7b063045bb2c
517be94b39d8742cd3d39aedc152e026d865afd6
refs/heads/master
2023-01-12T03:39:55.183000
2022-12-22T10:00:12
2022-12-22T10:00:12
25,984,875
0
0
null
null
null
null
UTF-8
R
false
false
9,114
r
get_internal_tree.R
#' ############################################################################################ #' @title Calculating size (numeber of individual of a node) #' @details #' Internal function #' @param x matrix or dataframe with data. #' @param size value indicating the minimun threshold of number of observations for a node #' @return the number of observations in a node #' @keywords internal #' @export #' percent.node <- function(x,size) { indiv = nrow(x) min.n.ind = trunc(indiv*size) list(min.n.ind=min.n.ind) } #' ############################################################################################ #' @title Calculating Deepth stop criterion #' @details #' Internal function #' @param node id that identifies a specicif node #' @return deepth of the tree #' @keywords internal #' @export #' showDeepth=function(node) { return (trunc(log2(node@id))) } #' ############################################################################################ #' @title Observations belonging to the root node #' @details #' Internal function #' @param moxtree class containing the moxtree elements #' @return the observations belonging to the root node #' @keywords internal #' @export #' root.tree <- function(moxtree) { root = NULL for (n in moxtree@nodes) { if (n@id == 1) { root=n@elements } } root } #' ############################################################################################ #' @title Observations belonging to the terminal nodes #' @details #' Internal function #' @param moxtree class containing the moxtree element. #' @return the observations belonging to the terminal nodes #' @keywords internal #' @export #' terminal.tree <- function(moxtree) { terminal = list() id = list() if (length(moxtree@nodes) > 1) { for (n in moxtree@nodes) { if (n@id == 1) { terminal[[length(terminal)+1]] = n@elements id[[length(id)+1]] = "Root" } if (length(n@childs) == 0) { terminal[[length(terminal)+1]] = n@elements id[[length(id)+1]] = n@id } } for (i in 1:length(terminal)){names(terminal) = paste("node",id)} terminal } else { terminal = NULL } terminal } #' ############################################################################################ #' @title Observations belonging to the nodes #' @details #' Internal function #' @param moxtree class containing the moxtree elements #' @return the observations belonging to the nodes #' @keywords internal #' @export #' nodes.tree <- function(moxtree) { nodes = list() id = list() if (length(moxtree@nodes) > 1) { for (n in moxtree@nodes) { nodes[[length(nodes)+1]] = n@elements id[[length(id)+1]] = n@id } for (i in 1:length(nodes)) {names(nodes) = paste("node",id)} nodes } else { nodes = NULL } nodes } #' ############################################################################################ #' @title Posibble partions for each node of the tree #' @details #' Internal function #' @param moxtree class containing the moxtree elements #' @return the Posibble partions for each node of the tree #' @keywords internal #' @export #' candidates.tree <- function(moxtree) { candidates = list() id = list() if (length(moxtree@nodes) > 1) { for (n in moxtree@nodes) { if (length(n@childs)>0) { candidates[[length(candidates)+1]] = n@info@candidates id[[length(id)+1]] = n@id } } for (i in 1:length(candidates)) {names(candidates) = paste("node",id)} candidates } else { candidates = NULL } candidates } #' ############################################################################################ #' @title F-global test results for each tree partition #' @details #' Internal function #' @param moxtree class containing the moxtree elements #' @return the F-global test results for each tree partition #' @keywords internal #' @export #' fglobal.tree <- function(moxtree) { fglobal = list() fgtable = NULL if (length(moxtree@nodes) > 1) { for (n in moxtree@nodes) { if (length(n@childs) > 0) { fglobal[[length(fglobal)+1]] = data.frame(n@id,n@info@fgstatistic,n@info@fpvalg,n@info@variable,t(n@info@level)) } } for (i in 1:length(fglobal)) {fgtable = rbind(fgtable,fglobal[[i]])} colnames(fgtable) = c("node","F value","Pr(>F)","variable","g1.mod","g2.mod") Fg.r = fgtable } else { Fg.r = NULL } Fg.r } #' ############################################################################################ #' @title F-coefficients test results for each tree partition #' @details #' Internal function #' @param moxtree class containing the moxtree elements #' @return the F-coefficients test results for each tree partition #' @keywords internal #' @export fcoef.tree <- function(moxtree) { fc = list() id = list() fctable = NULL if (length(moxtree@nodes) > 1) { for (n in moxtree@nodes) { if (length(n@childs) > 0) { id[[length(id)+1]] = n@id fctable = data.frame(as.matrix(n@info@fcstatistic),as.matrix(n@info@fpvalc)) colnames(fctable) = c("F value","Pr(>F)") fc[[length(fc)+1]] = fctable } } names(fc) = paste("node",id,sep="") Fc.r = fc } else { Fc.r=list(fc=NULL,Signif=NULL) } Fc.r } #' ############################################################################################ #' @title General information about the tree #' @details #' Internal function #' @param moxtree class containing the tree elements #' @return a dataframe containing information about the tree and its nodes #' @keywords internal #' @export #' mox.tree <- function(moxtree) { info.node = list() type = NULL terminal = NULL perc = NULL var = NULL mox = NULL if (length(moxtree@nodes)>1) { for (n in moxtree@nodes) { if (n@id == 1) { length.root = length(n@elements) } if (length(n@childs) > 0) { info.node[[length(info.node)+1]] = data.frame(n@info@variable,n@id,n@childs,n@info@level) } if (length(n@childs) == 0) { type = "least" terminal = "yes" } if (n@father == 0) { type = "root" terminal = "no" } if (n@father!=0 && length(n@childs) != 0) { type = "node" terminal = "no" } perc = round((length(n@elements)/length.root)*100,2) data = data.frame(n@id,n@father,showDeepth(n),type,terminal,length(n@elements),perc) mox = rbind(mox,data) } data.info.node = NULL for (i in 1:length(info.node)) {data.info.node = rbind(data.info.node,info.node[[i]])} names(data.info.node)[2] = "n.father" names(data.info.node)[3] = "n.id" MOX =merge (mox, data.info.node,by="n.id",all.x=TRUE)[,-9] names(MOX) = c("node","parent","depth","type","terminal","size","%","variable","category") MOX } else { MOX = NULL } MOX } #' ############################################################################################ #' @title General information about the pathmox algorithm #' @details #' Internal function #' @param signif stop condition 1: significance of the p-value #' @param size stop condition 2: minimum number of individuals in a node #' @param deep stop condition 3: maximum tree depth level #' @param y: set of segmentation variables #' @keywords internal #' @export info.mox <- function(signif,size,deep,y) { cat("\n") cat("PLS-SEM PATHMOX ANALYSIS","\n") cat("\n") cat("---------------------------------------------") cat("\n") cat("Info parameters algorithm","\n") info.value = rbind(signif,size,deep) dimnames(info.value) = NULL info.name = c("threshold signif.","node size limit(%)","tree depth level") info.tree = data.frame(info.name,info.value) names(info.tree) = c("parameters algorithm", "value") print(info.tree) cat("\n") cat("---------------------------------------------") cat("\n") cat("Info segmentation variables","\n") type.y = rep(0, ncol(y)) treat.y = rep("binary", ncol(y)) for (i in 1:length(type.y)) { type.y[i] = ifelse(is.ordered(y[, i]), "ord","nom") if (nlevels(y[, i]) > 2) if (is.ordered(y[, i])) treat.y[i] = "ordinal" else treat.y[i] = "nominal" } df.y = data.frame(nlevels = unlist(lapply(y, nlevels)),ordered = unlist(lapply(y, is.ordered)), treatment = treat.y) if (y[1,1] == 1){ df.y = df.y[-1,] } else { df.y } print(df.y) } #' ############################################################################################ #' @title printing the tree structure #' @details #' Internal function. #' @param moxtree moxtree object #' @return the tree structure #' @keywords internal #' @export #' printTree <- function(moxtree) { for (n in moxtree@nodes){ print (n) } }
84afd0009d68337cd59225335f8ca45ec7753b3d
c2061964216f76ad0f440c76dbfe1119e0279a22
/R/API-methods.R
65f3d6cff7f46778421a4f00c57d3ebfa0b38824
[]
no_license
cran/antaresRead
046829e05e411adfb55fc652ad49ea84f2610264
f6a182b21854e12c5c470afcd38c26f44fb2b8d5
refs/heads/master
2023-04-16T10:45:23.521000
2023-04-06T16:20:02
2023-04-06T16:20:02
87,090,660
0
0
null
null
null
null
UTF-8
R
false
false
4,663
r
API-methods.R
#' API methods #' #' @param endpoint API endpoint to interrogate, it will be added after `default_endpoint`. #' Can be a full URL (by wrapping ìn [I()]), in that case `default_endpoint` is ignored. #' @param ... Additional arguments passed to API method. #' @param default_endpoint Default endpoint to use. #' @param opts Antares simulation options or a `list` with an `host = ` slot. #' #' @return Response from the API. #' @export #' #' @name API-methods #' #' @importFrom httr GET accept_json stop_for_status content add_headers timeout #' #' @examples #' \dontrun{ #' #' # List studies with local API #' api_get( #' opts = list(host = "http://0.0.0.0:8080"), #' endpoint = NULL #' ) #' #' } api_get <- function(opts, endpoint, ..., default_endpoint = "v1/studies") { if (inherits(endpoint, "AsIs")) { opts$host <- endpoint endpoint <- NULL default_endpoint <- NULL } if (is.null(opts$host)) stop("No host provided in `opts`: use a valid simulation options object or explicitly provide a host with opts = list(host = ...)") config <- c( opts$httr_config, list( accept_json() ) ) if (!is.null(opts$token) && opts$token != "") { config <- c( config, add_headers(Authorization = paste("Bearer ", opts$token)) ) } if (is.null(opts$timeout)) opts$timeout <- 60 result <- GET( url = URLencode(paste(c(opts$host, default_endpoint, endpoint), collapse = "/")), config = config, timeout(opts$timeout), ... ) #fix for skipping 404 when some output is missing url_elements <- strsplit(result$url, "%2F")[[1]] condition_status_check <- !(!is.na(url_elements[4]) & url_elements[4] %in% c("economy","adequacy") & result$status_code == 404) if (condition_status_check) stop_for_status(result) else warn_for_status(result) content(result) } #' @export #' #' @rdname API-methods #' #' @importFrom httr POST accept_json content_type_json stop_for_status content add_headers api_post <- function(opts, endpoint, ..., default_endpoint = "v1/studies") { if (inherits(endpoint, "AsIs")) { opts$host <- endpoint endpoint <- NULL default_endpoint <- NULL } if (is.null(opts$host)) stop("No host provided in `opts`: use a valid simulation options object or explicitly provide a host with opts = list(host = ...)") config <- c( opts$httr_config, list( accept_json(), content_type_json() ) ) if (!is.null(opts$token) && opts$token != "") { config <- c( config, add_headers(Authorization = paste("Bearer ", opts$token)) ) } result <- POST( url = URLencode(paste(c(opts$host, default_endpoint, endpoint), collapse = "/")), config = config, ... ) stop_for_status(result) content(result) } #' @export #' #' @rdname API-methods #' #' @importFrom httr PUT accept_json stop_for_status content add_headers api_put <- function(opts, endpoint, ..., default_endpoint = "v1/studies") { if (inherits(endpoint, "AsIs")) { opts$host <- endpoint endpoint <- NULL default_endpoint <- NULL } if (is.null(opts$host)) stop("No host provided in `opts`: use a valid simulation options object or explicitly provide a host with opts = list(host = ...)") if (!is.null(opts$token) && opts$token != "") { config <- add_headers(Authorization = paste("Bearer ", opts$token), Accept = "application/json") } else { config <- add_headers(Accept = "application/json") } result <- PUT( url = URLencode(paste(c(opts$host, default_endpoint, endpoint), collapse = "/")), config, ... ) stop_for_status(result) content(result) } #' @export #' #' @rdname API-methods #' #' @importFrom httr DELETE accept_json stop_for_status content api_delete <- function(opts, endpoint, ..., default_endpoint = "v1/studies") { if (inherits(endpoint, "AsIs")) { opts$host <- endpoint endpoint <- NULL default_endpoint <- NULL } if (is.null(opts$host)) stop("No host provided in `opts`: use a valid simulation options object or explicitly provide a host with opts = list(host = ...)") config <- c( opts$httr_config, list( accept_json() ) ) if (!is.null(opts$token) && opts$token != "") { config <- c( config, add_headers(Authorization = paste("Bearer ", opts$token)) ) } result <- DELETE( url = URLencode(paste(c(opts$host, default_endpoint, endpoint), collapse = "/")), config = config, ... ) stop_for_status(result) content(result) }
d29addc45ad1540ad95c8544e8002562baf29435
d8affab3b21ca33c2b6397e28171c4ad69b03d98
/regression.R
471e4414ef889e20c3e50e5acbebf24faa2d7f99
[]
no_license
nupurkok/analytics
3e69e9eb88d9eb6cc4f33ae105b7993c46a69fce
b0b76dd306e443aae010cac55ffcda484c39ad42
refs/heads/master
2020-03-28T15:22:27.782000
2018-09-16T13:03:53
2018-09-16T13:03:53
148,586,169
0
0
null
null
null
null
UTF-8
R
false
false
546
r
regression.R
women str(women) cor(women$height, women$weight) cov(women$height, women$weight) plot(women) #create linear model fit1 = lm (formula=weight ~ height,data = women) summary(fit1) fitted(fit1) cbind(women, fitted(fit1), residuals(fit1)) ndata1 = data.frame(height = c(62.5, 63.5)) predict(fit1, newdata = ndata1) #multiple linear regression #predict mpg vs wt, hp mtcars fit2 = lm(mpg ~ wt + hp, data = mtcars) summary(fit2) range(mtcars$wt) ; range(mtcars$hp) ndata2=data.frame(wt=c(2.5,3.4), hp=c(100,250)) predict(fit2, newdata = ndata2)
46c4e6309d7e779524b8b1a79263f38885577650
ebb09f52b1ee12d8ae8d4c493e6f1079ee57868c
/ExploratoryDataAnalysis/Project2/plot1.R
344f1ab64d1fa16fc56bc45754d6205e3ffc4c86
[]
no_license
r6brian/datasciencecoursera
a1723f812a34eee7094dfaa0bfde6c618b349d6c
548944d3ba68d302160f05158fb90859bc4c8bae
refs/heads/master
2021-01-19T10:29:54.605000
2015-08-23T20:00:04
2015-08-23T20:00:04
26,268,379
0
0
null
null
null
null
UTF-8
R
false
false
634
r
plot1.R
# 1. Have total emissions from PM2.5 decreased in the United States from 1999 to 2008? # Read data files NEI <- readRDS("data/exdata-data-NEI_data/summarySCC_PM25.rds") SCC <- readRDS("data/exdata-data-NEI_data/Source_Classification_Code.rds") # aggregrate based upon Emissions and Years totalEmissions <- aggregate(Emissions ~ year, NEI, sum) # plot a bar graph png('plot1.png') barplot(height=totalEmissions$Emissions/10^6, names.arg=totalEmissions$year, xlab="years", ylab=expression('total PM'[2]*' emission(10^6 Tons)'), main=expression('Total PM'[2]*' emissions at various years')) dev.off()
d016bf7c1cea2be45570d0826610230b375be3ce
9bc17a169325375bc993b540d2ad0f0810ca0e76
/R/twoway.plots.R
a98edb8797477c8f6316b7dfb57853a3015db298
[]
no_license
alanarnholt/PASWR
335b960db32232a19d08560938d26f168e43b0d6
f11b56cff44d32c3683e29e15988b6a37ba8bfd4
refs/heads/master
2022-06-16T11:34:24.098000
2022-05-14T22:56:11
2022-05-14T22:56:11
52,523,116
2
1
null
null
null
null
UTF-8
R
false
false
1,375
r
twoway.plots.R
#' @title Exploratory Graphs for Two Factor Designs #' #' @description Function creates side-by-side boxplots for each factor, a design plot (means), and an interaction plot. #' #' @param Y response variable #' @param fac1 factor one #' @param fac2 factor two #' @param COL a vector with two colors #' #' @author Alan T. Arnholt <arnholtat@@appstate.edu> #' #' @seealso \code{\link{oneway.plots}}, \code{\link{checking.plots}} #' #' @export #' #' @examples #' with(data = TireWear, twoway.plots(Wear, Treat, Block)) #' #' @keywords hplot #################################################################### twoway.plots<-function(Y, fac1, fac2, COL=c("#A9E2FF", "#0080FF")){ opar <- par(no.readonly = TRUE) par(mfrow=c(2, 2), mar = c(5.1, 4.1, 1.1, 1.1)) YL <- range(Y) plot(Y ~ fac1, col = COL[1], xlab = deparse(substitute(fac1)), ylab = deparse(substitute(Y)), ylim = YL) plot(Y ~ fac2, col = COL[2], xlab = deparse(substitute(fac2)), ylab = deparse(substitute(Y)), ylim = YL) plot.design(Y ~ fac1 + fac2, fun = "mean", ylab = deparse(substitute(Y)), ylim = YL) interaction.plot(fac1, fac2, Y, xlab = deparse(substitute(fac1)), trace.label = deparse(substitute(fac2)), type = "b", legend = FALSE, ylab = deparse(substitute(Y)), ylim = YL) on.exit(par(opar)) }
b4e93e3bcccb0eb0d1014bd355bcfff5a5be6187
280019f481fe09da00296f45e5fa530051780756
/ui.R
10b50c14611abb664f6dbfc7ea4c164e2ac58b15
[]
no_license
linareja/2017_Buenos_Aires_Elections
1effb2b1d39bf660e9fa678a6a78ac3000f2122c
d500aaedb233fe541fe00dc63f0d488043467111
refs/heads/master
2021-09-12T16:33:33.715000
2018-04-18T18:19:56
2018-04-18T18:19:56
null
0
0
null
null
null
null
UTF-8
R
false
false
1,802
r
ui.R
library(shiny) dashboardPage( dashboardHeader(title = "2017 Elections in Buenos Aires Province"), dashboardSidebar( sidebarMenu( menuItem("Overview", tabName = "overview", icon = icon("globe")), menuItem("Analysis", tabName = "analysis", icon = icon("bar-chart")) )), dashboardBody( tabItems( tabItem("overview", fluidRow( column(6,selectInput("charge", "Select charge to visualize", levels(raw_data$variable)) )), fluidRow( column(6, h3("Overview")) ), fluidRow( column(6,drawMapUI("map1") ), column(6,drawTreeMapUI("treemap1") ) ), fluidRow( column(6, h3("Comparison")) ), fluidRow( column(6, selectInput("comparison_plot", "Select Comparison Plot", choices = c("Map", "Treemap"))) ), #Aca va a ir un selector para comparar por treemap o por mapa conditionalPanel("input.comparison_plot == 'Map'", fluidRow( column(6,drawMapUI("map_compare1",is.multiple = F)), column(6,drawMapUI("map_compare2",is.multiple = F)) ) ), conditionalPanel("input.comparison_plot == 'Treemap'", fluidRow( column(6,drawTreeMapUI("treemap_compare1",is.multiple = F)), column(6,drawTreeMapUI("treemap_compare2",is.multiple = F)) ) ) ), tabItem("analysis", drawHeatmapUI("heatmap")) ) ) )
564a95d83be7184c25e4953fc74f13401f3970ba
b6ed5857732c3261abab33a6665e7193d6862aef
/tests/testthat/test-read-oneshot-eav.R
d2b16cc13808d4cf760c57f846c793651568b48e
[ "MIT" ]
permissive
cran/REDCapR
5ac1ebdb03fbf7dfa1aab23a2c23f711adcd4847
a1aa09eb27fb627207255018fa41e30fa5d4b0fc
refs/heads/master
2022-08-27T14:49:33.798000
2022-08-10T15:10:18
2022-08-10T15:10:18
24,255,971
0
0
null
null
null
null
UTF-8
R
false
false
12,860
r
test-read-oneshot-eav.R
library(testthat) credential <- retrieve_credential_testing() update_expectation <- FALSE test_that("smoke test", { testthat::skip_on_cran() expect_message( returned_object <- REDCapR:::redcap_read_oneshot_eav(redcap_uri=credential$redcap_uri, token=credential$token) ) }) test_that("default", { testthat::skip_on_cran() path_expected <- "test-data/specific-redcapr/read-oneshot-eav/default.R" expected_outcome_message <- "\\d+ records and \\d+ columns were read from REDCap in \\d+(\\.\\d+\\W|\\W)seconds\\." expect_message( regexp = expected_outcome_message, returned_object <- REDCapR:::redcap_read_oneshot_eav( redcap_uri = credential$redcap_uri, token = credential$token ) ) if (update_expectation) save_expected(returned_object$data, path_expected) expected_data_frame <- retrieve_expected(path_expected) expect_equal(returned_object$data, expected=expected_data_frame) # dput(returned_object$data) expect_equal(returned_object$status_code, expected=200L) expect_equal(returned_object$raw_text, expected="", ignore_attr = TRUE) # dput(returned_object$raw_text) expect_true(returned_object$records_collapsed=="", "A subset of records was not requested.") expect_true(returned_object$fields_collapsed=="", "A subset of fields was not requested.") expect_true(returned_object$filter_logic=="", "A filter was not specified.") expect_match(returned_object$outcome_message, regexp=expected_outcome_message, perl=TRUE) expect_true(returned_object$success) }) test_that("specify-forms", { testthat::skip_on_cran() path_expected <- "test-data/specific-redcapr/read-oneshot-eav/specify-forms.R" desired_forms <- c("demographics", "race_and_ethnicity") expected_outcome_message <- "\\d+ records and \\d+ columns were read from REDCap in \\d+(\\.\\d+\\W|\\W)seconds\\." expect_message( regexp = expected_outcome_message, returned_object <- REDCapR:::redcap_read_oneshot_eav(redcap_uri=credential$redcap_uri, token=credential$token, forms=desired_forms) ) if (update_expectation) save_expected(returned_object$data, path_expected) expected_data_frame <- retrieve_expected(path_expected) expect_equal(returned_object$data, expected=expected_data_frame) # dput(returned_object$data) expect_equal(returned_object$status_code, expected=200L) expect_equal(returned_object$raw_text, expected="", ignore_attr = TRUE) # dput(returned_object$raw_text) expect_true(returned_object$records_collapsed=="", "A subset of records was not requested.") expect_true(returned_object$fields_collapsed=="", "A subset of fields was not requested.") expect_true(returned_object$filter_logic=="", "A filter was not specified.") expect_match(returned_object$outcome_message, regexp=expected_outcome_message, perl=TRUE) expect_true(returned_object$success) }) test_that("raw", { testthat::skip_on_cran() path_expected <- "test-data/specific-redcapr/read-oneshot-eav/raw.R" expected_outcome_message <- "\\d+ records and \\d+ columns were read from REDCap in \\d+(\\.\\d+\\W|\\W)seconds\\." expect_message( regexp = expected_outcome_message, returned_object <- REDCapR:::redcap_read_oneshot_eav(redcap_uri=credential$redcap_uri, token=credential$token, raw_or_label="raw") ) if (update_expectation) save_expected(returned_object$data, path_expected) expected_data_frame <- retrieve_expected(path_expected) expect_equal(returned_object$data, expected=expected_data_frame, label="The returned data.frame should be correct") # dput(returned_object$data) expect_equal(returned_object$status_code, expected=200L) expect_equal(returned_object$raw_text, expected="", ignore_attr = TRUE) # dput(returned_object$raw_text) expect_true(returned_object$records_collapsed=="", "A subset of records was not requested.") expect_true(returned_object$fields_collapsed=="", "A subset of fields was not requested.") expect_true(returned_object$filter_logic=="", "A filter was not specified.") expect_match(returned_object$outcome_message, regexp=expected_outcome_message, perl=TRUE) expect_true(returned_object$success) }) test_that("raw-and-dag", { testthat::skip_on_cran() path_expected <- "test-data/specific-redcapr/read-oneshot-eav/raw-and-dag.R" expected_outcome_message <- "\\d+ records and \\d+ columns were read from REDCap in \\d+(\\.\\d+\\W|\\W)seconds\\." expect_message( regexp = expected_outcome_message, returned_object <- REDCapR:::redcap_read_oneshot_eav(redcap_uri=credential$redcap_uri, token=credential$token, raw_or_label="raw", export_data_access_groups=TRUE) ) if (update_expectation) save_expected(returned_object$data, path_expected) expected_data_frame <- retrieve_expected(path_expected) expect_equal(returned_object$data, expected=expected_data_frame, label="The returned data.frame should be correct") # dput(returned_object$data) expect_equal(returned_object$status_code, expected=200L) expect_equal(returned_object$raw_text, expected="", ignore_attr = TRUE) # dput(returned_object$raw_text) expect_true(returned_object$records_collapsed=="", "A subset of records was not requested.") expect_true(returned_object$fields_collapsed=="", "A subset of fields was not requested.") expect_true(returned_object$filter_logic=="", "A filter was not specified.") expect_match(returned_object$outcome_message, regexp=expected_outcome_message, perl=TRUE) expect_true(returned_object$success) }) test_that("label-and-dag", { testthat::skip_on_cran() path_expected <- "test-data/specific-redcapr/read-oneshot-eav/label-and-dag.R" expected_outcome_message <- "\\d+ records and \\d+ columns were read from REDCap in \\d+(\\.\\d+\\W|\\W)seconds\\." expect_message( regexp = expected_outcome_message, returned_object <- REDCapR:::redcap_read_oneshot_eav(redcap_uri=credential$redcap_uri, token=credential$token, raw_or_label="label", export_data_access_groups=TRUE) ) if (update_expectation) save_expected(returned_object$data, path_expected) expected_data_frame <- retrieve_expected(path_expected) expect_equal(returned_object$data, expected=expected_data_frame, label="The returned data.frame should be correct") # dput(returned_object$data) expect_equal(returned_object$status_code, expected=200L) expect_equal(returned_object$raw_text, expected="", ignore_attr = TRUE) # dput(returned_object$raw_text) expect_true(returned_object$records_collapsed=="", "A subset of records was not requested.") expect_true(returned_object$fields_collapsed=="", "A subset of fields was not requested.") expect_true(returned_object$filter_logic=="", "A filter was not specified.") expect_match(returned_object$outcome_message, regexp=expected_outcome_message, perl=TRUE) expect_true(returned_object$success) }) test_that("label-header", { testthat::skip_on_cran() path_expected <- "test-data/specific-redcapr/read-oneshot-eav/label-header.R" expected_outcome_message <- "\\d+ records and \\d+ columns were read from REDCap in \\d+(\\.\\d+\\W|\\W)seconds\\." expect_message( regexp = expected_outcome_message, returned_object <- REDCapR:::redcap_read_oneshot_eav(redcap_uri=credential$redcap_uri, token=credential$token, raw_or_label_headers="label") ) if (update_expectation) save_expected(returned_object$data, path_expected) expected_data_frame <- retrieve_expected(path_expected) expect_equal(returned_object$data, expected=expected_data_frame, label="The returned data.frame should be correct", ignore_attr = TRUE) # dput(returned_object$data) expect_equal(returned_object$status_code, expected=200L) expect_equal(returned_object$raw_text, expected="", ignore_attr = TRUE) # dput(returned_object$raw_text) expect_true(returned_object$records_collapsed=="", "A subset of records was not requested.") expect_true(returned_object$fields_collapsed=="", "A subset of fields was not requested.") expect_true(returned_object$filter_logic=="", "A filter was not specified.") expect_match(returned_object$outcome_message, regexp=expected_outcome_message, perl=TRUE) expect_true(returned_object$success) }) test_that("filter-numeric", { testthat::skip_on_cran() path_expected <- "test-data/specific-redcapr/read-oneshot-eav/filter-numeric.R" expected_outcome_message <- "\\d+ records and \\d+ columns were read from REDCap in \\d+(\\.\\d+\\W|\\W)seconds\\." filter <- "[age] >= 61" expect_message( regexp = expected_outcome_message, returned_object <- REDCapR:::redcap_read_oneshot_eav(redcap_uri=credential$redcap_uri, token=credential$token, filter_logic=filter) ) if (update_expectation) save_expected(returned_object$data, path_expected) expected_data_frame <- retrieve_expected(path_expected) expect_equal(returned_object$data, expected=expected_data_frame, label="The returned data.frame should be correct") # dput(returned_object$data) expect_equal(returned_object$status_code, expected=200L) expect_equal(returned_object$raw_text, expected="", ignore_attr = TRUE) # dput(returned_object$raw_text) expect_true(returned_object$records_collapsed=="", "A subset of records was not requested.") expect_true(returned_object$fields_collapsed=="", "A subset of fields was not requested.") expect_equal(returned_object$filter_logic, filter) expect_match(returned_object$outcome_message, regexp=expected_outcome_message, perl=TRUE) expect_true(returned_object$success) }) test_that("filter-character", { testthat::skip_on_cran() path_expected <- "test-data/specific-redcapr/read-oneshot-eav/filter-character.R" if (update_expectation) save_expected(returned_object$data, path_expected) expected_data_frame <- retrieve_expected(path_expected) expected_outcome_message <- "\\d+ records and \\d+ columns were read from REDCap in \\d+(\\.\\d+\\W|\\W)seconds\\." filter <- "[name_first] = 'John Lee'" expect_message( regexp = expected_outcome_message, returned_object <- REDCapR:::redcap_read_oneshot_eav(redcap_uri=credential$redcap_uri, token=credential$token, filter_logic=filter) ) if (update_expectation) save_expected(returned_object$data, path_expected) expected_data_frame <- retrieve_expected(path_expected) expect_equal(returned_object$data, expected=expected_data_frame, label="The returned data.frame should be correct") # dput(returned_object$data) expect_equal(returned_object$status_code, expected=200L) expect_equal(returned_object$raw_text, expected="", ignore_attr = TRUE) # dput(returned_object$raw_text) expect_true(returned_object$records_collapsed=="", "A subset of records was not requested.") expect_true(returned_object$fields_collapsed=="", "A subset of fields was not requested.") expect_equal(returned_object$filter_logic, filter) expect_match(returned_object$outcome_message, regexp=expected_outcome_message, perl=TRUE) expect_true(returned_object$success) }) test_that("date-range", { testthat::skip_on_cran() path_expected <- "test-data/specific-redcapr/read-oneshot-eav/default.R" expected_outcome_message <- "\\d+ records and \\d+ columns were read from REDCap in \\d+(\\.\\d+\\W|\\W)seconds\\." start <- as.POSIXct(strptime("2018-08-01 03:00", "%Y-%m-%d %H:%M")) stop <- Sys.time() expect_message( regexp = expected_outcome_message, returned_object <- REDCapR:::redcap_read_oneshot_eav( redcap_uri = credential$redcap_uri, token = credential$token, datetime_range_begin = start, datetime_range_end = stop ) ) if (update_expectation) save_expected(returned_object$data, path_expected) expected_data_frame <- retrieve_expected(path_expected) expect_equal(returned_object$data, expected=expected_data_frame, label="The returned data.frame should be correct", ignore_attr = TRUE) # dput(returned_object$data) expect_equal(returned_object$status_code, expected=200L) expect_equal(returned_object$raw_text, expected="", ignore_attr = TRUE) # dput(returned_object$raw_text) expect_true(returned_object$records_collapsed=="", "A subset of records was not requested.") expect_true(returned_object$fields_collapsed=="", "A subset of fields was not requested.") expect_equal(returned_object$filter_logic, "") expect_match(returned_object$outcome_message, regexp=expected_outcome_message, perl=TRUE) expect_true(returned_object$success) }) test_that("bad token -Error", { testthat::skip_on_cran() expected_outcome_message <- "The REDCapR record export operation was not successful\\." expect_error( regexp = expected_outcome_message, REDCapR:::redcap_read_oneshot_eav( redcap_uri = credential$redcap_uri, token = "BAD00000000000000000000000000000" ) ) }) rm(credential)
ae049e4f7dded0c1877205b17e89aab67356d759
cf4263e82b2c118bc3ecea5dc62d561e7487cbd3
/tests/testthat/test_flatten_data.R
327e274c4b13ccbaaa4edf5a2d6be774fcc94394
[ "MIT" ]
permissive
EDIorg/ecocomDP
151a2d519ff740d466fafab74df5171a6ef196bf
0554d64ce81f35ed59985d9d991203d88fe1621f
refs/heads/main
2023-08-14T02:07:19.274000
2023-06-19T22:27:30
2023-06-19T22:27:30
94,339,321
26
10
NOASSERTION
2023-07-26T22:21:00
2017-06-14T14:22:43
R
UTF-8
R
false
false
7,103
r
test_flatten_data.R
context("flatten_data()") # Compare L0 flat and L1 flat - The column names and values of the L0 flat and L1 flattened tables should match, with an exception: # 1.) Primary keys, row identifiers, of the ancillary tables are now present. # Column presence ------------------------------------------------------------- testthat::test_that("Column presence", { for (i in c("df", "tbbl")) { # Parameterize if (i == "df") { # test w/data.frame L0_flat <- as.data.frame(ants_L0_flat) for (tbl in names(ants_L1$tables)) { ants_L1$tables[[tbl]] <- as.data.frame(ants_L1$tables[[tbl]]) } } else { # test w/tibble L0_flat <- ants_L0_flat } crit <- read_criteria() L1_flat <- flatten_data(ants_L1$tables) # Adjust L0 flat to our expectations L0_flat$location_name <- NA_character_ # Add exception # TEST: All L0 flat columns (with above exceptions) should be in L1 flat cols_missing_from_L1 <- base::setdiff(colnames(L0_flat), colnames(L1_flat)) expect_true(length(cols_missing_from_L1) == 0) # TEST: All L1 flat columns should be in L0 flat cols_missing_from_L0 <- base::setdiff(colnames(L1_flat), colnames(L0_flat)) expect_true(length(cols_missing_from_L0) == 0) } }) # Column classes -------------------------------------------------------------- testthat::test_that("Column classes", { for (i in c("df", "tbbl")) { # Parameterize if (i == "df") { # test w/data.frame L0_flat <- as.data.frame(ants_L0_flat) for (tbl in names(ants_L1$tables)) { ants_L1$tables[[tbl]] <- as.data.frame(ants_L1$tables[[tbl]]) } } else { # test w/tibble L0_flat <- ants_L0_flat } crit <- read_criteria() L1_flat <- flatten_data(ants_L1$tables) # TEST: flatten_data() applies a set of "smart" class coercions to return numeric values stored in the L1 as character back to their original numeric class. The following code tests that column classifications in L1 should be "similar" to those in L0. L0_classes <- unlist(lapply(L0_flat, class)) L1_classes <- unlist(lapply(L1_flat, class)) # Harmonize classes (because there is some variation) before comparing L0_classes[stringr::str_detect(names(L0_classes), "id")] <- "character" # identifiers should be character L1_classes[stringr::str_detect(names(L1_classes), "id")] <- "character" L0_classes[stringr::str_detect(L0_classes, "integer")] <- "numeric" # integer ~= numeric L1_classes[stringr::str_detect(L1_classes, "integer")] <- "numeric" # TEST: Compare col classes for (c in seq(L1_classes)) { col <- L1_classes[c] if (names(col) %in% names(L0_classes)) { use_i <- names(L0_classes) %in% names(col) if (any(use_i)) { expect_equal(L0_classes[use_i], col) } } } } }) # Observations (rows) match --------------------------------------------------- # TODO Implement this test? # testthat::test_that("Observations (rows) match", { # # Parameterize # crit <- read_criteria() # L0_flat <- ants_L0_flat # L1_flat <- ecocomDP::flatten_data(ants_L1$tables) # # Adjust L0 flat to our expectations # L0_flat <- L0_flat %>% # dplyr::select(-block) %>% # A higher level location lost when flattened # dplyr::select(-author) %>% # Columns of NA are dropped when flattened # dplyr::rename(location_name = plot) # Becomes "location_name" when flattened # # TEST: Observation "A" in L0 flat has the same values in observation "A" of L1 flat # # TODO observation_id are identical # # TODO match cols and sort, then compare (some subset?) # }) # Non-required columns -------------------------------------------------------- # Non-required columns of ecocomDP aren't required by flatten_data() testthat::test_that("Non-required columns", { for (i in c("df", "tbbl")) { # Parameterize if (i == "df") { # test w/data.frame for (tbl in names(ants_L1$tables)) { ants_L1$tables[[tbl]] <- as.data.frame(ants_L1$tables[[tbl]]) } } # Parameterize crit <- read_criteria() %>% dplyr::filter(required == TRUE, !is.na(column)) %>% dplyr::select(table, column) tbls <- ants_L1$tables # Throw out all non-required columns for (tname in names(tbls)) { rqd <- crit$column[crit$table %in% tname] tbls[[tname]] <- tbls[[tname]] %>% dplyr::select(dplyr::any_of(rqd)) } # TEST: Missing non-required columns isn't an issue L1_flat <- ecocomDP::flatten_data(tbls) cols_in <- unname(unlist(lapply(tbls, colnames))) cols_out <- colnames(L1_flat) dif <- base::setdiff(cols_in, cols_out) expect_equal(dif, # Difference is a set of cols that shouldn't be returned by anyway c("location_ancillary_id", "taxon_ancillary_id", "observation_ancillary_id", "variable_mapping_id", "table_name")) } }) # flatten_location() ---------------------------------------------------------- # location_name values are parsed into the original L0 column representation testthat::test_that("flatten_location(): No nesting", { loc <- tidyr::as_tibble( # A table demonstrating this use case data.frame( location_id = c("H1"), location_name = c("Highest__1"), latitude = 45, longitude = 123, elevation = 200, parent_location_id = NA_character_, stringsAsFactors = FALSE)) for (i in c("df", "tbbl")) { # Parameterize if (i == "df") { # test w/data.frame loc <- as.data.frame(loc) } # Parameterize res <- flatten_location(loc) loc_flat <- res$location_flat # TEST: Original columns of data are returned expect_true(all(c("Highest") %in% colnames(loc_flat))) # column names expect_equal(loc_flat$Highest, "1") # values } }) testthat::test_that("flatten_location(): 3 nested sites", { loc <- tidyr::as_tibble( # A table demonstrating this use case data.frame( location_id = c("H1", "M2", "L3"), location_name = c("Highest__1", "Middle__2", "Lowest__3"), latitude = c(NA, NA, 45), longitude = c(NA, NA, 123), elevation = c(NA, NA, 200), parent_location_id = c(NA_character_, "H1", "M2"), stringsAsFactors = FALSE)) for (i in c("df", "tbbl")) { # Parameterize if (i == "df") { # test w/data.frame loc <- as.data.frame(loc) } # Parameterize res <- flatten_location(loc) loc_flat <- res$location_flat # TEST: Original columns of data are returned expect_true(all(c("Highest", "Middle", "Lowest") %in% colnames(loc_flat))) # column names expect_equal(loc_flat$Highest, "1") # values expect_equal(loc_flat$Middle, "2") expect_equal(loc_flat$Lowest, "3") # TEST: Original columns are returned in the order of nesting expect_equal(which(colnames(loc_flat) %in% "Highest"), 3) expect_equal(which(colnames(loc_flat) %in% "Middle"), 4) expect_equal(which(colnames(loc_flat) %in% "Lowest"), 5) } })
8ce7a9d3e16bf2b520b938c008850a5ca1577fb8
92456ce1d280dd99f0df1cc2a2567c5021286f03
/R/prepare_data.R
5c8fabf25b3ad3505598af1c3c14f7a6948f57d1
[]
no_license
nzfarhad/AFG_MSNA_19_Analysis
41643620a065ff3eaba40779624101b55562efe4
66b4cfe032b7665475606dcab5eae4fcacba0e9c
refs/heads/master
2020-07-28T17:27:34.829000
2020-01-28T10:01:02
2020-01-28T10:01:02
209,478,936
0
2
null
null
null
null
UTF-8
R
false
false
100,120
r
prepare_data.R
# Title: Preparation of data for woa survey # Authors: Sayed Nabizada, Jarod Lapp, Christopher Jarvis, # Date created: 20/09/2019 # Date last changed: 25/09/2019 # Purpose: This script is for recoding variables in the whole of # of Afghanistan survey data # indicators and composite scores are created. # setup analysis environment source("./R/source.R") library(msni19) # character operation ch<-as.character chr<-as.character coerc<-function(x){as.numeric(chr(x))} # load data # data <- read_excel(master_data, sheet = "MSNA_AFG_19_parent_sheet", na = c("","NA"), guess_max = 3000) # overall_muac_data <- read_excel(master_data, sheet = "MSNA_AFG_19_muac" , na = c("","NA")) # overall_hh_roster <- read_excel(master_data, sheet = "MSNA_AFG_19_hh_roster" , na = c("","NA")) # overall_death_roster <- read_excel(master_data, sheet = "MSNA_AFG_19_hh_death_roster" , na = c("","NA")) # overall_left_roster <- read_excel( master_data, sheet = "MSNA_AFG_19_hh_left_roster" , na = c("","NA")) # data <- read.csv("input/data/clean/MSNA_AFG_19_parent_sheet.csv",stringsAsFactors=F,na.strings = c("", "NA"), check.names = F) # overall_muac_data <- read.csv("input/data/clean/MSNA_AFG_19_muac.csv",stringsAsFactors=F,na.strings = c("", "NA"), check.names = F) # overall_hh_roster <- read.csv("input/data/clean/MSNA_AFG_19_hh_roster.csv",stringsAsFactors=F,na.strings = c("", "NA"), check.names = F) # overall_death_roster <- read.csv("input/data/clean/MSNA_AFG_19_hh_death_roster.csv",stringsAsFactors=F,na.strings = c("", "NA"), check.names = F) # overall_left_roster <- read.csv("input/data/clean/MSNA_AFG_19_hh_left_roster.csv",stringsAsFactors=F,na.strings = c("", "NA"), check.names = F) # data <- read.csv("input/data/clean/complete_with_farah/MSNA_AFG_19_parent_sheet.csv",stringsAsFactors=F,na.strings = c("", "NA"), check.names = F) overall_muac_data <- read.csv("input/data/clean/complete_with_farah/MSNA_AFG_19_muac.csv",stringsAsFactors=F,na.strings = c("", "NA"), check.names = F) overall_hh_roster <- read.csv("input/data/clean/complete_with_farah/MSNA_AFG_19_hh_roster.csv",stringsAsFactors=F,na.strings = c("", "NA"), check.names = F) overall_death_roster <- read.csv("input/data/clean/complete_with_farah/MSNA_AFG_19_hh_death_roster.csv",stringsAsFactors=F,na.strings = c("", "NA"), check.names = F) overall_left_roster <- read.csv("input/data/clean/complete_with_farah/MSNA_AFG_19_hh_left_roster.csv",stringsAsFactors=F,na.strings = c("", "NA"), check.names = F) # Temp for the data is exported out of kobo incorrectly. rename1 <- function(d1) { sub("/", ".", names(d1)) } data$uuid <- data$`_uuid` names(data) <- rename1(data) names(overall_muac_data ) <- rename1(overall_muac_data ) names(overall_hh_roster ) <- rename1(overall_hh_roster ) names(overall_death_roster ) <- rename1(overall_death_roster) names(overall_left_roster ) <- rename1(overall_left_roster) # composite indicators # # The composite indicators are a combination of different variables # each value within a variable has a score and these need to be # coded for the different categories. # Then the variables can be summed in order to get the score # This will be done for multiple sectors. #### Composite indicators ############ ### Food Security & Agriculture #### # FCS data <- data %>% mutate( # FCS fcs_category_class = recode( fcs_category, "poor" = 4, "borderline" = 2, "acceptable" = 0 ), # HHS hhs_category_class = recode( hhs_category, "severe_hunger" = 4, "moderate_hunger" = 2, "little_hunger" = 0 ), # Food Source food_source_class = case_when( food_source %in% c('gift', 'assistance') ~ 2, food_source == 'borrowed' ~1, TRUE ~ 0 ), # ag impact ag_impact_class = case_when( agricultural_impact_how == '76_100' ~ 3, agricultural_impact_how == '51_75' ~ 1, agricultural_impact %in% c('no', 'not_applicable') ~ 0, agricultural_impact_how %in% c('0_25', '26_50' ) ~ 0 ), # livestock impact ls_impact_class = case_when( livestock_impact_how.livestock_died == 1 | livestock_impact_how.left_unattended == 1 ~ 2, livestock_impact_how.livestock_ill == 1 | livestock_impact_how.less_milk == 1 ~ 1, livestock_impact == 0 ~ 0, TRUE ~ 0, is.na(livestock_impact) ~ NA_real_ ) ) fsac_vars <- c("fcs_category_class", "hhs_category_class", "food_source_class", "ag_impact_class", "ls_impact_class") data$fsac_score <- comp_score(data, fsac_vars) data <- data %>% mutate( fsac_severity = case_when( fsac_score <= 2 ~ 1, fsac_score <= 5 ~ 2, fsac_score <= 8 ~ 3, fsac_score <= 16 ~ 4 ), fsac_sev_high = case_when( fsac_severity <= 2 ~ 0, fsac_severity <= 4 ~ 1 ) ) ################################################################## ### Protection #### # First setup the variables required to calculate the indicators and then calculate them # This way around if the weights are changed then it's all in one place. # protection incidents severe_prot_incidents_vars <- c( "adult_prot_incidents.assaulted_with_weapon", "child_prot_incidents.assaulted_with_weapon", "adult_prot_incidents.forced_work", "child_prot_incidents.forced_work", "adult_prot_incidents.forcibly_detained", "child_prot_incidents.forcibly_detained", "adult_prot_incidents.hindered_leave_settlement", "child_prot_incidents.hindered_leave_settlement", #### added from less_severe_prot_incidents "adult_prot_incidents.verbally_threatened", "child_prot_incidents.verbally_threatened", "adult_prot_incidents.assaulted_without_weapon", "child_prot_incidents.assaulted_without_weapon", "adult_prot_incidents.hindered_leave_district", "child_prot_incidents.hindered_leave_district" ) # less_severe_prot_incidents_vars <-c( # "adult_prot_incidents.verbally_threatened", # "child_prot_incidents.verbally_threatened", # "adult_prot_incidents.assaulted_without_weapon", # "child_prot_incidents.assaulted_without_weapon", # "adult_prot_incidents.hindered_leave_district", # "child_prot_incidents.hindered_leave_district" # ) data$severe_prot_incidents <- comp_score(data, severe_prot_incidents_vars) # data$less_severe_prot_incidents <- comp_score(data, less_severe_prot_incidents_vars) # protection concerns severe_prot_concerns_vars <- c( "prot_concerns.violence_maiming", "prot_concerns.abduction", "prot_concerns.explosive_hazards", "prot_concerns.psych_wellbeing", # added from less_severe_prot_concern "prot_concerns.violence_injuries", "prot_concerns.early_marriage", "prot_concerns.destruction_property", "prot_concerns.theft" ) # less_severe_prot_concerns_vars <- c( # "prot_concerns.violence_injuries", # "prot_concerns.early_marriage", # "prot_concerns.destruction_property", # "prot_concerns.theft" # ) data$severe_prot_concerns <- comp_score(data, severe_prot_concerns_vars) # data$less_severe_prot_concerns <- comp_score(data, less_severe_prot_concerns_vars) # explosive hazards severe_explosive_hazards_vars <- c( "explosive_impact.injury_death", "explosive_impact.access_services", "explosive_impact.relocation", "explosive_impact.livelihoods_impact", "explosive_impact.psych_impact" ) less_severe_explosive_hazards_vars <- c( "explosive_impact.restrict_recreation" ) data$severe_explosive_hazards <- comp_score(data, severe_explosive_hazards_vars) data$less_severe_explosive_hazards <- comp_score(data, less_severe_explosive_hazards_vars) # tazkira tazkira_total_vars <- c( "adult_tazkira", "child_tazkira") data$tazkira_total <- comp_score(data, tazkira_total_vars) children_working_yes_no_2 = case_when( data$children_working == 0 ~ "0", data$children_working >= 1 ~ "1 or more", TRUE ~ NA_character_ ) # Protection Severity Score ## Weights data <- data %>% mutate( prot_incident_class = case_when( severe_prot_incidents >= 1 ~ 3, # severe_prot_incidents == 0 & data$less_severe_prot_incidents >= 1 ~ 2, TRUE ~ 0), # violence targeting women, girls, boys sgbv_incidents_class = case_when( other_incidents.sgbv == 1 | other_concerns.sgbv == 1 ~ 2, TRUE ~ 0 ), # children working unsafe conditions children_work_safety_class = case_when( children_working_yes_no_2 =='1 or more' ~ 1, TRUE ~ 0 ), prot_concerns_class = case_when( severe_prot_concerns >= 1 ~ 3, # severe_prot_concerns == 0 & data$less_severe_prot_concerns >= 1 ~ 2, TRUE ~ 0 ), # hh members injured conflict or nat disaster injuries_class = case_when( adult_injuries_cause %in% c('conflict', 'natural_disaster') | child_injuries_cause %in% c('conflict', 'natural_disaster') ~ 3, TRUE ~ 0 ), prot_explosive_hazards_class = case_when( severe_explosive_hazards >= 1 ~ 3, severe_explosive_hazards == 0 & less_severe_explosive_hazards >=1 ~ 2, TRUE ~ 0 ), tazkira_class = case_when( tazkira_total == 0 ~ 2, tazkira_total > 0 & tazkira_total < hh_size ~ 1 ) ) # Score prot_score_vars <- c( "prot_incident_class", "sgbv_incidents_class", "children_work_safety_class", "prot_concerns_class", "injuries_class", "prot_explosive_hazards_class", "tazkira_class") data$prot_score <- comp_score(data, prot_score_vars) data <- data %>% mutate( prot_severity = case_when( prot_score <= 2 ~ 1, prot_score <= 5 ~ 2, prot_score <= 8 ~ 3, prot_score <= 18 ~ 4 ), prot_sev_high = case_when( prot_severity >= 3 ~ 1, TRUE ~ 0 ) ) ################## protection new indicator 1 ###################### prot_all_indictors <- c( "adult_prot_incidents.verbally_threatened", "adult_prot_incidents.assaulted_without_weapon", "adult_prot_incidents.assaulted_with_weapon", "adult_prot_incidents.hindered_leave_settlement", "adult_prot_incidents.hindered_leave_district", "adult_prot_incidents.forced_work", "adult_prot_incidents.forcibly_detained", "child_prot_incidents.verbally_threatened", "child_prot_incidents.assaulted_without_weapon", "child_prot_incidents.assaulted_with_weapon", "child_prot_incidents.hindered_leave_settlement", "child_prot_incidents.hindered_leave_district", "child_prot_incidents.forced_work", "child_prot_incidents.forcibly_detained", "other_incidents.sgbv", "other_incidents.other", "prot_concerns.violence_maiming", "prot_concerns.violence_injuries", "prot_concerns.psych_wellbeing", "prot_concerns.abduction", "prot_concerns.theft", "prot_concerns.explosive_hazards", "prot_concerns.destruction_property", "prot_concerns.early_marriage", "prot_concerns.other", "other_concerns.sgbv", "other_concerns.other" ) data$prot_all_indictors_score <- comp_score(data, prot_all_indictors) data <- data %>% mutate( prot_new_indicator_1 = case_when( prot_all_indictors_score >= 1 ~ ">=1", prot_all_indictors_score == 0 ~ "0", TRUE ~ NA_character_ ) ) ################## protection new indicator 2 ###################### data <- data %>% mutate( displ_explosive_presence_na_to_0 = case_when( displ_explosive_presence == "both" ~ 1, displ_explosive_presence == "current" ~ 1, displ_explosive_presence == "previous" ~ 1, displ_explosive_presence == "no" ~ 0, TRUE ~ 0 ) ) prot_all_indictors_2 <- c( "adult_prot_incidents.verbally_threatened", "adult_prot_incidents.assaulted_without_weapon", "adult_prot_incidents.assaulted_with_weapon", "adult_prot_incidents.hindered_leave_settlement", "adult_prot_incidents.hindered_leave_district", "adult_prot_incidents.forced_work", "adult_prot_incidents.forcibly_detained", "child_prot_incidents.verbally_threatened", "child_prot_incidents.assaulted_without_weapon", "child_prot_incidents.assaulted_with_weapon", "child_prot_incidents.hindered_leave_settlement", "child_prot_incidents.hindered_leave_district", "child_prot_incidents.forced_work", "child_prot_incidents.forcibly_detained", "other_incidents.sgbv", "other_incidents.other", "prot_concerns.violence_maiming", "prot_concerns.violence_injuries", "prot_concerns.psych_wellbeing", "prot_concerns.abduction", "prot_concerns.theft", "prot_concerns.explosive_hazards", "prot_concerns.destruction_property", "prot_concerns.early_marriage", "prot_concerns.other", "other_concerns.sgbv", "other_concerns.other", "displ_explosive_presence_na_to_0" ) data$prot_all_indictors_score_2 <- comp_score(data, prot_all_indictors_2) data <- data %>% mutate( prot_new_indicator_2 = case_when( prot_all_indictors_score_2 >= 1 ~ ">=1", prot_all_indictors_score_2 == 0 ~ "0", TRUE ~ NA_character_ ) ) ################## protection new indicator 3 ###################### data <- data %>% mutate( nondispl_explosive_presence_na_to_0 = case_when( nondispl_explosive_presence == "yes" ~ 1, nondispl_explosive_presence == "no" ~ 0, TRUE ~ 0 ) ) prot_all_indictors_3 <- c( "adult_prot_incidents.verbally_threatened", "adult_prot_incidents.assaulted_without_weapon", "adult_prot_incidents.assaulted_with_weapon", "adult_prot_incidents.hindered_leave_settlement", "adult_prot_incidents.hindered_leave_district", "adult_prot_incidents.forced_work", "adult_prot_incidents.forcibly_detained", "child_prot_incidents.verbally_threatened", "child_prot_incidents.assaulted_without_weapon", "child_prot_incidents.assaulted_with_weapon", "child_prot_incidents.hindered_leave_settlement", "child_prot_incidents.hindered_leave_district", "child_prot_incidents.forced_work", "child_prot_incidents.forcibly_detained", "other_incidents.sgbv", "other_incidents.other", "prot_concerns.violence_maiming", "prot_concerns.violence_injuries", "prot_concerns.psych_wellbeing", "prot_concerns.abduction", "prot_concerns.theft", "prot_concerns.explosive_hazards", "prot_concerns.destruction_property", "prot_concerns.early_marriage", "prot_concerns.other", "other_concerns.sgbv", "other_concerns.other", "displ_explosive_presence_na_to_0", "nondispl_explosive_presence_na_to_0" ) data$prot_all_indictors_score_3 <- comp_score(data, prot_all_indictors_3) data <- data %>% mutate( prot_new_indicator_3 = case_when( prot_all_indictors_score_3 >= 1 ~ ">=1", prot_all_indictors_score_3 == 0 ~ "0", TRUE ~ NA_character_ ) ) ################## protection new indicator 4 ###################### data <- data %>% mutate( lcsi_category_class2 = case_when( lcsi_category == "food_secure" | lcsi_category == "marginally_insecure" ~ 0, lcsi_category == "moderately_insecure" | lcsi_category == "severely_insecure" ~ 1, TRUE ~ 0 ) ) prot_all_indictors_4 <- c( "adult_prot_incidents.verbally_threatened", "adult_prot_incidents.assaulted_without_weapon", "adult_prot_incidents.assaulted_with_weapon", "adult_prot_incidents.hindered_leave_settlement", "adult_prot_incidents.hindered_leave_district", "adult_prot_incidents.forced_work", "adult_prot_incidents.forcibly_detained", "child_prot_incidents.verbally_threatened", "child_prot_incidents.assaulted_without_weapon", "child_prot_incidents.assaulted_with_weapon", "child_prot_incidents.hindered_leave_settlement", "child_prot_incidents.hindered_leave_district", "child_prot_incidents.forced_work", "child_prot_incidents.forcibly_detained", "other_incidents.sgbv", "other_incidents.other", "prot_concerns.violence_maiming", "prot_concerns.violence_injuries", "prot_concerns.psych_wellbeing", "prot_concerns.abduction", "prot_concerns.theft", "prot_concerns.explosive_hazards", "prot_concerns.destruction_property", "prot_concerns.early_marriage", "prot_concerns.other", "other_concerns.sgbv", "other_concerns.other", "displ_explosive_presence_na_to_0", "nondispl_explosive_presence_na_to_0", "lcsi_category_class2" ) data$prot_all_indictors_score_4 <- comp_score(data, prot_all_indictors_4) data <- data %>% mutate( prot_new_indicator_4 = case_when( prot_all_indictors_score_4 >= 1 ~ ">=1", prot_all_indictors_score_4 == 0 ~ "0", TRUE ~ NA_character_ ) ) ################################################################# ################## protection new indicator 5 ###################### prot_all_indictors_5 <- c( "adult_prot_incidents.verbally_threatened", "adult_prot_incidents.assaulted_without_weapon", "adult_prot_incidents.assaulted_with_weapon", "adult_prot_incidents.hindered_leave_settlement", "adult_prot_incidents.hindered_leave_district", "adult_prot_incidents.forced_work", "adult_prot_incidents.forcibly_detained", "child_prot_incidents.verbally_threatened", "child_prot_incidents.assaulted_without_weapon", "child_prot_incidents.assaulted_with_weapon", "child_prot_incidents.hindered_leave_settlement", "child_prot_incidents.hindered_leave_district", "child_prot_incidents.forced_work", "child_prot_incidents.forcibly_detained", "other_incidents.sgbv", "other_incidents.other", "prot_concerns.violence_maiming", "prot_concerns.violence_injuries", "prot_concerns.psych_wellbeing", "prot_concerns.abduction", "prot_concerns.theft", "prot_concerns.explosive_hazards", "prot_concerns.destruction_property", "prot_concerns.early_marriage", "prot_concerns.other", "other_concerns.sgbv", "other_concerns.other", "displ_explosive_presence_na_to_0", "nondispl_explosive_presence_na_to_0", "lcsi_category_class2", "children_work_safety_class" ) data$prot_all_indictors_score_5 <- comp_score(data, prot_all_indictors_5) data <- data %>% mutate( prot_new_indicator_5 = case_when( prot_all_indictors_score_5 >= 1 ~ ">=1", prot_all_indictors_score_5 == 0 ~ "0", TRUE ~ NA_character_ ) ) ################## protection new indicator 6 ###################### data <- data %>% mutate( other_impact_class = case_when( other_impact.injury_death == 1 | other_impact.new_mines == 1 ~ 1, TRUE ~ 0 ) ) prot_all_indictors_6 <- c( "adult_prot_incidents.verbally_threatened", "adult_prot_incidents.assaulted_without_weapon", "adult_prot_incidents.assaulted_with_weapon", "adult_prot_incidents.hindered_leave_settlement", "adult_prot_incidents.hindered_leave_district", "adult_prot_incidents.forced_work", "adult_prot_incidents.forcibly_detained", "child_prot_incidents.verbally_threatened", "child_prot_incidents.assaulted_without_weapon", "child_prot_incidents.assaulted_with_weapon", "child_prot_incidents.hindered_leave_settlement", "child_prot_incidents.hindered_leave_district", "child_prot_incidents.forced_work", "child_prot_incidents.forcibly_detained", "other_incidents.sgbv", "other_incidents.other", "prot_concerns.violence_maiming", "prot_concerns.violence_injuries", "prot_concerns.psych_wellbeing", "prot_concerns.abduction", "prot_concerns.theft", "prot_concerns.explosive_hazards", "prot_concerns.destruction_property", "prot_concerns.early_marriage", "prot_concerns.other", "other_concerns.sgbv", "other_concerns.other", "displ_explosive_presence_na_to_0", "nondispl_explosive_presence_na_to_0", "lcsi_category_class2", "other_impact_class" ) data$prot_all_indictors_score_6 <- comp_score(data, prot_all_indictors_6) data <- data %>% mutate( prot_new_indicator_6 = case_when( prot_all_indictors_score_6 >= 1 ~ ">=1", prot_all_indictors_score_6 == 0 ~ "0", TRUE ~ NA_character_ ) ) ###################################################end ### ESNFI #### # shelter type data$shelter_class<-ifelse(data$shelter == 'open_space',3,ifelse(data$shelter == 'tent' | data$shelter == 'makeshift_shelter' | data$shelter == 'collective_centre' | data$shelter == 'transitional',2,0)) # shelter damage data$shelter_damage_class<-ifelse(data$shelter_damage_extent== 'fully_destroyed' & data$shelter_damage_repair == 'no',3, ifelse(data$shelter_damage_extent== 'significant_damage' & data$shelter_damage_repair == 'no',2, ifelse(data$shelter_damage_extent== 'partial_damage' & data$shelter_damage_repair == 'no',1,0))) data$shelter_damage_class[is.na(data$shelter_damage_class)] <- 0 # TENENCY AGREEMENT data$tenancy_class<-ifelse(data$tenancy == 'unofficial',3,ifelse(data$tenancy == 'own_home_without_doc' | data$tenancy == 'rental_verbal' | data$shelter_hosted == 'yes',2,0)) data$tenancy_class[is.na(data$tenancy_class)] <- 0 # blankets data$blankets_class<-ifelse(data$blankets_number > data$hh_size,3,0) data$blankets_class[is.na(data$blankets_class)] <- 0 # basic needs data$sleeping_mats <- car::recode(data$sleeping_mats, " 'yes' = 1; 'no' = 0") data$tarpaulin <- car::recode(data$tarpaulin, " 'yes' = 1; 'no' = 0") data$cooking_pots <- car::recode(data$cooking_pots, " 'yes' = 1; 'no' = 0") data$stainless_steel <- car::recode(data$stainless_steel, " 'yes' = 1; 'no' = 0") data$water_storage <- car::recode(data$water_storage, " 'yes' = 1; 'no' = 0") data$hygiene_sanitation <- car::recode(data$hygiene_sanitation, " 'yes' = 1; 'no' = 0") data$basic_needs_total<-coerc(data[["sleeping_mats"]])+coerc(data[["tarpaulin"]])+coerc(data[["cooking_pots"]])+coerc(data[["stainless_steel"]])+coerc(data[["water_storage"]])+coerc(data[["hygiene_sanitation"]]) data$basic_needs_score<-car::recode(data$basic_needs_total, "0:2=3; 3:5=2; 6=0") # ESNFI Severity Score data$esnfi_score<-coerc(data[["shelter_class"]])+coerc(data[["shelter_damage_class"]])+coerc(data[["tenancy_class"]])+coerc(data[["blankets_class"]])+coerc(data[["basic_needs_score"]]) data$esnfi_severity<-car::recode(data$esnfi_score, "0:2='1'; 3:6='2'; 7:9='3'; 10:16='4'") data$esnfi_sev_high<-ifelse(data$esnfi_severity==3|data$esnfi_severity==4,1,0) ###################################################end ### <3 <3 <3 <3 <3 ESNFI 4 ARI <3 <3 <3 <3 <3 #### # shelter type data$shelter_class_4_ari<-case_when(data$shelter == 'open_space'| data$shelter == 'tent' | data$shelter == 'makeshift_shelter'| data$shelter == 'collective_centre' ~3, data$shelter == 'transitional'~2, data$shelter=='permanent' & (data$shelter_hosted_why =='cash_rent'| data$shelter_hosted_why =='trans_shelter_host_family'| data$shelter_hosted_why =='materials_tools_extend') ~2, TRUE~ 0) # shelter damage data$shelter_damage_class_4_ari<-ifelse(data$shelter_damage_extent== 'fully_destroyed' & data$shelter_damage_repair == 'no',3, ifelse(data$shelter_damage_extent== 'significant_damage' & data$shelter_damage_repair == 'no',2, ifelse(data$shelter_damage_extent== 'partial_damage' & data$shelter_damage_repair == 'no',1,0))) data$shelter_damage_class_4_ari[is.na(data$shelter_damage_class_4_ari)] <- 0 # TENENCY AGREEMENT data$tenancy_class_4_ari<-ifelse(data$tenancy == 'unofficial',3,ifelse(data$tenancy == 'own_home_without_doc' | data$tenancy == 'rental_verbal' | data$shelter_hosted == 'yes',2,0)) data$tenancy_class_4_ari[is.na(data$tenancy_class_4_ari)] <- 0 # ESNFI Severity Score data$esnfi_score_4_ari<-coerc(data[["shelter_class_4_ari"]])+coerc(data[["shelter_damage_class_4_ari"]])+coerc(data[["tenancy_class_4_ari"]]) data$esnfi_severity_4_ari<-car::recode(data$esnfi_score_4_ari, "0:2='1'; 3:4='2'; 5:6='3'; 7:10='4'") data$esnfi_sev_high_4_ari<-ifelse(data$esnfi_severity_4_ari==3|data$esnfi_severity_4_ari==4,1,0) ################################################################# ### WASH #### # water source # data$water_source_class<-car::recode(data$water_source, "'surface_water'=3; 'water_trucking'=2; 'spring_unprotected'=2; 'spring_protected'=0; 'handpump_private'=0; 'handpump_public'=0; 'piped_public'=0; 'other'=0") # water barriers data$water_barriers_class<-ifelse(data$water_sufficiency== 'insufficient' & (data$water_barriers== 'too_far' | data$water_barriers== 'high_risk' | data$water_barriers== 'social_restrictions'), 3,ifelse(data$water_sufficiency== 'insufficient',2, ifelse(data$water_sufficiency== 'barely_sufficient',1,0))) data$water_barriers_class[is.na(data$water_barriers)] <- 0 # soap data$soap_class<-ifelse(data$soap == 'yes_didnt_see' | data$soap == 'no', 1,0) # latrines # data$latrine_class<-ifelse(data$latrine == 'open' | data$latrine == 'public_latrine', 3, ifelse(data$latrine == 'pit_latrine_uncovered',2,0)) # primary waste dispopsal # data$waste_disposal_class<-ifelse(data$waste_disposal == 'open_space' | data$waste_disposal == 'burning', 2,0) #distance to primary water source data$water_distance_class<-ifelse(data$water_distance == 'over_1km'| data$water_distance == '500m_to_1km',3,0) # WASH Severity Score data$wash_score<-coerc(data[["water_source_class"]])+coerc(data[["water_barriers_class"]])+coerc(data[["soap_class"]])+coerc(data[["latrine_class"]])+coerc(data[["waste_disposal_class"]])+coerc(data[["water_distance_class"]]) data$wash_severity<-car::recode(data$wash_score, "0:2='1'; 3:5='2'; 6:8='3'; 9:16='4'") data$wash_sev_high<-ifelse(data$wash_severity==3|data$wash_severity==4,1,0) ################################################################# ### Nutrition #### muac_presence_analysis<-overall_muac_data %>% group_by(`_submission__uuid`) %>% filter(person_muac>=1) %>% summarize(number_muac_person=sum(person_muac), number_muac_mod_mal=sum(moderate_malnutrition), number_muac_sev_mal=sum(severe_malnutrition), number_muac_above_125 = sum(muac_measurement>=125, na.rm = T), min_muac=min(muac_measurement), ruft_reception_num = sum(rutf_reception== "yes"), ruft_reception = sum(rutf_reception== "yes")>=1) # Malnutrition present = 1, not present = 0 muac_presence_analysis$malnutrition_present<-ifelse(muac_presence_analysis$number_muac_mod_mal>=1 | muac_presence_analysis$number_muac_sev_mal>=1,1,0) # join with parent table data<-full_join(data, muac_presence_analysis, by = c("uuid"="_submission__uuid")) # reported malnourishment (mod & sev muac) data$muac_score<-ifelse(data$number_muac_sev_mal>1,7,ifelse(data$number_muac_sev_mal==1,6,ifelse(data$number_muac_sev_mal==0 & data$number_muac_mod_mal>1,4,ifelse(data$number_muac_sev_mal==0 & data$number_muac_mod_mal==1,3,0)))) # dietary diversity --- # therefore nutrition compotite indicator will exclude hhs with children aged 2-5, since this they are not asked this question ### data$dietary_div_count<-coerc(data[["minimum_dietary_diversity.staples"]])+coerc(data[["minimum_dietary_diversity.legumes"]])+coerc(data[["minimum_dietary_diversity.dairy"]])+coerc(data[["minimum_dietary_diversity.meat"]])+coerc(data[["minimum_dietary_diversity.eggs"]])+coerc(data[["minimum_dietary_diversity.vitamin_a_veg"]])+coerc(data[["minimum_dietary_diversity.other_veg"]]) data$dietary_div_score<-ifelse(data$dietary_div_count==0,4,ifelse(data$dietary_div_count==1,3,ifelse(data$dietary_div_count==2,2,ifelse(data$dietary_div_count==3,1,0)))) data$dietary_div_score[is.na(data$dietary_div_score)] <- 0 # Nutrition Severity Score data$nut_score_hh_w_muac<-coerc(data[["muac_score"]])+coerc(data[["dietary_div_score"]]) data$nut_score<-data$nut_score_hh_w_muac data$nut_score[is.na(data$nut_score)] <- 0 data$nut_severity<-car::recode(data$nut_score, "0:2='1'; 3:5='2'; 6:8='3'; 9:16='4'") # data$nut_sev_high<-ifelse(data$nut_severity==3|data$nut_severity==4,1,0) data$nut_sev_high<-ifelse(data$nut_severity==3|data$nut_severity==4 | data$nut_severity==2 ,1,0) ################################################################# ### Education EiE #### education_analysis<-overall_hh_roster %>% filter(!is.na(current_year_enrolled)) education_analysis$enrolled_and_attending<-ifelse(education_analysis$current_year_enrolled=='no',0, ifelse(education_analysis$current_year_enrolled=='yes' & education_analysis$current_year_attending=='no',0,1)) education_analysis$total_schoolage_child<-1 #removal from school due to shock education_analysis$shock_presence<-coerc(education_analysis[["edu_removal_shock.displacement"]])+coerc(education_analysis[["edu_removal_shock.conflict"]])+coerc(education_analysis[["edu_removal_shock.natural_disaster"]]) education_analysis$shock_presence[is.na(education_analysis$shock_presence)] <- 0 ################## not part of composite ################################################# education_analysis$enrolled_1 <- if_else(education_analysis$current_year_enrolled=='no',0,1) education_analysis$attending_1 <- if_else(education_analysis$current_year_attending=='no',0,1) education_analysis <- education_analysis %>% mutate( attending_male = case_when( current_year_attending == "yes" & hh_member_sex == "male" ~ 1, TRUE ~ 0 ), attending_female = case_when( current_year_attending == "yes" & hh_member_sex == "female" ~ 1, TRUE ~ 0 ), enrolled_male = case_when( current_year_enrolled == "yes" & hh_member_sex == "male" ~ 1, TRUE ~ 0 ), enrolled_female = case_when( current_year_enrolled == "yes" & hh_member_sex == "female" ~ 1, TRUE ~ 0 ), shock_presence_male = case_when( shock_presence > 0 & hh_member_sex == "male" ~ 1, TRUE ~ 0 ), shock_presence_female = case_when( shock_presence > 0 & hh_member_sex == "female" ~ 1, TRUE ~ 0 ) ) #################################################################################### # group dataset into hh education_analysis_hh<-education_analysis %>% group_by(`_submission__uuid`) %>% summarize(count_school_child=sum(total_schoolage_child), count_enrolled_attending=sum(enrolled_and_attending), count_current_enrolled = sum(enrolled_1, na.rm = T), count_current_enrolled_male = sum(enrolled_male, na.rm = T), count_current_enrolled_female = sum(enrolled_female, na.rm = T), count_current_attending = sum(attending_1, na.rm = T), count_current_attending_male = sum(attending_male, na.rm = T), count_current_attending_female = sum(attending_female, na.rm = T), count_shock=sum(shock_presence), count_shock_male = sum(shock_presence_male, na.rm = T), count_shock_female = sum(shock_presence_female, na.rm = T) ) # shock weight education_analysis_hh$shock_class<-ifelse(education_analysis_hh$count_shock >= 1, 5,0) # percent children enrolled or attending education_analysis_hh$percent_enrolled= coerc(education_analysis_hh[["count_enrolled_attending"]])/coerc(education_analysis_hh[["count_school_child"]]) education_analysis_hh$enroll_perc_class<-car::recode(education_analysis_hh$percent_enrolled, "0:0.249=1; 0.25:0.499=2; 0.5:0.749=3; 0.75:1=4") # greater than 3 children not attending education_analysis_hh$count_not_enrolled<-coerc(education_analysis_hh[["count_school_child"]])-coerc(education_analysis_hh[["count_enrolled_attending"]]) education_analysis_hh$count_not_enrolled_class<-ifelse(education_analysis_hh$count_not_enrolled>=3,3,0) # join with parent table data<-full_join(data, education_analysis_hh,by = c("uuid"="_submission__uuid")) # reasons not attending data$severe_not_attending<-coerc(data[["boy_unattendance_reason.insecurity"]])+coerc(data[["boy_unattendance_reason.child_works_instead"]])+coerc(data[["girl_unattendance_reason.insecurity"]])+coerc(data[["girl_unattendance_reason.child_works_instead"]]) data$severe_not_attending[is.na(data$severe_not_attending)] <- 0 data$less_severe_not_attending<-coerc(data[["boy_unattendance_reason.lack_facilities"]])+coerc(data[["boy_unattendance_reason.lack_documentation"]])+coerc(data[["boy_unattendance_reason.too_expensive"]])+coerc(data[["girl_unattendance_reason.lack_facilities"]])+coerc(data[["girl_unattendance_reason.lack_documentation"]])+coerc(data[["girl_unattendance_reason.too_expensive"]]) data$less_severe_not_attending[is.na(data$less_severe_not_attending)] <- 0 data$not_attending_class<-ifelse(data$severe_not_attending >= 1,3, ifelse(data$severe_not_attending==0 & data$less_severe_not_attending >=1,2,0)) data$not_attending_class[is.na(data$not_attending_class)] <- 0 # Education Severity Score data$edu_score_hh_w_schoolage<-coerc(data[["enroll_perc_class"]])+coerc(data[["shock_class"]])+coerc(data[["count_not_enrolled_class"]])+coerc(data[["not_attending_class"]]) data$edu_score<-data$edu_score_hh_w_schoolage data$edu_score[is.na(data$edu_score)] <- 0 data$edu_severity<-car::recode(data$edu_score, "0:2='1'; 3:5='2'; 6:8='3'; 9:16='4'") data$edu_sev_high<-ifelse(data$edu_severity==3|data$edu_severity==4,1,0) ################################################################# ### Health #### #deaths under 5 years age overall_death_roster$deaths_under5<-ifelse(overall_death_roster$hh_died_age<5,1,0) # deaths >= 5 overall_death_roster$deaths_over5<-ifelse(overall_death_roster$hh_died_age>=5,1,0) # group by hh health_analysis<-overall_death_roster %>% group_by(`_submission__uuid`) %>% summarize(number_death_under5=sum(deaths_under5), hh_member_died = sum(hh_member_died), number_death_over5=sum(deaths_over5)) # join with parent dataset data<-full_join(data, health_analysis,by = c("uuid"="_submission__uuid")) data$number_death_under5[is.na(data$number_death_under5)] <- 0 # #deaths under 5 yrs age weight # data$number_death_under5_class<-ifelse(data$number_death_under5 >= 1, 3,0) # data$number_death_under5_class[is.na(data$number_death_under5_class)] <- 0 # # # deaths >= 5 weight # data$number_death_over5_class<-ifelse(data$number_death_over5 >= 1, 2,0) # data$number_death_over5_class[is.na(data$number_death_over5_class)] <- 0 # health facility barriers data$health_barriers_total<-coerc(data[["health_facility_barriers.unsafe"]])+coerc(data[["health_facility_barriers.cost_services"]])+coerc(data[["health_facility_barriers.cost_medicines"]])+coerc(data[["health_facility_barriers.too_far"]])+coerc(data[["health_facility_barriers.documentation_problems"]])+coerc(data[["health_facility_barriers.insufficient_female_staff"]])+coerc(data[["health_facility_barriers.treatment_refused"]])+coerc(data[["health_facility_barriers.other"]]) data$health_barriers_total[is.na(data$health_barriers_total)] <- 0 # data$health_facility_barriers_class<-ifelse(data$health_facility_access == 'no' & data$health_barriers_total>1,3,ifelse(data$health_facility_access == 'no' & data$health_barriers_total==1,2,0)) data$health_facility_barriers_class<-ifelse(data$health_facility_access == 'no' ,3,0) # health facility distance data$health_facility_dist_class<-ifelse(data$health_facility_distance == 'none' | data$health_facility_distance=='more_10km',3,ifelse(data$health_facility_distance=='6_10km',2,0)) # health facilities affected data$health_facility_affected_class<-ifelse(data$health_facility_affected_how == 'forcibly_closed'|data$health_facility_affected_how == 'damaged_conflict'|data$health_facility_affected_how == 'damaged_natural_disasters',3, ifelse(data$health_facility_affected_how=='lack_staff'|data$health_facility_affected_how=='lack_medicine',2,0)) data$health_facility_affected_class[is.na(data$health_facility_affected_class)] <- 0 # health selected as priority need data$health_priority_need_class<-ifelse(data$priority_needs.healthcare == 1, 3,0) # behaviour changes as result of conflict data$behavior_change_cause_class<-case_when(data$adult_behavior_change == 'yes'& data$behavior_change_cause=='yes'~ 3, data$child_behavior_change == 'yes'& data$behavior_change_cause=='yes'~ 3, TRUE~ 0) data$behavior_change_cause_class[is.na(data$behavior_change_cause_class)] <- 0 # birth location # data$birth_location_class<-ifelse(data$birth_location == 'home'|data$birth_location == 'midwife_home'|data$birth_location == 'outside'|data$birth_location == 'other',1,0) # data$birth_location_class[is.na(data$birth_location_class)] <- 0 # Health Severity Score # data$health_score<- coerc(data[["health_facility_barriers_class"]])+coerc(data[["health_facility_dist_class"]])+coerc(data[["health_facility_affected_class"]])+coerc(data[["health_priority_need_class"]])+coerc(data[["behavior_change_cause_class"]])+coerc(data[["birth_location_class"]]) data$health_score<- coerc(data[["health_facility_barriers_class"]])+coerc(data[["health_facility_dist_class"]])+coerc(data[["health_facility_affected_class"]])+coerc(data[["health_priority_need_class"]])+coerc(data[["behavior_change_cause_class"]]) data$health_severity<-car::recode(data$health_score, "0:2='1'; 3:5='2'; 6:8='3'; 9:16='4'") data$health_sev_high<-ifelse(data$health_severity==3|data$health_severity==4,1,0) ################################################################# # number sectoral needs #### data$total_sectoral_needs<-coerc(data[["fsac_sev_high"]])+coerc(data[["prot_sev_high"]])+coerc(data[["esnfi_sev_high"]])+coerc(data[["wash_sev_high"]])+coerc(data[["nut_sev_high"]])+coerc(data[["edu_sev_high"]])+coerc(data[["health_sev_high"]]) ################################################################# ### LSCI - coping strategies #### # coping severity data$lcsi_severity<-car::recode(data$lcsi_category, "'food_secure'='minimal'; 'marginally_insecure'='stress'; 'moderately_insecure'='severe'; 'severely_insecure'='extreme'") ## Indicators #### ### Numerators ## Some numerators combine variables calcualte those here data$edu_age_boys_girls_num <- comp_score(data, c("boys_ed","girls_ed")) food_water_rent_vars <- c( "food_exp", "water_expt", "rent_exp" ) data$food_water_rent_num <- comp_score(data, food_water_rent_vars) all_expenses_vars <- c( "food_exp", "water_expt", "rent_exp", "fuel_exp", "debt_exp") data$all_expenses <- comp_score(data, all_expenses_vars) min_die_vars <- c( "minimum_dietary_diversity.staples", "minimum_dietary_diversity.legumes", "minimum_dietary_diversity.dairy", "minimum_dietary_diversity.meat", "minimum_dietary_diversity.eggs", "minimum_dietary_diversity.vitamin_a_veg", "minimum_dietary_diversity.other_veg") data$min_die_num <- comp_score(data, min_die_vars) priority_nfi_vars <- c( "sleeping_mats", "tarpaulin", "cooking_pots", "stainless_steel", "water_storage", "hygiene_sanitation" ) data$priority_nfi_num <- comp_score(data, priority_nfi_vars) child_vars <- c( "males_0_2_total", "males_3_5_total", "females_0_2_total", "females_3_5_total") data$children_under5 <- comp_score(data, child_vars) comp_ind_vars <- c( "prot_sev_high", "fsac_sev_high", "esnfi_sev_high", "wash_sev_high", "edu_sev_high", "health_sev_high" ) data$comp_ind_sev <- comp_score(data, comp_ind_vars) comp_ind_vars_nut <- c( "prot_sev_high", "fsac_sev_high", "esnfi_sev_high", "wash_sev_high", "edu_sev_high", "health_sev_high", "nut_sev_high" ) data$comp_ind_sev_nut <- comp_score(data, comp_ind_vars_nut) ## Age categories hh data <- data %>% mutate( age_0_4_hh = case_when( hoh_age <=4 ~ 1, TRUE ~ 0 ), age_0_17_hh = case_when( hoh_age <=17 ~ 1, TRUE ~ 0 ) , age_0_14_hh = case_when( hoh_age <=14 ~ 1, TRUE ~ 0 ) , age_10_17_hh = case_when( hoh_age >= 10 & hoh_age <=17 ~ 1, TRUE ~ 0 ) , age_15_64_hh = case_when( hoh_age >= 14 & hoh_age <=64 ~ 1, TRUE ~ 0 ) , age_18_59_hh = case_when( hoh_age >= 18 & hoh_age <=59 ~ 1, TRUE ~ 0 ) , age_18_64_hh = case_when( hoh_age >= 18 & hoh_age <=64 ~ 1, TRUE ~ 0 ) , age_60_and_more_hh = case_when( hoh_age >= 60 ~ 1, TRUE ~ 0 ) , age_65_hh = case_when( hoh_age >= 65 ~ 1, TRUE ~ 0 ) , testt = case_when( hoh_age < 120 ~ 1, TRUE ~ 0 ) ) ## Age categories roster hh_group <- overall_hh_roster %>% mutate( age_0_4 = hh_member_age <=4, age_0_17 = hh_member_age <=17, age_0_14 = hh_member_age <=14, age_10_17 = hh_member_age >= 10 & hh_member_age <=17, age_15_64 = hh_member_age >= 14 & hh_member_age <=64, age_18_59 = hh_member_age >= 18 & hh_member_age <=59, age_18_64 = hh_member_age >= 18 & hh_member_age <=64, age_60_and_more = hh_member_age >= 60, age_65 = hh_member_age >= 65 ) %>% group_by(`_submission__uuid`) %>% summarise( age_0_4 = sum(age_0_4, na.rm = TRUE), age_0_17 = sum(age_0_17, na.rm = TRUE), age_0_14 = sum(age_0_14, na.rm = TRUE), age_10_17 = sum(age_10_17, na.rm = TRUE), age_15_64 = sum(age_15_64, na.rm = TRUE), age_18_59 = sum(age_18_59, na.rm = TRUE), age_18_64 = sum(age_18_64, na.rm = TRUE), age_60_and_more = sum(age_60_and_more, na.rm = T), age_65 = sum(age_65, na.rm = TRUE) ) # Age Cat Vars age_0_4_vars <- c( 'age_0_4', 'age_0_4_hh' ) age_0_17_vars <- c( 'age_0_17', 'age_0_17_hh' ) age_0_14_vars <- c( 'age_0_14', 'age_0_14_hh' ) age_10_17_vars <- c( 'age_10_17', 'age_10_17_hh' ) age_15_64_vars <- c( 'age_15_64', 'age_15_64_hh' ) age_18_59_vars <- c( 'age_18_59', 'age_18_59_hh' ) age_18_64_vars <- c( 'age_18_64', 'age_18_64_hh' ) age_60_and_more_var <- c( 'age_60_and_more', 'age_60_and_more_hh' ) age_65_var <- c( 'age_65', 'age_65_hh' ) data <- full_join(data, hh_group,by = c("uuid"="_submission__uuid")) # Merge Age cat hh_roster and hh data data$age_0_4_merged <- comp_score(data,age_0_4_vars) data$age_0_17_merged <- comp_score(data,age_0_17_vars) data$age_0_14_merged <- comp_score(data,age_0_14_vars) data$age_10_17_merged <- comp_score(data,age_10_17_vars) data$age_15_64_merged <- comp_score(data,age_15_64_vars) data$age_18_59_merged <- comp_score(data,age_18_59_vars) data$age_18_64_merged <- comp_score(data,age_18_64_vars) data$age_60_and_more_merged <- comp_score(data,age_60_and_more_var) data$age_65_merged <- comp_score(data,age_65_var) # Adjust displacement status as more information in other data non_displ_data <- read.csv("input/Non_Displaced_Host_List_v2.csv",stringsAsFactors=F,na.strings = c("", "NA")) data<-full_join(data, non_displ_data,by = c("district"="district")) data$final_displacement_status_non_displ<-ifelse(data$final_displacement_status=='non_displaced'|data$final_displacement_status=='host', data$non_displ_class,data$final_displacement_status) # prev_displacement data <- data %>% mutate( # prev_displacement_num prev_displacement_num_class = case_when( prev_displacement_num == 2 ~ "2", prev_displacement_num == 3 ~ "3", prev_displacement_num >3 ~ "4+" ), # refugee_displace_year refugee_displace_year_class = case_when( refugee_displace_year == 0 ~ "0", refugee_displace_year == 1 ~ "1", refugee_displace_year == 2 ~ "2", refugee_displace_year == 3 ~ "3", refugee_displace_year > 3 ~ "4+" ), # cb_return_displace_year cb_return_displace_year_class = case_when( cb_return_displace_year == 0 ~ "0", cb_return_displace_year == 1 ~ "1", cb_return_displace_year == 2 ~ "2", cb_return_displace_year == 3 ~ "3", cb_return_displace_year > 3 ~ "4+" ), # cb_return_return_year cb_return_return_year_call = case_when( cb_return_return_year == 0 ~ "0", cb_return_return_year == 1 ~ "1", cb_return_return_year == 2 ~ "2", cb_return_return_year == 3 ~ "3", cb_return_return_year > 3 ~ "4+" ), # idp_displ_year idp_displ_year_class = case_when( idp_displ_year == 0 ~ "0", idp_displ_year == 1 ~ "1", idp_displ_year == 2 ~ "2", idp_displ_year == 3 ~ "3", idp_displ_year > 3 ~ "4+" ), # head of household age_group hoh_age_group = case_when( hoh_age >= 65 ~ "65+", hoh_age < 65 ~ "<65" ), # head of household disabled hoh_disabled = case_when( wg_walking == "yes" | wg_selfcare == "yes" ~ "disabled", wg_walking == "no" | wg_selfcare == "no" ~ "not_disabled", TRUE ~ NA_character_ ), pregnant_member = case_when( pregnant > 0 ~ "at_least_one_mem_pregnant", pregnant == 0 ~ "no_mem_pregnent", TRUE ~ NA_character_ ), lactating_member = case_when( lactating > 0 ~ "at_least_one_mem_lactating", lactating == 0 ~ "no_mem_lactating", TRUE ~ NA_character_ ), pregnant_lactating_member = case_when( pregnant > 0 | lactating > 0 ~ "at_least_one_mem_pregnant_lactating", pregnant == 0 & lactating == 0 ~ "no_mem_pregnent_lactating", TRUE ~ NA_character_ ), female_literacy_yes_no = case_when( female_literacy == 0 ~ "0", female_literacy >= 1 ~ "1 or more", TRUE ~ NA_character_ ), male_literacy_yes_no = case_when( male_literacy == 0 ~ "0", male_literacy >= 1 ~ "1 or more", TRUE ~ NA_character_ ), # How many adults 18+ years worked outside of the household in the last 30 days? adults_working_yes_no = case_when( adults_working == 0 ~ "0", adults_working >= 1 ~ "1 or more", TRUE ~ NA_character_ ), children_working_yes_no = case_when( children_working == 0 ~ "0", children_working >= 1 ~ "1 or more", TRUE ~ NA_character_ ), ag_income_cal = case_when( ag_income == 0 ~ 0, ag_income > 0 ~ ag_income / hh_size, TRUE ~ NA_real_ ), livestock_income_cal = case_when( livestock_income == 0 ~ 0, livestock_income > 0 ~ livestock_income / hh_size, TRUE ~ NA_real_ ), rent_income_cal = case_when( rent_income == 0 ~ 0, rent_income > 0 ~ rent_income / hh_size, TRUE ~ NA_real_ ), small_business_income_cal = case_when( small_business_income == 0 ~ 0, small_business_income > 0 ~ small_business_income / hh_size, TRUE ~ NA_real_ ), unskill_labor_income_cal = case_when( unskill_labor_income == 0 ~ 0, unskill_labor_income > 0 ~ unskill_labor_income / hh_size, TRUE ~ NA_real_ ), skill_labor_income_cal = case_when( skill_labor_income == 0 ~ 0, skill_labor_income > 0 ~ skill_labor_income / hh_size, TRUE ~ NA_real_ ), formal_employment_income_cal = case_when( formal_employment_income == 0 ~ 0, formal_employment_income > 0 ~ formal_employment_income / hh_size, TRUE ~ NA_real_ ), gov_benefits_income_cal = case_when( gov_benefits_income == 0 ~ 0, gov_benefits_income > 0 ~ gov_benefits_income / hh_size, TRUE ~ NA_real_ ), hum_assistance_income_cal = case_when( hum_assistance_income == 0 ~ 0, hum_assistance_income > 0 ~ hum_assistance_income / hh_size, TRUE ~ NA_real_ ), remittance_income_cal = case_when( remittance_income == 0 ~ 0, remittance_income > 0 ~ remittance_income / hh_size, TRUE ~ NA_real_ ), loans_income_cal = case_when( loans_income == 0 ~ 0, loans_income > 0 ~ loans_income / hh_size, TRUE ~ NA_real_ ), asset_selling_income_cal = case_when( asset_selling_income == 0 ~ 0, asset_selling_income > 0 ~ asset_selling_income / hh_size, TRUE ~ NA_real_ ), total_income_cal = case_when( total_income == 0 ~ 0, total_income > 0 ~ total_income / hh_size, TRUE ~ NA_real_ ), # Debt level debt_amount_cal = case_when( debt_amount == 0 ~ 0, debt_amount > 0 ~ debt_amount / hh_size, TRUE ~ NA_real_), food_exp_cal = case_when( total_income == 0 ~ 0, total_income > 0 ~ food_exp / total_income, TRUE ~ NA_real_ ), water_expt_cal = case_when( total_income == 0 ~ 0, total_income > 0 ~ water_expt / total_income, TRUE ~ NA_real_ ), rent_exp_cal = case_when( total_income == 0 ~ 0, total_income > 0 ~ rent_exp / total_income, TRUE ~ NA_real_ ), fuel_exp_cal = case_when( total_income == 0 ~ 0, total_income > 0 ~ fuel_exp / total_income, TRUE ~ NA_real_ ), debt_exp_cal = case_when( total_income == 0 ~ 0, total_income > 0 ~ debt_exp / total_income, TRUE ~ NA_real_ ), basic_needs_cal = case_when( total_income == 0 ~ 0, food_water_rent_num > 0 ~ food_water_rent_num / total_income, TRUE ~ NA_real_ ), minimum_dietary_diversity_cal = case_when( min_die_num >= 4 ~ "4 food groups", min_die_num < 4 ~ "<4 food groups", TRUE ~ NA_character_ ), rooms_hh_cal = case_when( rooms > 0 ~ hh_size / rooms, TRUE ~ 0 ), blankets_people_cal = case_when( blankets_number == 0 ~ 0, blankets_number > 0 ~ blankets_number / hh_size, TRUE ~ NA_real_ ), blankets_suff_cal = case_when( blankets_people_cal < 1 ~ "<1", blankets_people_cal >= 1 ~ "1+", TRUE ~ NA_character_ ), priority_nfi_cal = case_when( priority_nfi_num <= 1 ~ "0_1", priority_nfi_num <= 3 ~ "2_3", priority_nfi_num <= 5 ~ "4_5", priority_nfi_num <= 6 ~ "6", TRUE ~ NA_character_ ), imp_energy_source1_cal = case_when( energy_source %in% c("wood" , "animal_waste" , "paper_waste") ~ 1, TRUE ~ 0 ), imp_energy_source2_cal = case_when( energy_source %in% c("coal" , "charcoal" , "lpg" , "electricity") ~ 1, TRUE ~ 0 ), diarrhea_cases_cal = case_when( diarrhea_cases == 0 ~ 0, diarrhea_cases > 0 ~ diarrhea_cases / diarrhea_total, TRUE ~ NA_real_ ), perc_diarrhea_cases_cal = case_when( diarrhea_cases == 0 ~ "0", diarrhea_cases > 0 ~ ">=1", TRUE ~ NA_character_ ), imp_water_source1_cal = case_when( water_source %in% c("handpump_private", "handpump_public", "piped_public", "spring_protected") ~ 1, TRUE ~ 0 ), imp_water_source2_cal = case_when( water_source %in% c("spring_unprotected","surface_water" , "water_trucking", "other") ~ 1, TRUE ~ 0 ), imp_san_source1_cal = case_when( water_source %in% c("open", "pit_latrine_uncovered", "other") ~ 1, TRUE ~ 0 ), imp_san_source2_cal = case_when( water_source %in% c("public_latrine", "pit_latrine_covered", "vip_latrine", "flush_toilet_open_drain", "flush_toilet_septic") ~ 1, TRUE ~ 0 ), comp_ind_sev_2_call = case_when( comp_ind_sev >= 2 ~ ">=2", comp_ind_sev <2 ~ "<2", TRUE ~ NA_character_ ), comp_ind_sev_2_nut_call = case_when( comp_ind_sev_nut >= 2 ~ ">=2", comp_ind_sev_nut <2 ~ "<2", TRUE ~ NA_character_ ), comp_ind_sev_3_call = case_when( comp_ind_sev >= 3 ~ ">=3", comp_ind_sev < 3 ~ "<3", TRUE ~ NA_character_ ), dep_ratio_call = case_when( age_0_4_merged == 0 & age_65_merged == 0 ~ 0, (age_0_14_merged > 0 | age_65_merged > 0) ~ sum(age_0_14_merged,age_65_merged, na.rm = TRUE)/sum(age_15_64_merged,na.rm = TRUE), TRUE ~ NA_real_ ), dep_ratio_call_2 = case_when( age_0_17_merged == 0 & age_60_and_more_merged == 0 ~ 0, (age_0_17_merged > 0 | age_60_and_more_merged > 0) ~ sum(age_0_17_merged,age_60_and_more_merged, na.rm = TRUE)/sum(age_18_59_merged ,na.rm = TRUE), TRUE ~ NA_real_ ), female_lit_call = case_when( female_literacy == 0 ~ 0, female_literacy == 0 ~ female_literacy/sum(females_11_17_total,females_18_plus_total, na.rm=TRUE), TRUE ~ NA_real_ ), male_lit_call = case_when( male_literacy == 0 ~ 0, male_literacy == 0 ~ male_literacy/sum(males_11_17_total,males_18_plus_total, na.rm=TRUE), TRUE ~ NA_real_ ), adult_behavior_change_call = case_when( adult_behavior_change == "yes" ~ 1, adult_behavior_change == "no" ~ 0, TRUE ~ NA_real_ ), child_behavior_change_call = case_when( child_behavior_change == "yes" ~ 1, child_behavior_change == "no" ~ 0, TRUE ~ NA_real_ ), atleast_one_behav_change_call = case_when( child_behavior_change_call == 0 & adult_behavior_change_call == 0 ~ 0, child_behavior_change_call > 0 | adult_behavior_change_call > 0 ~ 1, TRUE ~ NA_real_ ), adults_working_call = case_when( adults_working == 0 ~ 0, adults_working > 0 & age_18_64 > 0 ~ adults_working/age_18_64, TRUE ~ NA_real_ ), child_working_call = case_when( is.na(children_working) ~ 0, children_working == 0 ~ 0, children_working > 0 & age_10_17 > 0 ~ children_working/age_10_17, TRUE ~ NA_real_ ), adult_tazkira_cal = case_when( adult_tazkira == 0 ~ "0", adult_tazkira >= 1 ~ ">=1", TRUE ~ NA_character_ ), child_tazkira_cal = case_when( child_tazkira == 0 ~ "0", child_tazkira >= 1 ~ ">=1", TRUE ~ NA_character_ ), child_tazkira_cal = case_when( child_tazkira == 0 ~ "0", child_tazkira >= 1 ~ ">=1", TRUE ~ NA_character_ ), any_tazkira_cal = case_when( adult_tazkira == 0 & child_tazkira == 0~ "0", adult_tazkira >= 1 | child_tazkira >= 1~ ">=1", TRUE ~ NA_character_ ), insuf_blank_energy = case_when( blankets_suff_cal == "<1" & energy_source == "wood" | energy_source == "paper_waste" | energy_source == "animal_waste" ~ "yes", TRUE ~ "no" ), current_presence_mines = case_when( displ_explosive_presence == "both" | displ_explosive_presence == "current" | nondispl_explosive_presence == "yes" ~ "current_explosive_presence", displ_explosive_presence == "previous" | displ_explosive_presence == "no" | nondispl_explosive_presence == "no" ~ "no_explosive_presence", TRUE ~ NA_character_ ), # child_working_call = case_when( # children_working == 0 ~ 0, # children_working > 0 ~ children_working/age_10_17, # TRUE ~ NA_real_ # ), count_current_enrolled_avg = count_current_enrolled / edu_age_boys_girls_num, count_current_attending_avg = count_current_attending / edu_age_boys_girls_num ) # Major events major_events_vars <- c( "major_events.avalanche", "major_events.conflict", "major_events.drought", "major_events.earthquake", "major_events.floods", "major_events.other" ) major_events_score <- (rowSums(data[major_events_vars])) data <- data %>% mutate( major_events_cal = case_when( major_events_score == 0 ~ "none", major_events_score == 1 ~ "1", major_events_score == 2 ~ "2", major_events_score >= 3 ~ ">= 3", TRUE ~ NA_character_ ) ) # hno_intersectoral analysis data <- data %>% mutate( # GBV incident OR threat gbv_incidents_threats = case_when( other_incidents == "sgbv" | other_concerns == "sgbv" ~ ">=1", (other_incidents == "no" | other_incidents == "other") & (other_concerns == "no" | other_concerns == "other") ~ "0", TRUE ~ NA_character_ ), # At least one protection incident for adult OR child prot_incident_adult_child = case_when( adult_prot_incidents != "none" | child_prot_incidents != "none" ~ ">=1", adult_prot_incidents == "none" & child_prot_incidents == "none" ~ "0", TRUE ~ NA_character_ ), # Total income per day per household member in USD daily_income_hh_members = case_when( (((total_income / 30) / hh_size) / 78.36) > 1.90 ~ 1, (((total_income / 30) / hh_size) / 78.36) <= 1.90 ~ 0, TRUE ~ NA_real_ ), # health health_service_access_class = case_when( health_facility_access == "no" ~ 1, health_facility_access == "yes" ~ 0, TRUE ~ NA_real_ ), #ESNFI shelter_type_access_class = case_when( shelter == "tent" | shelter == "makeshift_shelter" | shelter == "collective_centre" | shelter == "open_space" ~ 1, shelter == "transitional" | shelter == "permanent" ~ 0, TRUE ~ NA_real_ ), #EiE hh_level_school_attendance_class = case_when( count_current_attending > 0 ~ 1, TRUE ~ 0 ), #FSA No data for Farah paper interviews market_service_access_class = case_when( market_access == "no" ~ 1, market_access == "yes" ~ 0, TRUE ~ NA_real_ ), #protection identity_ownership_class = case_when( child_tazkira == 0 & adult_tazkira == 0 ~ 1, child_tazkira >=1 | adult_tazkira >=1 ~ 0, TRUE ~ NA_real_ ), #WASH access_to_water_class = case_when( water_source == "handpump_private" | water_source == "handpump_public" | water_source == "piped_public" | water_source == "spring_protected" ~ 1, water_source == "spring_unprotected" | water_source == "surface_water" | water_source == "water_trucking" | water_source == "other" ~ 0, TRUE ~ NA_real_ ) ) access_services_vars <- c("health_service_access_class", "shelter_type_access_class", "hh_level_school_attendance_class", "market_service_access_class", "identity_ownership_class","access_to_water_class") data$services_score <- comp_score(data, access_services_vars) data <- data %>% mutate( comp_ind_access_services = case_when( services_score <= 2 ~ 0, services_score >= 3 ~ 1 ) ) #Recoding new variables data$hh_no_tazkira <- ifelse(data$tazkira_total < 1, "Tazkira_No", "Tazkira_Yes") data$muac_yes_no <- ifelse(data$muac_total > 0 & !is.na(data$min_muac) ,"Yes","No") data$recent_non_recent <- ifelse(data$final_displacement_status_non_displ == "recent_idps", "recent_idps", ifelse(data$final_displacement_status_non_displ == "non_recent_idps", "non_recent_idps", NA )) data$edu_removal_shock_cal <- ifelse(data$shock_class == 5, "Yes", "No") data$enrolled_attending <- ifelse(data$count_enrolled_attending > 0, "Enrolled_and_Attending", "Not" ) data$schoo_age_boys_girls <- coerc(data$boys_ed) + coerc(data$girls_ed) ## source disaggs source("r/prepare_disagg.R") ################ MEB analysis ########################################################### # sustainable income vars sustainable_income_vars <- c( 'ag_income', 'livestock_income', 'rent_income', 'small_business_income', 'unskill_labor_income', 'skill_labor_income', 'formal_employment_income', 'gov_benefits_income' ) # sustainable income per HH data$sustainable_income <- comp_score(data, sustainable_income_vars) # sustainable income per HH member data$sustainable_income_per_mem <- data$sustainable_income / data$hh_size # net inocome per hh data$net_income <- data$sustainable_income - data$all_expenses # total Exp per hh memeber data$total_exp_per_mem <- data$all_expenses / data$hh_size data <- data %>% mutate( food_exp_per_mem = food_exp / hh_size, water_expt_per_mem = water_expt / hh_size, rent_exp_per_mem = rent_exp / hh_size, fuel_exp_per_mem = fuel_exp / hh_size, debt_exp_per_mem = debt_exp / hh_size, food_exp_spent = case_when( food_exp > 0 ~ 1, food_exp == 0 ~ 0, TRUE ~ NA_real_ ), water_expt_spent = case_when( water_expt > 0 ~ 1, water_expt == 0 ~ 0, TRUE ~ NA_real_ ), rent_exp_spent = case_when( rent_exp > 0 ~ 1, rent_exp == 0 ~ 0, TRUE ~ NA_real_ ), fuel_exp_spent = case_when( fuel_exp > 0 ~ 1, fuel_exp == 0 ~ 0, TRUE ~ NA_real_ ), debt_exp_spent = case_when( debt_exp > 0 ~ 1, debt_exp == 0 ~ 0, TRUE ~ NA_real_ ) ) # sustainable income 2 vars sustainable_income_2_vars <- c( 'ag_income', 'livestock_income', 'rent_income', 'small_business_income', 'unskill_labor_income', 'skill_labor_income', 'formal_employment_income' ) # sustainable income per HH data$sustainable_income_2 <- comp_score(data, sustainable_income_2_vars) # sustainable income per HH member data$sustainable_income_2_per_mem <- data$sustainable_income_2 / data$hh_size # unskilled_labor_income per hh member data$unskill_labor_income_per_mem <- data$unskill_labor_income / data$hh_size # unskilled + agriculture + livestock income vars unskill_ag_live_income_vars <- c( 'ag_income', 'livestock_income', 'unskill_labor_income' ) # unskilled + agriculture + livestock income data$unskill_ag_live_income_income <- comp_score(data, unskill_ag_live_income_vars) # unskilled + agriculture + livestock income per HH member data$unskill_ag_live_income_income_per_mem <- data$unskill_ag_live_income_income / data$hh_size ######################################################################################## ############################# Vulnerablity composites ################################### data <- data %>% mutate( hoh_disabled_vul_class = case_when( data$hoh_disabled == "disabled" ~ 1, data$hoh_disabled == "not_disabled" ~ 0, TRUE ~ 0 ), hoh_debt_disagg_vul_class = case_when( hoh_debt_disagg == "high_debt" ~ 1, hoh_debt_disagg == "low_debt" ~ 0, hoh_debt_disagg == "medium_debt" ~ 0, hoh_debt_disagg == "no_debt" ~ 0, TRUE ~ 0 ), tazkira_disagg_vul_class = case_when( tazkira_disagg == "non_have_tazkira" ~ 1, tazkira_disagg == "all_have_tazkira" ~ 0, TRUE ~ 0 ), hoh_age_group_vul_class = case_when( hoh_age_group == "65+" ~ 1, hoh_age_group == "<65" ~ 0, TRUE ~ 0 ), hoh_sex_disagg_vul_class = case_when( hoh_sex_disagg == "female" ~ 1, hoh_sex_disagg == "male" ~ 0, TRUE ~ 0 ), pregnant_lactating_member_vul_class = case_when( pregnant_lactating_member == "at_least_one_mem_pregnant_lactating" ~ 1, pregnant_lactating_member == "no_mem_pregnent_lactating" ~ 0, TRUE ~ 0 ), chronic_illness_vul_class = case_when( chronic_illness == "yes" ~ 1, chronic_illness == "no " ~ 0, chronic_illness == "no_answer" ~ 0, TRUE ~ 0 ), literacy_vul_class = case_when( female_literacy_yes_no == "0" & male_literacy_yes_no == "0" ~ 1, female_literacy_yes_no == "1 or more" ~ 0, male_literacy_yes_no == "1 or more" ~ 0, TRUE ~ 0 ), behav_change_disagg_vul_class = case_when( behav_change_disagg == "yes" ~ 1, behav_change_disagg == "no" ~ 0, TRUE ~ 0 ), female_literacy_yes_no_class = case_when( female_literacy_yes_no == "0" ~ 1, female_literacy_yes_no == "1 or more" ~ 0, TRUE ~ 0 ), behavior_change_cause_class2 = case_when( behavior_change_cause == "yes" ~ 1, TRUE ~ 0 ), child_behavior_change_class2 = case_when( child_behavior_change == "yes" ~ 1, TRUE ~ 0 ), adult_behavior_change_class2 = case_when( adult_behavior_change == "yes" ~ 1, TRUE ~ 0 ), adult_behavior_only_by_conflict = case_when( adult_behavior_change == "yes" & behavior_change_cause == "yes" ~ 1, TRUE ~ 0 ) ) ## Vulnerable_group_1 Vulnerable_group_1_vars <- c( "hoh_disabled_vul_class", "hoh_debt_disagg_vul_class", "tazkira_disagg_vul_class", "hoh_age_group_vul_class", "hoh_sex_disagg_vul_class", "chronic_illness_vul_class", "literacy_vul_class" ) data$Vulnerable_group_1_vars_score <- comp_score(data, Vulnerable_group_1_vars) data <- data %>% mutate( vulnerable_group_1 = case_when( Vulnerable_group_1_vars_score >= 1 ~ "vulnerable", Vulnerable_group_1_vars_score == 0 ~ "not_vulnerable", TRUE ~ NA_character_ ) ) ## vulnerable_group_4 Vulnerable_group_4_vars <- c( "hoh_disabled_vul_class", "hoh_debt_disagg_vul_class", "tazkira_disagg_vul_class", "hoh_age_group_vul_class", "hoh_sex_disagg_vul_class", "behav_change_disagg_vul_class" ) data$Vulnerable_group_4_vars_score <- comp_score(data, Vulnerable_group_4_vars) data <- data %>% mutate( vulnerable_group_4 = case_when( Vulnerable_group_4_vars_score >= 1 ~ "vulnerable", Vulnerable_group_4_vars_score == 0 ~ "not_vulnerable", TRUE ~ NA_character_ ) ) ## Vulnerable_group_5 Vulnerable_group_5_vars <- c( "hoh_disabled_vul_class", "hoh_debt_disagg_vul_class", "tazkira_disagg_vul_class", "hoh_age_group_vul_class", "hoh_sex_disagg_vul_class", "pregnant_lactating_member_vul_class", "chronic_illness_vul_class", "behav_change_disagg_vul_class", "literacy_vul_class" ) data$Vulnerable_group_5_vars_score <- comp_score(data, Vulnerable_group_5_vars) data <- data %>% mutate( vulnerable_group_5 = case_when( Vulnerable_group_5_vars_score >= 1 ~ "vulnerable", Vulnerable_group_5_vars_score == 0 ~ "not_vulnerable", TRUE ~ NA_character_ ) ) ## Vulnerable_group_6 Vulnerable_group_6_vars <- c( "hoh_disabled_vul_class", "hoh_debt_disagg_vul_class", "tazkira_disagg_vul_class", "hoh_age_group_vul_class", "hoh_sex_disagg_vul_class", "behav_change_disagg_vul_class", "female_literacy_yes_no_class" ) data$Vulnerable_group_6_vars_score <- comp_score(data, Vulnerable_group_6_vars) data <- data %>% mutate( vulnerable_group_6 = case_when( Vulnerable_group_6_vars_score >= 1 ~ "vulnerable", Vulnerable_group_6_vars_score == 0 ~ "not_vulnerable", TRUE ~ NA_character_ ) ) ## Vulnerable_group_7 ## vulnerable_group_7 Vulnerable_group_7_vars <- c( "hoh_disabled_vul_class", "hoh_debt_disagg_vul_class", "tazkira_disagg_vul_class", "hoh_age_group_vul_class", "hoh_sex_disagg_vul_class", "behavior_change_cause_class2" ) data$Vulnerable_group_7_vars_score <- comp_score(data, Vulnerable_group_7_vars) data <- data %>% mutate( vulnerable_group_7 = case_when( Vulnerable_group_7_vars_score >= 1 ~ "vulnerable", Vulnerable_group_7_vars_score == 0 ~ "not_vulnerable", TRUE ~ NA_character_ ) ) ## vulnerable_group_8 Vulnerable_group_8_vars <- c( "hoh_disabled_vul_class", "hoh_debt_disagg_vul_class", "tazkira_disagg_vul_class", "hoh_age_group_vul_class", "hoh_sex_disagg_vul_class", "adult_behavior_only_by_conflict" ) data$Vulnerable_group_8_vars_score <- comp_score(data, Vulnerable_group_8_vars) data <- data %>% mutate( vulnerable_group_8 = case_when( Vulnerable_group_8_vars_score >= 1 ~ "vulnerable", Vulnerable_group_8_vars_score == 0 ~ "not_vulnerable", TRUE ~ NA_character_ ) ) ###############################################end ######################### ## esnfi_new_indicator_1 data <- data %>% mutate( shelter_class2 = case_when( shelter == "tent" | shelter == "collective_centre" | shelter == "makeshift_shelter" | shelter == "open_space" ~ 1, shelter == "transitional" | shelter == "permanent" ~ 0, TRUE ~ 0 ), shelter_damage_and_repair_class = case_when( (shelter_damage.due_to_conflict == 1 | shelter_damage.due_to_natural_disaster == 1) & shelter_damage_repair == "no" ~ 1, shelter_damage.no == 1 | shelter_damage_repair == "yes" ~ 0, TRUE ~ 0 ), priority_nfi_cal_class = case_when( priority_nfi_cal == "0_1" | priority_nfi_cal == "2_3" ~ 1, priority_nfi_cal == "4_5" | priority_nfi_cal == "6" ~ 0, TRUE ~ 0 ) ) esnfi_new_indicator_1_vars <- c( "shelter_class2", "shelter_damage_and_repair_class", "priority_nfi_cal_class" ) esnfi_new_indicator_1_vars_score <- comp_score(data, esnfi_new_indicator_1_vars) data <- data %>% mutate( esnfi_new_indicator_1 = case_when( esnfi_new_indicator_1_vars_score >= 1 ~ 1, esnfi_new_indicator_1_vars_score == 0 ~ 0, TRUE ~ 0 ) ) ###################################end ######## wash_new_indicator 1####### data <- data %>% mutate( water_source_class2 = case_when( water_source == "spring_unprotected" | water_source == "surface_water" | water_source == "water_trucking" | water_source == "other" ~ 1, water_source == "handpump_private" | water_source == "handpump_public" | water_source == "handpump_public" | water_source == "spring_protected" ~ 0, TRUE ~ 0 ), latrine_class2 = case_when( latrine == "open" | latrine == "pit_latrine_uncovered" | latrine == "other" ~ 1, latrine == "public_latrine" | latrine == "pit_latrine_covered" | latrine == "vip_latrine" | latrine == "flush_toilet_open_drain" | latrine == "flush_toilet_septic" ~ 0, TRUE ~ 0 ), soap_class2 = case_when( soap == "no" ~ 1, soap == "yes_didnt_see" | soap == "yes_saw" ~ 0, TRUE ~ 0 ), diarrhea_cases_class = case_when( diarrhea_cases >= 1 ~ 1, diarrhea_cases == 0 ~ 0, TRUE ~ 0 ), diarrhea_cases_class_children = case_when( diarrhea_cases >= 1 ~ 1, diarrhea_cases == 0 ~ 0, TRUE ~ NA_real_ ) ) wash_new_indicator_1_vars <- c( "water_source_class2", "latrine_class2", "soap_class2" ) wash_new_indicator_1_vars_score <- comp_score(data, wash_new_indicator_1_vars) data <- data %>% mutate( wash_new_indicator_1 = case_when( wash_new_indicator_1_vars_score >= 2 ~ 1, wash_new_indicator_1_vars_score == 0 ~ 0, TRUE ~ 0 ) ) ##############################################end ######## wash_new_indicator 2 ####### wash_new_indicator_2_vars <- c( "water_source_class2", "latrine_class2", "soap_class2", "diarrhea_cases_class" ) wash_new_indicator_2_vars_score <- comp_score(data, wash_new_indicator_2_vars) data <- data %>% mutate( wash_new_indicator_2 = case_when( wash_new_indicator_2_vars_score >= 2 ~ 1, wash_new_indicator_2_vars_score == 0 ~ 0, TRUE ~ 0 ) ) ############# winterization_indicator ################## data <- data %>% mutate( shelter_class3 = case_when( shelter == "tent" | shelter == "collective_centre" | shelter == "makeshift_shelter" | shelter == "open_space" ~ 1, shelter == "transitional" | shelter == "permanent" ~ 0, TRUE ~ 0 ), blankets_suff_cal_class = case_when( blankets_suff_cal == "<1" ~ 1, blankets_suff_cal == "1+" ~ 0, TRUE ~ 0 ), energy_source_class = case_when( energy_source == "animal_waste" | energy_source == "charcoal" | energy_source == "paper_waste" | energy_source == "wood" ~ 1, energy_source == "coal" | energy_source == "lpg" | energy_source == "electricity" | energy_source == "other" ~ 0, TRUE ~ 0 ) ) winterization_indicator_vars <- c( "shelter_class3", "blankets_suff_cal_class", "energy_source_class" ) winterization_indicator_vars_score <- comp_score(data, winterization_indicator_vars) data <- data %>% mutate( winterization_indicator = case_when( winterization_indicator_vars_score >= 2 ~ 1, winterization_indicator_vars_score == 0 ~ 0, TRUE ~ 0 ) ) ################################################end #################### dip push factors ############ ipd_push_factors_vars <- c( 'idp_push_factors.active_conflict', 'idp_push_factors.anticipated_conflict', 'idp_push_factors.earthquake', 'idp_push_factors.floods', 'idp_push_factors.avalanche', 'idp_push_factors.drought', 'idp_push_factors.poverty', 'idp_push_factors.service_access', 'idp_push_factors.other' ) ipd_push_factors_vars_short <- c( 'idp_push_factors.active_conflict', 'idp_push_factors.anticipated_conflict', 'idp_push_factors.earthquake', 'idp_push_factors.floods', 'idp_push_factors.avalanche', 'idp_push_factors.drought' ) data$ipd_push_factors_vars_score <- comp_score(data, ipd_push_factors_vars) data$ipd_push_factors_vars_score_short <- comp_score(data, ipd_push_factors_vars_short) data <- data %>% mutate( idp_push_factors_cat = case_when( ipd_push_factors_vars_score == 1 ~ "1_event", ipd_push_factors_vars_score < 3 ~ "2_events", ipd_push_factors_vars_score >=3 ~ "3_or_more_events", TRUE ~ NA_character_ ), idp_push_factors_cat_short = case_when( ipd_push_factors_vars_score_short == 1 ~ "1_event", ipd_push_factors_vars_score_short < 3 ~ "2_events", ipd_push_factors_vars_score_short >=3 ~ "3_or_more_events", TRUE ~ NA_character_ ) ) ##################### MSNI ####################### #### IMPACT data <- data %>% mutate( major_events_impc = case_when( major_events_cal == ">= 3" | major_events_cal == "2" ~ 3, major_events_cal == "1" ~ 1, TRUE ~ 0 ), agricultural_impact_how_impc = case_when( agricultural_impact_how == "51_75" ~ 1, agricultural_impact_how == "76_100" ~ 2, TRUE ~ 0 ), livestock_impact_how_impc = case_when( livestock_impact_how.livestock_died == 1 ~ 1, livestock_impact_how.left_unattended == 1 ~ 1, TRUE ~ 0 ), explosive_impact_death_impc = case_when( explosive_impact.injury_death == 1 ~ 3, TRUE ~ 0 ), explosive_impact_others_impc = case_when( explosive_impact.psych_impact == 1 | explosive_impact.relocation == 1 | explosive_impact.access_services == 1 | explosive_impact.restrict_recreation == 1 | explosive_impact.livelihoods_impact == 1 | explosive_impact.other == 1 & explosive_impact.injury_death != 1 ~ 2, TRUE ~ 0 ), adult_injuries_cause_impc = case_when( adult_injuries_cause == "conflict" | adult_injuries_cause == "natural_disaster" | child_injuries_cause == "conflict" | child_injuries_cause == "natural_disaster" ~ 3, TRUE ~ 0 ), shelter_damage_impc = case_when( shelter_damage == "due_to_conflict" | shelter_damage == "due_to_natural_disaster" ~ 2, TRUE ~ 0 ), edu_removal_shock_impc = case_when( count_shock >= 1 ~ 1, TRUE ~ 0 ), health_facility_reopened_impc = case_when( health_facility_reopened == "remain_closed" ~ 1, TRUE ~ 0 ), water_damaged_cause_impc = case_when( water_damaged_cause == "conflict" | water_damaged_cause == "natural_disaster" | water_damaged_cause == "drought" ~ 2, TRUE ~ 0 ), aid_access_issue_2_impc = case_when( aid_access_issue == "yes" & aid_access_issue_type == "insecurity" | aid_access_issue_type == "explosive_hazards" ~ 2, TRUE ~ 0 ), aid_access_issue_1_impc = case_when( aid_access_issue == "yes" & aid_access_issue_type == "distance" | aid_access_issue_type == "social_restrictions" ~ 1, TRUE ~ 0 ) ) # impact class vars msni_impact_score_vars <- c( "major_events_impc", "agricultural_impact_how_impc", "livestock_impact_how_impc", "explosive_impact_death_impc", "explosive_impact_others_impc", "adult_injuries_cause_impc", "shelter_damage_impc", "edu_removal_shock_impc", "health_facility_reopened_impc", "water_damaged_cause_impc", "aid_access_issue_2_impc", "aid_access_issue_1_impc" ) # impact score data$msni_impact_score <- comp_score(data, msni_impact_score_vars) # impact severity data <- data %>% mutate( impact = case_when( msni_impact_score < 3 ~ 1, msni_impact_score > 2 & msni_impact_score < 6 ~ 2, msni_impact_score > 5 & msni_impact_score < 9 ~ 3, msni_impact_score >= 9 ~ 4, TRUE ~ 0 ) ) #### End IMPACT #### Capacity gaps data <- data %>% mutate( capacity_gaps = case_when( lcsi_severity == "minimal" ~ 1, lcsi_severity == "stress" ~ 2, lcsi_severity == "severe" ~ 3, lcsi_severity == "extreme" ~ 4, TRUE ~ NA_real_ ) ) #### End Capacity gaps # HC-LSG/ESNFI - shelter_lsg data <- data %>% mutate( shelter_type_lsg = case_when( shelter == "open_space" ~ 3, shelter == "tent" | shelter == "makeshift_shelter" | shelter == "collective_centre" ~ 2, # shelter == "transitional" ~ 1, TRUE ~ 0 ), shelter_damage_lsg = case_when( shelter_damage_extent == "fully_destroyed" & shelter_damage_repair == "no" ~ 3, shelter_damage_extent == "significant_damage" & shelter_damage_repair == "no" ~ 2, TRUE ~ 0 ), winterisation_lsg = case_when( blankets_suff_cal == "<1" & (energy_source == "animal_waste" | energy_source == "paper_waste" | energy_source == "wood") ~ 3, TRUE ~ 0 ), access_nfi_lsg = case_when( priority_nfi_num < 3 ~ 3, priority_nfi_num > 2 & priority_nfi_num < 6 ~ 2, TRUE ~ 0 ) ) # shelter_lsg class vars msni_shelter_lsg_vars <- c( "shelter_type_lsg", "shelter_damage_lsg", "winterisation_lsg", "access_nfi_lsg" ) # shelter_lsg score data$msni_shelter_lsg_score <- comp_score(data, msni_shelter_lsg_vars) # shelter_lsg severity data <- data %>% mutate( shelter_lsg = case_when( msni_shelter_lsg_score < 3 ~ 1, msni_shelter_lsg_score > 2 & msni_shelter_lsg_score < 6 ~ 2, msni_shelter_lsg_score > 5 & msni_shelter_lsg_score < 9 ~ 3, msni_shelter_lsg_score >= 9 ~ 4 ) ) #### end shelter_lsg # HC-LSG/FSA - fsl_lsg data <- data %>% mutate( fcs_lsg = case_when( fcs_category == "poor" ~ 3, fcs_category == "borderline" ~ 2, TRUE ~ 0 ), hhs_lsg = case_when( hhs_category == "severe_hunger" ~ 3, hhs_category == "moderate_hunger" ~ 2, TRUE ~ 0 ), food_source_lsg = case_when( food_source == "assistance" | food_source == "gift" | food_source == "borrowed" ~ 3, # food_source == "borrowed" ~ 2, TRUE ~ 0 ), market_access_lsg = case_when( market_access == "no" ~ 3, TRUE ~ 0 ), market_distance_lsg = case_when( market_distance == "6_10km" ~ 2, TRUE ~ 0 ) ) # fsl_lsg class vars msni_fsl_lsg_vars <- c( "fcs_lsg", "hhs_lsg", "food_source_lsg", "market_access_lsg", "market_distance_lsg" ) # fsl_lsg score data$msni_fsl_lsg_score <- comp_score(data, msni_fsl_lsg_vars) # fsl_lsg severity data <- data %>% mutate( fsl_lsg = case_when( msni_fsl_lsg_score < 3 ~ 1, msni_fsl_lsg_score > 2 & msni_fsl_lsg_score < 6 ~ 2, msni_fsl_lsg_score > 5 & msni_fsl_lsg_score < 9 ~ 3, msni_fsl_lsg_score >= 9 ~ 4 ) ) # fsl_lsg severity 2 data <- data %>% mutate( fsl_lsg_2 = case_when( msni_fsl_lsg_score < 3 ~ 1, msni_fsl_lsg_score > 2 & msni_fsl_lsg_score < 7 ~ 2, msni_fsl_lsg_score > 6 & msni_fsl_lsg_score < 9 ~ 3, msni_fsl_lsg_score >= 9 ~ 4 ) ) # fsl_lsg severity 3 data <- data %>% mutate( fsl_lsg_3 = case_when( msni_fsl_lsg_score < 3 ~ 1, msni_fsl_lsg_score > 2 & msni_fsl_lsg_score < 8 ~ 2, msni_fsl_lsg_score > 7 & msni_fsl_lsg_score < 10 ~ 3, msni_fsl_lsg_score >= 10 ~ 4 ) ) #### end fsl_lsg # HC-LSG/Health - health_lsg data <- data %>% mutate( access_health_center_lsg = case_when( health_facility_access == "no" ~ 3, TRUE ~ 0 ), health_facility_distance_lsg = case_when( health_facility_distance == "none" | health_facility_distance == "more_10km" ~ 3, health_facility_distance == "6_10km" ~ 2, TRUE ~ 0 ), behav_change_lsg = case_when( behav_change_disagg == "yes" ~ 3, TRUE ~ 0 ), birth_location_lsg = case_when( birth_location == "outside" | diarrhea_cases_class == 1 ~ 3, birth_location == "home" | birth_location == "midwife_home" | birth_location == "other" ~ 2, TRUE ~ 0 ) ) # health_lsg class vars msni_health_lsg_vars <- c( "access_health_center_lsg", "health_facility_distance_lsg", "behav_change_lsg", "birth_location_lsg" ) # health_lsg score data$msni_health_lsg_score <- comp_score(data, msni_health_lsg_vars) # health_lsg severity data <- data %>% mutate( health_lsg = case_when( msni_health_lsg_score < 3 ~ 1, msni_health_lsg_score > 2 & msni_health_lsg_score < 6 ~ 2, msni_health_lsg_score > 5 & msni_health_lsg_score < 9 ~ 3, msni_health_lsg_score >= 9 ~ 4 ) ) #### end health_lsg # HC-LSG/Protection - protection_lsg data <- data %>% mutate( prot_incidents_4_lsg = case_when( adult_prot_incidents.assaulted_with_weapon == 1 | adult_prot_incidents.hindered_leave_settlement == 1 | adult_prot_incidents.forced_work == 1 | adult_prot_incidents.forcibly_detained == 1 | child_prot_incidents.assaulted_with_weapon == 1 | child_prot_incidents.hindered_leave_settlement == 1 | child_prot_incidents.forced_work == 1 | child_prot_incidents.forcibly_detained == 1 ~ 4, TRUE ~ 0 ), prot_incidents_3_lsg = case_when( adult_prot_incidents.verbally_threatened == 1 | adult_prot_incidents.assaulted_without_weapon == 1 | adult_prot_incidents.hindered_leave_district == 1 | child_prot_incidents.verbally_threatened == 1 | child_prot_incidents.assaulted_without_weapon == 1 | child_prot_incidents.hindered_leave_district == 1 & (adult_prot_incidents.assaulted_with_weapon == 0 | adult_prot_incidents.hindered_leave_settlement == 0 | adult_prot_incidents.forced_work == 0 | adult_prot_incidents.forcibly_detained == 0 | child_prot_incidents.assaulted_with_weapon == 0 | child_prot_incidents.hindered_leave_settlement == 0 | child_prot_incidents.forced_work == 0 | child_prot_incidents.forcibly_detained == 0) ~ 3, TRUE ~ 0 ), other_incidents_lsg = case_when( other_incidents == "sgbv" | other_concerns == "sgbv" | boy_marriage == "yes" | girl_marriage == "yes" ~ 3, TRUE ~ 0 ), prot_concerns_lsg = case_when( prot_concerns.violence_maiming == 1 | prot_concerns.violence_injuries == 1 | prot_concerns.psych_wellbeing == 1 | prot_concerns.abduction == 1 | prot_concerns.theft == 1 | prot_concerns.explosive_hazards == 1 | prot_concerns.destruction_property == 1 | prot_concerns.early_marriage == 1 | prot_concerns.other == 1 ~ 3, TRUE ~ 0 ), safety_lsg = case_when( safety == "poor" | safety == "very_poor" ~ 2, TRUE ~ 0 ) ) # protection_lsg class vars msni_protection_lsg_vars <- c( "prot_incidents_4_lsg", "prot_incidents_3_lsg", "other_incidents_lsg", "prot_concerns_lsg", "safety_lsg" ) # protection_lsg score data$msni_protection_lsg_score <- comp_score(data, msni_protection_lsg_vars) # protection_lsg severity data <- data %>% mutate( protection_lsg = case_when( msni_protection_lsg_score < 3 ~ 1, msni_protection_lsg_score > 2 & msni_protection_lsg_score < 6 ~ 2, msni_protection_lsg_score > 5 & msni_protection_lsg_score < 9 ~ 3, msni_protection_lsg_score >= 9 ~ 4 ) ) #### end protection_lsg # HC-LSG/WASH wash_lsg data <- data %>% mutate( water_source_lsg = case_when( water_source == "surface_water" ~ 3, water_source == "water_trucking" | water_source == "spring_unprotected" ~ 2, TRUE ~ 0 ), soap_lsg = case_when( soap == "no" ~ 3, TRUE ~ 0 ), latrine_lsg = case_when( latrine == "open" | latrine == "public_latrine" | waste_disposal == "open_space" ~ 3, latrine == "pit_latrine_uncovered" | waste_disposal == "burning" ~ 2, TRUE ~ 0 ), water_distance_lsg = case_when( water_distance == "over_1km" ~ 3, water_distance == "500m_to_1km" ~ 2, TRUE ~ 0 ) ) # wash_lsg class vars msni_wash_lsg_vars <- c( "water_source_lsg", "soap_lsg", "latrine_lsg", "water_distance_lsg" ) # wash_lsg score data$msni_wash_lsg_score <- comp_score(data, msni_wash_lsg_vars) # wash_lsg severity data <- data %>% mutate( wash_lsg = case_when( msni_wash_lsg_score < 3 ~ 1, msni_wash_lsg_score > 2 & msni_wash_lsg_score < 6 ~ 2, msni_wash_lsg_score > 5 & msni_wash_lsg_score < 9 ~ 3, msni_wash_lsg_score >= 9 ~ 4 ) ) # wash_lsg severity 2 data <- data %>% mutate( wash_lsg_2 = case_when( msni_wash_lsg_score < 3 ~ 1, msni_wash_lsg_score > 2 & msni_wash_lsg_score < 7 ~ 2, msni_wash_lsg_score > 6 & msni_wash_lsg_score < 9 ~ 3, msni_wash_lsg_score >= 9 ~ 4 ) ) # wash_lsg severity 3 data <- data %>% mutate( wash_lsg_3 = case_when( msni_wash_lsg_score < 3 ~ 1, msni_wash_lsg_score > 2 & msni_wash_lsg_score < 8 ~ 2, msni_wash_lsg_score > 7 & msni_wash_lsg_score < 10 ~ 3, msni_wash_lsg_score >= 10 ~ 4 ) ) #### end wash_lsg # HC-LSG/EiE - education_lsg data <- data %>% mutate( not_attending_lsg = case_when( percent_enrolled >= 0.75 & percent_enrolled <= 1 ~ 4, percent_enrolled >= 0.5 & percent_enrolled <= 0.749 ~ 3, percent_enrolled >= 0.25 & percent_enrolled <= 0.449 ~ 2, percent_enrolled >= 0 & percent_enrolled <= 0.249 ~ 1, TRUE ~ 0 ), education_level_lsg = case_when( highest_edu == "none" ~ 2, highest_edu == "primary" ~ 1, TRUE ~ 0 ), unattending_security_lsg = case_when( boy_unattendance_reason.insecurity == 1 | boy_unattendance_reason.child_works_instead == 1 | girl_unattendance_reason.insecurity == 1 | girl_unattendance_reason.child_works_instead == 1 ~ 3, TRUE ~ 0 ), unattending_cultural_lsg = case_when( boy_unattendance_reason.cultural_reasons == 1 | girl_unattendance_reason == 1 | boy_unattendance_reason.lack_facilities == 1 | girl_unattendance_reason.lack_facilities == 1 ~ 2, TRUE ~ 0 ), unattending_finance_doc_lsg = case_when( boy_unattendance_reason.lack_documentation == 1 | boy_unattendance_reason.too_expensive == 1 | boy_unattendance_reason.lack_teachers == 1 | girl_unattendance_reason.lack_documentation ==1 | girl_unattendance_reason.too_expensive == 1 | girl_unattendance_reason.lack_teachers == 1 ~ 1, TRUE ~ 0 ) ) # education_lsg class vars msni_education_lsg_vars <- c( "not_attending_lsg", "unattending_security_lsg", "unattending_cultural_lsg", "unattending_finance_doc_lsg", "education_level_lsg" ) # education_lsg score data$msni_education_lsg_score <- comp_score(data, msni_education_lsg_vars) # education_lsg severity data <- data %>% mutate( education_lsg = case_when( msni_education_lsg_score < 3 ~ 1, msni_education_lsg_score > 2 & msni_education_lsg_score < 6 ~ 2, msni_education_lsg_score > 5 & msni_education_lsg_score < 9 ~ 3, msni_education_lsg_score >= 9 ~ 4 ) ) #### end education_lsg ################################################# data <- data %>% filter(!is.na(province)) # fliter prolematic feilds uuid_filter <- c("ac3e8430-ba88-497b-9895-c1bd8da7f79e", "8ac61e9b-8ff8-4e4a-9619-1dc0ab31f396", "7171e0a8-3a40-4c57-b84d-a65f08115994", "596c244b-ea20-48ef-8218-023ac3f2831f") `%notin%` <- Negate(`%in%`) data <- data %>% filter(uuid %notin% uuid_filter ) # MSNI Indicator data$msni <- msni(education_lsg = data$education_lsg, fsl_lsg = data$fsl_lsg, health_lsg = data$health_lsg, protection_lsg = data$protection_lsg, shelter_lsg = data$shelter_lsg, wash_lsg = data$wash_lsg, capacity_gaps = data$capacity_gaps, impact = data$impact) data$msni2 <- msni(education_lsg = data$education_lsg, fsl_lsg = data$fsl_lsg_2, health_lsg = data$health_lsg, protection_lsg = data$protection_lsg, shelter_lsg = data$shelter_lsg, wash_lsg = data$wash_lsg_2, capacity_gaps = data$capacity_gaps, impact = data$impact) data$msni3 <- msni(education_lsg = data$education_lsg, fsl_lsg = data$fsl_lsg_3, health_lsg = data$health_lsg, protection_lsg = data$protection_lsg, shelter_lsg = data$shelter_lsg, wash_lsg = data$wash_lsg_3, capacity_gaps = data$capacity_gaps, impact = data$impact) data$msni_sev_high <- ifelse(data$msni==3|data$msni==4,1,0) # HHs found to have severe or extreme sectoral needs in one or more sectors # lsg_needs_2_cal data <- data %>% mutate( shelter_lsg_class = case_when( shelter_lsg == 3 | shelter_lsg == 4 ~ 1, shelter_lsg == 1 | shelter_lsg == 2 ~ 0, TRUE ~ NA_real_ ), fsl_lsg_class = case_when( fsl_lsg == 3 | fsl_lsg == 4 ~ 1, fsl_lsg == 1 | fsl_lsg == 2 ~ 0, TRUE ~ NA_real_ ), health_lsg_class = case_when( health_lsg == 3 | health_lsg == 4 ~ 1, health_lsg == 1 | health_lsg == 2 ~ 0, TRUE ~ NA_real_ ), protection_lsg_class = case_when( protection_lsg == 3 | protection_lsg == 4 ~ 1, protection_lsg == 1 | protection_lsg == 2 ~ 0, TRUE ~ NA_real_ ), wash_lsg_class = case_when( wash_lsg == 3 | wash_lsg == 4 ~ 1, wash_lsg == 1 | wash_lsg == 2 ~ 0, TRUE ~ NA_real_ ), education_lsg = case_when( education_lsg == 3 | education_lsg == 4 ~ 1, education_lsg == 1 | education_lsg == 2 ~ 0, TRUE ~ NA_real_ ) ) lsg_needs_2_cal_vars <- c( "shelter_lsg_class", "fsl_lsg_class", "health_lsg_class", "protection_lsg_class", "wash_lsg_class", "education_lsg" ) # lsg_needs_2_cal score data$lsg_needs_2_cal_score <- comp_score(data, lsg_needs_2_cal_vars) # lsg_needs_2_cal data <- data %>% mutate( lsg_needs_2_cal = case_when( lsg_needs_2_cal_score == 0 ~ "no_need", lsg_needs_2_cal_score == 1 ~ "one_need", lsg_needs_2_cal_score > 1 ~ "two_or_more_need" ) ) # msni drivers data <- data %>% mutate( fsl_wash_driver = case_when( fsl_lsg == 3 | fsl_lsg == 4 | wash_lsg == 3 | wash_lsg == 4 ~ "sectoral_need", fsl_lsg == 1 | fsl_lsg == 2 | wash_lsg == 1 | wash_lsg == 2 ~ "no_need", TRUE ~ NA_character_ ), impact_driver = case_when( ((impact == 3 | impact == 4) & (health_lsg == 3 | health_lsg == 4)) | ((impact == 3 | impact == 4) & (shelter_lsg == 3 | shelter_lsg == 4)) | ((impact == 3 | impact == 4) & (protection_lsg == 3 | protection_lsg == 4)) ~ "sectoral_need", TRUE ~ "no_need" ), shelter_driver_class = case_when( shelter_lsg == 3 | shelter_lsg == 4 ~ 1, TRUE ~ 0, ), protection_driver_class = case_when( protection_lsg == 3 | protection_lsg == 4 ~ 1, TRUE ~ 0 ), health_driver_class = case_when( health_lsg == 3 | health_lsg == 4 ~ 1, TRUE ~ 0 ), capacity_gaps_sev = case_when( capacity_gaps >=3 ~ "high", capacity_gaps <=2 ~ "low", TRUE ~ NA_character_ ) ) # esnfi_prot_health_driver esnfi_prot_health_driver_vars <- c( "shelter_driver_class", "protection_driver_class", "health_driver_class" ) # esnfi_prot_health_driver score data$esnfi_prot_health_driver_score <- comp_score(data, esnfi_prot_health_driver_vars) # lsg_needs_2_cal data <- data %>% mutate( esnfi_prot_health_driver = case_when( esnfi_prot_health_driver_score <= 1 ~ "no_need", esnfi_prot_health_driver_score >= 2 ~ "sectoral_need", ) ) ############### MSNI TEST ############### data <- data %>% mutate( hh_msni_one = case_when( education_lsg == 1 & fsl_lsg == 1 & health_lsg == 1 & protection_lsg == 1 & shelter_lsg == 1 & wash_lsg == 1 & capacity_gaps == 1 & impact == 1 ~ "1", TRUE ~ "1+" ), hh_msni_one_only_sectors = case_when( education_lsg == 1 & fsl_lsg == 1 & health_lsg == 1 & protection_lsg == 1 & shelter_lsg == 1 & wash_lsg == 1 ~ "1", TRUE ~ "1+" ) ) ######################################### #join main dataset var to hh roster data_sub <- data %>% select(final_displacement_status_non_displ, region_disagg, urban_disagg, hoh_sex_disagg, hoh_disabled_disagg, hoh_chronic_illness_disagg, hoh_elderly_disagg, displacements_disagg, literate_adult_disagg, lcsi_disagg, host_disagg, disp_length_disagg, hoh_sex2_disagg, behav_change_disagg, child_behav_change_disagg, tazkira_disagg3, hoh_debt_disagg , vulnerable_group_4, vulnerable_group_7, registered_dissagg, informal_settlement, child_tazkira_disagg, uuid) overall_hh_roster <- overall_hh_roster %>% mutate( school_age = case_when( hh_member_age >=6 & hh_member_age <= 18 ~ "school_age", TRUE ~ "not_school_age" ), current_year_attending_na_no = case_when( current_year_attending == "no" ~ "no", current_year_attending == "yes" ~ "yes", TRUE & school_age == "school_age" ~ "no" ), edu_removal_shock.no_sch_age = case_when( edu_removal_shock.no == 1 ~ 1, TRUE & school_age == "school_age" ~ 0 ), edu_removal_shock.conflict_sch_age = case_when( edu_removal_shock.conflict == 1 ~ 1, TRUE & school_age == "school_age" ~ 0 ), edu_removal_shock.displacement_sch_age = case_when( edu_removal_shock.displacement == 1 ~ 1, TRUE & school_age == "school_age" ~ 0 ), edu_removal_shock.natural_disaster_sch_age = case_when( edu_removal_shock.natural_disaster == 1 ~ 1, TRUE & school_age == "school_age" ~ 0 ), edu_removal_shock_sch_age = case_when( edu_removal_shock.no == 1 ~ "yes", TRUE & school_age == "school_age" ~ "no" ), hh_member_age_cat = case_when( hh_member_age >= 0 & hh_member_age < 6 ~ "0_5", hh_member_age > 5 & hh_member_age < 19 ~ "6_18", hh_member_age > 18 & hh_member_age < 60 ~ "19_59", hh_member_age > 59 ~ "60+" ), # demographic hh roster data hh_member_age_cat_gender = case_when( hh_member_age >= 0 & hh_member_age < 6 & hh_member_sex == "female" ~ "female_0_5", hh_member_age >= 0 & hh_member_age < 6 & hh_member_sex == "male" ~ "male_0_5", hh_member_age > 5 & hh_member_age < 19 & hh_member_sex == "female" ~ "female_6_18", hh_member_age > 5 & hh_member_age < 19 & hh_member_sex == "male" ~ "male_6_18", hh_member_age > 18 & hh_member_age < 60 & hh_member_sex == "female" ~ "female_19_59", hh_member_age > 18 & hh_member_age < 60 & hh_member_sex == "male" ~ "male_19_59", hh_member_age > 59 & hh_member_sex == "female" ~ "female_60+", hh_member_age > 59 & hh_member_sex == "male" ~ "male_60+" ), male_female_perc = case_when( hh_member_sex == "female" ~ "female", hh_member_sex == "male" ~ "male" ), ## request # 30 school_age_cat_gender = case_when( hh_member_age > 5 & hh_member_age < 13 & hh_member_sex == "female" ~ "female_6_12", hh_member_age > 12 & hh_member_age < 19 & hh_member_sex == "female" ~ "female_13_18", hh_member_age > 5 & hh_member_age < 13 & hh_member_sex == "male" ~ "male_6_12", hh_member_age > 12 & hh_member_age < 19 & hh_member_sex == "male" ~ "male_13_18", TRUE ~ NA_character_ ) ) ############## demographic hoh data ##################### hoh_data <- data %>% select( hh_member_sex = hoh_sex, hh_member_age = hoh_age, `_submission__uuid` = uuid, province, survey_village) %>% mutate( hh_member_age_cat_gender = case_when( hh_member_age >= 0 & hh_member_age < 6 & hh_member_sex == "female" ~ "female_0_5", hh_member_age >= 0 & hh_member_age < 6 & hh_member_sex == "male" ~ "male_0_5", hh_member_age > 5 & hh_member_age < 19 & hh_member_sex == "female" ~ "female_6_18", hh_member_age > 5 & hh_member_age < 19 & hh_member_sex == "male" ~ "male_6_18", hh_member_age > 18 & hh_member_age < 60 & hh_member_sex == "female" ~ "female_19_59", hh_member_age > 18 & hh_member_age < 60 & hh_member_sex == "male" ~ "male_19_59", hh_member_age > 59 & hh_member_sex == "female" ~ "female_60+", hh_member_age > 59 & hh_member_sex == "male" ~ "male_60+" ), male_female_perc = case_when( hh_member_sex == "female" ~ "female", hh_member_sex == "male" ~ "male" ), school_age_cat_gender = case_when( hh_member_age > 5 & hh_member_age < 13 & hh_member_sex == "female" ~ "female_6_12", hh_member_age > 12 & hh_member_age < 19 & hh_member_sex == "female" ~ "female_13_18", hh_member_age > 5 & hh_member_age < 13 & hh_member_sex == "male" ~ "male_6_12", hh_member_age > 12 & hh_member_age < 19 & hh_member_sex == "male" ~ "male_13_18", TRUE ~ NA_character_ ) ) hoh_data <- hoh_data %>% select( hh_member_sex, hh_member_age, hh_member_age_cat_gender, male_female_perc, school_age_cat_gender, province, survey_village, `_submission__uuid` ) roster_data <- overall_hh_roster %>% select( hh_member_sex, hh_member_age, hh_member_age_cat_gender, male_female_perc, school_age_cat_gender, province, survey_village, `_submission__uuid` ) combined_hoh_and_roster <- rbind(roster_data, hoh_data) # for demographic combined_hoh_and_roster_joined <- koboloops::add_parent_to_loop(combined_hoh_and_roster, data_sub, uuid.name.loop = "_submission__uuid", uuid.name.parent = "uuid") combined_hoh_and_roster_joined <- combined_hoh_and_roster_joined %>% mutate( hh_member_under_over_15 = case_when( hh_member_age <= 15 ~ "15_and_under", hh_member_age > 15 ~ "over_15", TRUE ~ NA_character_ ) ) write.csv(combined_hoh_and_roster_joined, "./input/data/recoded/hh_roster_hoh_demographic.csv", row.names = F) # for education questions hh_roster_joined <- koboloops::add_parent_to_loop(overall_hh_roster, data_sub, uuid.name.loop = "_submission__uuid", uuid.name.parent = "uuid") write.csv(hh_roster_joined, "./input/data/recoded/hh_roster.csv", row.names = F) write.csv(data, "./input/data/recoded/data_with_strata2.csv", row.names = F) ## Test
17d0b4508a89eda9690757bbd1a506dc8eba11fb
de83a2d0fef79a480bde5d607937f0d002aa879e
/P2C2M.SNAPP/R/draw.samples2.R
4afd6ee40fe1adb1f7db29b2654b926047494a2b
[]
no_license
P2C2M/P2C2M_SNAPP
0565abc0ea93195c9622dc5d4e693ccde17bebc7
94cd62285419a79f5d03666ec2ea3e818803d0db
refs/heads/master
2020-05-07T18:54:40.440000
2020-01-10T15:59:45
2020-01-10T15:59:45
180,788,408
2
0
null
null
null
null
UTF-8
R
false
false
1,099
r
draw.samples2.R
##### Randomly sample from posterior ##### draw.samples <- function(num_sims, gens_run, sample_unif){ # num.sims = user input # of simulations to perform; gens_run = # of markov steps saved; sample_unif = if true, sample posterior uniformly. Otherwise sample randomly burnin <- ceiling(gens_run * 0.10) non_burnin <- seq(burnin + 1, gens_run, 1) # get sequence of step numbers in non burnin posterior if (num_sims > length(non_burnin)){ # if # of simulations input is greater than the number of steps in the posterior post_samples <- non_burnin # use all non_burnin steps } else{ if (sample_unif == TRUE){ interval <- length(non_burnin) / num_sims # get interval to sample post_samples <- non_burnin[1] while (post_samples[length(post_samples)] + interval <= gens_run){ post_samples = c(post_samples, post_samples[length(post_samples)] + interval) } post_samples <- sapply(post_samples, floor) # round down } else{ post_samples <- sort(sample(non_burnin, num_sims)) # randomly sample steps } } return(post_samples) }
5e6123c9c6678ffff155f6d6bb0973954d846370
925c515b771a8ea7ca31cc530308d594c30fba07
/code/TableS3.R
3591bcb04a019b009fd1c4d141478c8c465a6176
[]
no_license
melofton/freshwater-forecasting-review
41ba42f0aee6180d7a731fcf838dccc8f7590588
c06097cbab6d88c1dc30d0f2c3cf8a3baddaeacc
refs/heads/main
2023-07-06T21:54:48.183000
2023-06-27T20:18:46
2023-06-27T20:18:46
478,673,588
0
1
null
2022-07-08T19:45:20
2022-04-06T18:05:25
R
UTF-8
R
false
false
541
r
TableS3.R
#Matrix analysis #Author: Mary Lofton #Date: 06JUL22 #clear environment rm(list = ls()) #set-up pacman::p_load(tidyverse, lubridate, cowplot,ggbeeswarm, viridis) #read in data dat5 <- read_csv("./data/cleaned_matrix.csv") ##Table 3 #### dat10 <- dat5 %>% mutate(ecosystem_type = ifelse(ecosystem == "river" | grepl("basin",other_ecosystem),"Lotic","Lentic")) colnames(dat10) tab3 <- dat10[,c(2,4,3,27,11,12,13,14,18,19,20,21,16,17,23)] %>% arrange(Year) tab3[16,"Year"] <- 2022 write.csv(tab3,"Table3.csv",row.names = FALSE)
1bc891cc48422875088ad36e2f4ff1053e811f2d
218aae83a9d0994561991ba8affe528f1e381457
/R/edgepoints.R
e7cee35ceeef11b83b9b9d0b6abfaa1dc7d09ef5
[]
no_license
cran/edci
4efcf830e8cec5d1522397140afd5650655b66b3
d24ed3f7d6bd543f5b1fa07b8db821d42c8fe795
refs/heads/master
2020-12-25T16:56:26.204000
2018-05-16T20:49:37
2018-05-16T20:49:37
17,718,677
0
0
null
null
null
null
UTF-8
R
false
false
3,698
r
edgepoints.R
edgepoints = function(data, h1n, h2n, asteps = 4, estimator = "kernel", kernel = "mean", score = "gauss", sigma = 1, kernelfunc = NULL, margin = FALSE) { epDelta = function(x) { if (x < 0) -1 else 1 } epAt = function(x, y) { if (x == 0) { if (y >= 0) pi/2 else pi/2 } else { atan(y/x) } } epR1 = function(theta, x, y) { sqrt(x^2 + y^2) * epDelta(x) * cos(epAt(x, y) - theta) } epR2 = function(theta, x, y) { sqrt(x^2 + y^2) * epDelta(x) * sin(epAt(x, y) - theta) } angle = matrix(double(length(data)), nrow=nrow(data)) value = matrix(double(length(data)), nrow=nrow(data)) es = NULL sc = NULL ms = sigma * max(data) if (estimator == "kernel") es = 0 else if (estimator == "median") es = 1 else if (estimator == "M_mean") es = 2 else if (estimator == "M_median") es = 3 else if (estimator == "test_mean") es = 5 else if (estimator == "test_median") es = 6 else stop("estimator \"", estimator, "\" unknown.") if (es==2 || es ==3) { if (score == "gauss") { sc = 0 } if (score == "huber") { sc = 1 #ms = sigma/2 } if (score == "mean") { sc = 9 } } env = ceiling(sqrt((h1n * nrow(data))^2 + (h2n * ncol(data))^2)) kernmat = NULL if (kernel == "mean" || es >= 5) { kern = 0 } else if (kernel == "linear") { kern = 1 } else if (kernel == "linear2") { kern = 2 } else if (kernel == "gauss") { kern = 3 } else if (kernel == "func") { kern = 4 kernmat = double(asteps * (2 * env + 1)^2) for (i in ((-env):env)) { for(j in ((-env):env)) { for (k in (0:(asteps - 1))) { theta = -pi/2 + (k * pi/asteps) x = epR1(theta, i/nrow(data), j/ncol(data))/h1n y = epR2(theta, i/nrow(data), j/ncol(data))/h2n kernmat[k * (2 * env + 1)^2 + (i + env) * (2 * env + 1) + (j + env) + 1] = kernelfunc(2 * x, y) } } } } else { stop("kernel \"",kernel,"\" unknown.") } if (es == 1) kern = 0 if (!is.null(es)) { result = .C("c_edgepoints", as.double(data), nrow(data), ncol(data), as.integer(kern), # kernel as.double(h1n), as.double(h2n), as.integer(es), as.integer(sc), # Typ der Scorefunktion as.double(sigma), # Sigma as.double(kernmat), # Gewichtsmatrix as.double(ms), # Max_Schritt as.integer(asteps), angle = angle, value = value, PACKAGE = "edci") } value = result$value angle = result$angle if (es == 5 || es == 6) value = -value if (margin == FALSE) { if (es == 5 || es == 6) v = 1 else v = 0 value[c(1:env,(nrow(value) - env + 1):nrow(value)), ] = v value[, c(1:env, (ncol(value) - env+1):ncol(value))] = v } else if (margin == "cut") { value = value[(env + 1):(nrow(value) - env), (env + 1):(ncol(value) - env)] angle = angle[(env + 1):(nrow(angle) - env), (env + 1):(ncol(angle) - env)] } list(value = value, angle = angle) } eplist = function(data, maxval, test = FALSE, xc = NULL, yc = NULL) { if (test == TRUE) { data[[1]] = -data[[1]] maxval = -maxval } n = sum(data[[1]] > maxval) if (is.null(xc)) xc = seq(1/nrow(data[[1]]), 1, 1/nrow(data[[1]])) if (is.null(yc)) yc = seq(1/ncol(data[[1]]), 1, 1/ncol(data[[1]])) o = order(data[[1]], decreasing = TRUE)[1:n] result = cbind(xc[(o - 1) %% nrow(data[[1]]) + 1], yc[(o - 1) %/% nrow(data[[1]]) +1 ], data[[2]][o]) colnames(result) = c("x", "y", "angle") result }
4e4ff604aaf7b5ff470c8227b043cf073c00c388
d3fdbf9442b8e0ffbc208ad50087f0ece05f405e
/Modulo 3- Resampling-Bayesianos-Markov/Ejercicio 3.3/Ejercicio3_3_MarianaSilvera.R
c9857fb242ead0825c194c8628a35108f8e2f36e
[]
no_license
msilvera/R-DataAnalysis2021-OTGA
b176f5f48076ce57ed1c7935fbe37ada31f21bda
1bc03219b4d36c73d2196534c111878476d4373d
refs/heads/main
2023-06-14T21:55:42.036000
2021-07-04T18:38:51
2021-07-04T18:38:51
380,082,123
0
0
null
null
null
null
UTF-8
R
false
false
947
r
Ejercicio3_3_MarianaSilvera.R
library(FSAdata) library(MASS) library(dplyr) #library(help="FSAdata") #cargo los datos #data <- WalleyeErie2 summary(WalleyeErie2) data <-subset(x=WalleyeErie2, subset = !is.na(w)) #elimino los datos incompletos summary(data) set.seed(1) # semilla para el random data <- data %>% mutate_at(vars("age"), factor) # transformo en factor la comlumna edad #extraigo el 80% de los datos para entrenamiento intrain <- sample(1:nrow(data), size = round(0.8*nrow(data))) #genero modelo para la edad en base a las demas variables lda.fit <-lda(age~. , data= data, subset= intrain) lda.fit #verifico que tan bien se comporta el discriminante lineal generado lda.pred <- predict(lda.fit, data) names(lda.pred) #obtenfo la clase lda.class <- lda.pred$class #construyo la matriz table(lda.class, data$age) #veo que tan bien se ajusta, utilizando la media mean(lda.class==data$age) #resultado, desempeño de : 0.6571231
eb3d9c97b02f6f8d4ca16e857d987432473f6d4c
89d2d6b83bb0fcad3db66b139a617b0cc40bf34a
/R3-Aliona.R
dfc622532aca8311dc0e2430e94dcfdf29a65c9b
[]
no_license
alionahst/R3
5e6760cab681ab10149267ed31884ccb16cc6eb5
d980eddc32efd762b3178bc3933b8ba486929944
refs/heads/master
2023-01-03T05:25:17.275000
2020-10-20T22:13:42
2020-10-20T22:13:42
305,684,425
0
0
null
null
null
null
UTF-8
R
false
false
2,799
r
R3-Aliona.R
#Chapter 3: Basic graphics and data - Aliona Hoste demo(graphics) plot(iris) #1. Plot a cheat-sheet with values of color and point type (col = , and pch = ) from 1 to 25, and export it as a jpeg of 15 cm wide, 6 cm high and resolution 100 points per cm. plot(0, 0, xlim = c(0, 26), ylim = c(0.5, 1.5) , ylab = "color", xlab = "color number", yaxt = "n") for (i in 1:25) { points(i, 1, pch = i, col = i, cex = 1.5) } jpeg(filename = "firstplot.jpeg", width = 15, height = 6, units = "cm", res = 100) plot(0, 0, xlim = c(0, 26), ylim = c(0.5, 1.5) , ylab = "colors & sign", xlab = "color number", yaxt = "n") for (i in 1:25) { points(i, 1, pch = i, col = i, cex = 1.5) } dev.off() #2. Plot into a graph ten Poisson distributions with lambda ranging from 1 to 10. Put legend and title. Export it as a .tiff file with size of 15x15 cm. x <- seq(-1, 20, 1) # Sequence y <- dpois(x, lambda = 1) # densities for x plot(x, y, type = "n") # Empty plot (type = "n") for(i in 1:10){ y <- dpois(x, lambda = i) lines(x, y, col = i) } title(main="Poisson distribution, lambda = 1:10") legend("topright", legend = paste("lambda =", 1:10),lty = 1, col = 1:10) #export into tiff plot tiff("Plot1_poisson_1to10.tiff", width = 15, height = 15, units = "cm", bg = "transparent", res = 150) # Open the device "Plot1.tiff" x <- seq(-1, 20, 1) # Sequence y <- dpois(x, lambda = 1) # densities for x plot(x, y, type = "n") # Empty plot (type = "n") for(i in 1:10){ y <- dpois(x, lambda = i) lines(x, y, col = i) } title(main="Poisson distribution, lambda = 1:10") legend("topright", legend = paste("lambda =", 1:10),lty = 1, col = 1:10) dev.off() #3. Import data from this article: https://peerj.com/articles/328/ Webcsv <- "https://dfzljdn9uc3pi.cloudfront.net/2014/328/1/Appendix1.csv" Data <- read.table(Webcsv, header = T, sep = ",", skip = 2) str(Data) #Be careful importing the data. Notice that you have to skip two first lines using “skip = 2”13. #With these data, using for(), plot graphs to represent the effect of all the numerical variables, from “richness” to “mean_quality” on “yield”. Choose the type of graph that you think better represents this effect for the different species. Create only one pdf with all the graphs inside. #To find the best graph for each type of data, a very helpful web is from Data to Viz https://www.data-to-viz.com/. plot(Data[-1]) plot(Data$mean_yield ~ Data$richness) for(i in names(Data[6:12])) { plot(Data$mean_yield ~ Data[[i]], ylab = "Mean yields", xlab = as.character(names(Data[i]))) title(main= paste("Mean yield in function of", as.character(names(Data[i])))) }
7015d5870ad5056141a600ab0b532cfd67a48a59
e56da52eb0eaccad038b8027c0a753d9eb2ff19e
/man-roxygen/tipsForTreeGeneration.R
b3874469bd8aa861c1cbae942f72fce3a7ff9898
[]
no_license
ms609/TreeTools
fb1b656968aba57ab975ba1b88a3ddf465155235
3a2dfdef2e01d98bf1b58c8ee057350238a02b06
refs/heads/master
2023-08-31T10:02:01.031000
2023-08-18T12:21:10
2023-08-18T12:21:10
215,972,277
16
5
null
2023-08-16T16:04:19
2019-10-18T08:02:40
R
UTF-8
R
false
false
174
r
tipsForTreeGeneration.R
#' @param tips An integer specifying the number of tips, or a character vector #' naming the tips, or any other object from which [`TipLabels()`] can #' extract leaf labels.
15f17c33f851b0ab97d37c7507f338f9cc08551e
d30fa10aa7b3837145a1d1f0bcff6a55372ea4eb
/plot_kmer_dist.R
a39c14daba7632aabe23b7da8c1d0a54f095915a
[]
no_license
mborche2/Matts_Satellite_Size_Code
541bfdada9a61238ecb6c59594dbfd5e60766e97
824fcf6e8f4ab555df774baa9cd8caf6dd8200ae
refs/heads/master
2023-03-28T07:29:31.677000
2021-03-23T18:57:52
2021-03-23T18:57:52
348,837,905
0
0
null
null
null
null
UTF-8
R
false
false
689
r
plot_kmer_dist.R
library(ggplot2) setwd("/n/core/bigDataAI/Genomics/Gerton/jennifer_gerton/jeg10/") for (i in 1:21){ filenam <- paste("plots/kmer_frequency_asp/kmer_frequency_",toString(i),"_array.tsv",sep = "") array_specifics <- read.table(filenam,header = FALSE) freq_table <- table(array_specifics[,2]) freq_df <- as.data.frame(freq_table) freq_df[,2] <- log(freq_df[,2]) filenam2 <- paste("kmer_frequency_",toString(i),"_array_standard_axes.png",sep="") png(filenam2) plot(freq_df,xlab="Number of Occurences of Kmer in Array",ylab="Log (ln) Frequency of Kmer Occurence Number",axes=FALSE) axis(side=1, at=seq(0,4000,by=25)) axis(side=2, at=seq(0, 10, by=1)) box() dev.off() }
393e68c42ae3b36432c1265386c913a44b8e6d7e
c97fa9aadc45c44fad6433ae10c772060bde355c
/MyNotes/03 - Geting and Cleaning Data/01 Class_Data.Table_Package.R
41cd46ae55c1ae3679c91b186b783fad89090d5a
[]
no_license
vitorefigenio/datasciencecoursera
9866816242d39fa9fc9520bc4d543efc815afeb5
03722d0c7c6d219ec84f48e02065493f6657cc0a
refs/heads/master
2021-01-17T11:17:58.099000
2016-02-28T03:06:37
2016-02-28T03:06:37
29,034,385
0
0
null
null
null
null
ISO-8859-1
R
false
false
943
r
01 Class_Data.Table_Package.R
#data.table package # Create Data.Table install.packages("data.table") library(data.table) DF = data.frame(x=rnorm(9), y=rep(c("a","b","c"), each=3), z=rnorm(9)) head(DF,3) DT = data.table(x=rnorm(9), y=rep(c("a","b","c"), each=3), z=rnorm(9)) head(DT,3) # comando ara ver tdas as abelas criadas na memória tables() # Subsetting rows DT[2,] DT[DT$y=="a"] DT[c(2,3)] # Subseting columns DT[,c(2,3)] # É comum o uso de expressões { x=1 y=2 } k = {print(10);5} print(k) # Calculating values for variables with expressions DT[,list(mean(x),sum(z))] DT[,table(y)] # Adding new column DT[,w:=z^2] DT # Multiple Operations DT[,m:={tmp <- (x+z); log2(tmp+5)}] plot(DT[,m]) # plyr like operations DT[, a:=x>0] DT[,b:= mean(x+w), by=a] DT # Special Variables set.seed(123) DT <- data.table(x=sample(letters[1:3], 1E5, TRUE)) DT[, .N, by=x] # keys DT = data.table(x=rep(c("a","b","c"), each=100), z=rnorm(300)) setkey(DT,x) DT['a']
12d5a52eb7e5fb10a0b5d87bdc8740c29b7c2a5a
39315660a0226ae527ec8e0c7e6ae866df675b5f
/exercise1/computeCost.R
5057e5c02d42dd31073fb2393dff4c7ded690bc3
[]
no_license
Lemmawool/R-Practice
28a7ce208f7d012eb4bc886fdb27b72754a171e9
0c3bed53e27953e9f19f92fd6e7b595a7e379262
refs/heads/master
2021-05-14T13:44:03.051000
2018-01-22T02:02:51
2018-01-22T02:02:51
115,955,944
0
0
null
null
null
null
UTF-8
R
false
false
105
r
computeCost.R
computeCost <- function(X, y, theta){ m = length(y) return ((1/(2*m)) * sum((X %*% theta - y) ^ 2)) }
e662f9c90536aa7a7802ef2046cda55ac460d02e
63227ea5a4085bb789824448502c95a98d8f375f
/cachematrix.R
4e87ebeb3d25a82fe63b07127301dae99ce920d6
[]
no_license
lfdelama/ProgrammingAssignment2
f81f6ae4cf9246cc21a2fce019bc59a04949303d
417909969f9fdd8c4d23700e1fcf535237a2c2ec
refs/heads/master
2020-12-24T14:18:50.589000
2014-05-22T21:32:07
2014-05-22T21:32:07
null
0
0
null
null
null
null
UTF-8
R
false
false
1,314
r
cachematrix.R
## These two functions below are used to cache the inverse of a square matrix, ## so every time the same inverse is required, it doesn't need to be recomputed. ## This function creates a special matrix which ## contains a list of the following functions: ## - set, to set the value of the matrix ## - get, to get the value of the matrix ## - setinverse, to set the value of the inverse of the matrix ## - getinverse, to get the value of the inverse of the matrix makeCacheMatrix<- function(x = matrix()) { inv <- NULL set <- function(y) { x <<- y inv <<- NULL } get <- function() x setinverse <- function(inverse) inv <<- inverse getinverse <- function() inv list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ## This function calculates and returns the inverse of the special matrix that ## it was created with the above function. ## If the inverse of the matrix has previously calculated, this function will return ## directly the value stored in the cache of the makeCacheMatrix function. cacheSolve <- function(x, ...) { inv <- x$getinverse() if(!is.null(inv)) { message("getting cached data") return(inv) } data <- x$get() inv <- solve(data, ...) x$setinverse(inv) inv }
48f4c3afd8bf9957f151bbbad760e9b7f9c317fe
64e7ac1d0437b1d874b4ed070e6bda152decddee
/plot2.R
e2892d66195304ed5b560890e85b152215d7920e
[]
no_license
mooctus/ExData_Plotting1
072db8facebd27a8a8aab985be057b9b2c2b8122
005cba7dd9d88e94113a57eb6f8d77b9a3618811
refs/heads/master
2021-01-12T20:07:17.994000
2014-05-09T15:54:17
2014-05-09T15:54:17
null
0
0
null
null
null
null
UTF-8
R
false
false
569
r
plot2.R
Sys.setlocale(category = "LC_ALL", locale = "C") df <- read.table(file="household_power_consumption.txt", sep=";", na.strings="?", header=TRUE) df$Time <- strptime( paste0(df$Date, " ", df$Time), format=paste0("%d/%m/%Y %H:%M:%S") ) df$Date <- as.Date(df$Date,format="%d/%m/%Y") df1 <- df[df$Date %in% as.Date(c('2007-02-01', '2007-02-02')),] png(filename="plot2.png",width=480, height=480) with (df1, plot(Time, Global_active_power, type="n", xlab="", ylab="Global Active Power (kilowatts)") ) with (df1, lines(Time, Global_active_power) ) dev.off()
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
31