blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 327 | content_id stringlengths 40 40 | detected_licenses listlengths 0 91 | license_type stringclasses 2 values | repo_name stringlengths 5 134 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 46 values | visit_date timestamp[us]date 2016-08-02 22:44:29 2023-09-06 08:39:28 | revision_date timestamp[us]date 1977-08-08 00:00:00 2023-09-05 12:13:49 | committer_date timestamp[us]date 1977-08-08 00:00:00 2023-09-05 12:13:49 | github_id int64 19.4k 671M ⌀ | star_events_count int64 0 40k | fork_events_count int64 0 32.4k | gha_license_id stringclasses 14 values | gha_event_created_at timestamp[us]date 2012-06-21 16:39:19 2023-09-14 21:52:42 ⌀ | gha_created_at timestamp[us]date 2008-05-25 01:21:32 2023-06-28 13:19:12 ⌀ | gha_language stringclasses 60 values | src_encoding stringclasses 24 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 7 9.18M | extension stringclasses 20 values | filename stringlengths 1 141 | content stringlengths 7 9.18M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d3d1b445c5563e9d8fc13d8b4f6b0659103e860b | 70c6f5c7eac898411bb1900de776111535fb624f | /cachematrix.R | 52cfa5d4ceb0a5be2dade27627f4bafcadb7391d | [] | no_license | bfurlan/ProgrammingAssignment2 | 82b2541d12659a56a15f5e3da476eb822eddc391 | 95fc7d6a1b32e0dfb27fe179b357360051a90b2e | refs/heads/master | 2020-04-06T06:25:18.534067 | 2014-12-20T12:51:18 | 2014-12-20T12:51:18 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,069 | r | cachematrix.R | ## Put comments here that give an overall description of what your
## functions do
## creates a special "matrix" object that can cache its inverse.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
#set orig. matrix
set <- function(y) {
x <<- y
inv <<- NULL
}
#get orig. matrix
get <- function() x
#set inv matrix
setinv <- function(i) inv <<- i
#get inv matrix
getinv <- function() inv
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
## computes the inverse of the special
# "matrix" returned by `makeCacheMatrix` above. If the inverse has
# already been calculated (and the matrix has not changed), then
# `cacheSolve` should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
#if it is cashed return inv
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
#otherwise calculate inv. matrix and keep it
data <- x$get()
inv <- solve(data, ...)
x$setinv(inv)
inv
}
|
66580b0951ce350974022c48803c702be653f9e3 | ec1e4c46e8ed66233147de96e95a84d638d57079 | /cachematrix.R | 3c36d81a56a9ae8b43bffbbedac1f8f18b5e0c34 | [] | no_license | satbirminhas/ProgrammingAssignment2 | 4874119fbe9cc41a400fe23b70a2663275024207 | bd918e299fff673d67f364d2000c8f116d70f33d | refs/heads/master | 2021-01-22T17:17:56.470174 | 2015-06-19T11:33:26 | 2015-06-19T11:33:44 | 37,606,484 | 0 | 0 | null | 2015-06-17T16:21:27 | 2015-06-17T16:21:27 | null | UTF-8 | R | false | false | 1,279 | r | cachematrix.R | ## These functions provide a mechanism to cache the Inverse of a given matrix by
## utilizing the scoping rules in R
## This function creates a special matrix that contains a function to
## 1. set the value of the matrix
## 2. get the value of the matrix
## 3. set the value of inverse
## 4. get the value of inverse
makeCacheMatrix <- function(x = matrix())
{
inv <- NULL
set <- function (y)
{
x <<- y #Set the value of matrix
inv <<- NULL
}
get <- function () #Get the value of matrix
{
x
}
setinv <- function (inverse)
{
inv <<- inverse
}
getinv <- function ()
{
inv
}
#Return a list of functions
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
## This function would compute the inverse of the matrix. However, if the
## inverse is already available in the cache, the value from cache is returned
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
#Get inverse value from the cache
inv <- x$getinv()
if(!is.null(inv)) #inverse is available in cache
{
message("Getting inverse from cache")
return(inv)
}
data <- x$get()
inv <- solve(data, ...) #compute the inverse
x$setinv(inv)
inv
}
|
73c3bbbbc8d6e8708148cdaedf30bb6f9d0e0cc4 | 48705854e259262e4860d36f9ec805044641ca0a | /fun/tryMaxTimes.r | 825c245c5801191e153514ecfbd14632b1ba36e5 | [] | no_license | fxi/LebaMod | 9042b37a1c8762f21a5b3860c19ec05aae533c0d | c7933bb6b83b6c1f6b5c649ca95583404e4dbf0d | refs/heads/master | 2021-01-01T18:37:27.540506 | 2014-07-29T08:59:33 | 2014-07-29T08:59:33 | 22,042,033 | 1 | 1 | null | null | null | null | UTF-8 | R | false | false | 644 | r | tryMaxTimes.r |
tryMaxTimes <- function(expr,maxTry=3,delay=1) {
stopifnot(is.expression(expr))
i=1
test=F
while (i==1 | !test ) {
message('TryMaxTimes. t=',i)
res <- try(eval(expr,envir=parent.frame()))
wMsg=paste(expr,'failed. ',maxTry-i,' try left.')
fMsg=paste(expr,'failed after ',i,' try')
#ifelse(!isTRUE(res)|i<maxTry,{Sys.sleep(delay);warning(wMsg);i=i+1},{test=T;return(res)})
if(class(res)=='try-error' & i<maxTry){
Sys.sleep(delay)
warning(wMsg)
i=i+1
}else if(class(res)=='try-error' & i>=maxTry){
test=T
warning(fMsg)
return(res)
}else{
test=T
return(res)
}
}
}
|
0280d456f10afc503ee709c95a076fbc97ace36f | 9f94e2dc159f10282930049004d0bbcffd6728b9 | /analysis/publication.R | 70dde75239b706dc1b9476316744d007e3ef3729 | [] | no_license | louis21228/ca-parkinsons | 6506a7ddcede3b231bfde97f33c23898d5d6d04f | 2f6beedd2954938d210fb47c380b79880bf174e4 | refs/heads/master | 2020-06-13T14:52:35.389704 | 2017-11-13T03:03:00 | 2017-11-13T03:03:00 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 38,378 | r | publication.R | # Cleaning up and presenting data
# Because I need to learn Sweave at some poin
library(doBy)
library(xtable)
library(reshape)
library(grid)
library(RColorBrewer)
library(gridExtra)
library(plyr)
library(infotheo)
library(ggplot2)
library(rtf) # For outputting to microsoft word
library(gplots)
library(reshape2)
library(scales)
# constants ====
nmsd.symptoms <- c(
NMS.D.NAMES,
"Tremor",
"Bradykinesia",
"Rigidity",
"Axial",
'Cluster'
)
nmsd.extra <- c(
'Age',
'Sex',
'PD_onset',
'PD_duration',
'CISI_PD_total',
'ldopa',
'Surgery',
'Cluster'
)
# Depends on valid cluster assignment, assert that the distribution is
# table(clus4.wide$cluster)
# 1 2 3 4
# 406 189 221 88
# V-measure ====
# always useful...
v.measure <- function(a, b) {
mi <- mutinformation(a, b)
entropy.a <- entropy(a)
entropy.b <- entropy(b)
if (entropy.a == 0.0) {
homogeneity <- 1.0
} else {
homogeneity <- mi / entropy.a
}
if (entropy.b == 0.0) {
completeness <- 1.0
} else {
completeness <- mi / entropy.b
}
if (homogeneity + completeness == 0.0) {
v.measure.score <- 0.0
} else {
v.measure.score <- (2.0 * homogeneity * completeness
/ (homogeneity + completeness))
}
# Can also return homogeneity and completeness if wanted
c(homogeneity, completeness, v.measure.score)
}
# ON NONMOTOR DOMAINS ====
# Somewhat oddly, the correct clustering vector lies in trees$clusters4$clustering$cluster
present <- reshape::rename(raw.omitted, gsub("/", "_", PUB.MAP))
present.full <- reshape::rename(raw.omitted.full, gsub("/", "_", PUB.MAP))
present$Cluster <- cl$cluster
present.full$Cluster <- cl$cluster
# Funcs for latex
mean.sd <- function(data, sig = 2) {
paste(round(mean(data), sig), " (", round(sd(data), sig), ")", sep = "")
}
get.xtable <- function(df, file = NULL) {
summary.t <- t(summaryBy(. ~ Cluster, df, FUN = function(x) mean.sd(x, sig = 1), # Only 1 decimal
keep.names = TRUE))
# Get rid of "cluster" row
summary.t <- summary.t[-which(rownames(summary.t) == 'Cluster'), ]
xtable(summary.t,
sanitize.colnames.function = function(x) gsub(pattern = '\\_', replacement = '/', x = x))
}
to.latex <- function(df, file = NULL) {
xt <- get.xtable(df, file = file)
print(xt, type = "latex", file = file, booktabs = TRUE)
}
# Redo ANOVA + bonferroni correction.
# Apparently Tukey takes care of multiple comparisons but make sure that's not a
# setting or grouping you need to actually make happen in R.
to.latex(present, "../writeup/manuscript/include/nmsd_summaries.tex")
to.latex(present.full[, gsub("/", "_", nmsd.extra)], "../writeup/manuscript/include/nmsd_extra.tex")
# Publication-ready dendrogram ====
remove.domain.n <- function(s) {
splitted <- strsplit(s, '-')[[1]]
if (length(splitted) == 1) {
s
} else {
splitted[3]
}
}
rid.of.middle <- function(s) {
splitted <- strsplit(s, '-')[[1]]
if (length(splitted) == 1) {
s # No -, leave it alone
} else {
# Get rid of that middle one
# Could get rid of preceding d as well
domain <- splitted[1]
symp <- splitted[3]
paste(domain, symp, sep = '-')
}
}
hm.m$colDendrogram <- hm.m$colDendrogram %>% sort(type = "nodes")
labels.wo.d <- unname(sapply(labels(hm.m$colDendrogram), rid.of.middle))
color.vec <- ifelse(labels.wo.d %in% MOTOR.SYMPTOMS, "blue", "black")
# TODO: Capitalize map if necessary
cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")
par(mar=c(3, 4, 0.5, 0))
hm.m$colDendrogram %>%
set("labels", labels.wo.d) %>%
set("branches_lwd", 2) %>%
hang.dendrogram(hang_height = 3) %>%
color_branches(k = 6, col = cbPalette[2:7]) %>%
# set("branches_k_color", k = 5, col = brewer.pal(8, 'Dark2')[4:8]) %>%
# Here, "1" is motor, "2" is nonmotor (sorting by nodes is convenient here)
color_labels(col = color.vec) %>%
plot(ylim = c(10, 45))#, xlab = "Symptom", ylab = "Height")
dev.copy(pdf, "../figures/nms30m-colhc-pub.pdf", width = 15, height = 8)
dev.off()
# Publication-ready boxplots ====
dev.off()
clus <- clus4.long
# Get rid of extra
clus.pub <- clus
clus.pub <- clus.pub[clus.pub$variable != "sex", ]
clus.pub$variable <- sapply(clus.pub$variable, function(s) paste("\n", PUB.MAP.N[as.character(s)][[1]], "\n", sep = ""))
clus.pub$variable <- factor(clus.pub$variable)
clus.pub$variable <- factor(clus.pub$variable, levels(clus.pub$variable)[c(1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 17, 18, 14, 13, 10, 16, 15)])
# Add types. Need to do after factors have been reorganized for some reason
clus.pub$Type <- ""
clus.pub[clus.pub$variable %in%
sapply(NMS.D, function(s) paste("\n", PUB.MAP.N[as.character(s)][[1]], "\n", sep = "")), ]$Type <- "Nonmotor (analyzed)"
clus.pub[clus.pub$variable %in% factor(c("\nAxial\n", "\nRigidity\n", "\nBradykinesia\n", "\nTremor\n", "\nMotor_comp\n")), ]$Type <- "Motor (analyzed)"
clus.pub[!(clus.pub$Type %in% c("Nonmotor (analyzed)", "Motor (analyzed)")), ]$Type <- "Other (not analyzed)"
clus.pub$Type <- factor(clus.pub$Type, levels = c('Nonmotor (analyzed)', 'Motor (analyzed)', 'Other (not analyzed)'))
p <- ggplot(clus.pub, aes(x = factor(cluster), y = measurement, fill = factor(cluster))) +
geom_boxplot() +
guides(fill = FALSE) +
facet_wrap( ~ variable, scales = "free") +
xlab("") +
ylab("") +
theme_pub() +
theme(strip.background = element_blank(), strip.text = element_text(lineheight = 0.4)) +
scale_fill_manual(values = brewer.pal(8, "Set2")[1:4])
# print(p)
dummy <- ggplot(clus.pub, aes(x = factor(cluster), y = measurement)) +
facet_wrap( ~ variable, scales = "free") +
geom_rect(aes(fill = Type), xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) +
theme_minimal() +
theme(strip.text = element_text(lineheight = 0.4, size = 14),
legend.text = element_text(size = 14),
legend.title = element_text(size = 16)) +
labs(fill = "Variable Type") +
scale_fill_manual(values = brewer.pal(8, "Set2")[c(5:7)]) +
theme(legend.position = c(0.7, 0.11))
# dummy
# Terribly complicated way to add colors
# http://stackoverflow.com/questions/19440069/ggplot2-facet-wrap-strip-color-based-on-variable-in-data-set
library(gtable)
g1 <- ggplotGrob(p)
g2 <- ggplotGrob(dummy)
gtable_select <- function (x, ...)
{
matches <- c(...)
x$layout <- x$layout[matches, , drop = FALSE]
x$grobs <- x$grobs[matches]
x
}
panels <- grepl(pattern="panel", g2$layout$name)
strips <- grepl(pattern="strip_t", g2$layout$name)
legends <- grepl(pattern="guide-box", g2$layout$name)
g2$layout$t[panels] <- g2$layout$t[panels] - 1
g2$layout$b[panels] <- g2$layout$b[panels] - 1
new_strips <- gtable_select(g2, panels | strips | legends)
grid.newpage()
grid.draw(new_strips)
gtable_stack <- function(g1, g2){
g1$grobs <- c(g1$grobs, g2$grobs)
g1$layout <- transform(g1$layout, z= z-max(z), name="g2")
g1$layout <- rbind(g1$layout, g2$layout)
g1
}
## ideally you'd remove the old strips, for now they're just covered
new_plot <- gtable_stack(g1, new_strips)
grid.newpage()
grid.draw(new_plot)
dev.copy(pdf, "../figures/kmeans-summaries-4-pub.pdf", width = 14, height = 10)
dev.off()
# Anova with bonferroni correction on c1====
clus4.wide.st <- cbind(raw.omitted, cluster = cl$cluster)
clus4.wide.st <- clus4.wide.st[, -which(names(clus4.wide.st) %in% NMS.30)]
# Why isn't this already a factor? Really confused
# Because it wasn't set in clusters.raw - if this is a bad thing lmk
clus4.wide.st$cluster <- as.factor(clus4.wide.st$cluster)
# Just NMS
clus4.wide.st <- clus4.wide.st[, c(NMS.D, "axial", "rigidity", "bradykin", "tremor", "scmmotcp", "cluster", "cisitot", "age", "pdonset", "durat_pd")]
# Assuming 1st column is cluster (which it should be)
oneways <- lapply(colnames(clus4.wide.st[, -which(colnames(clus4.wide.st) %in% c("cluster"))]), function(col) {
fm <- substitute(i ~ cluster, list(i = as.name(col)))
oneway.test(fm, clus4.wide.st)
})
for (test in oneways) {
# Bonferroni correction INCLUDING SEX since we need that divisor even though
# we're not actually testing here (binary tests later will do the same)
if (test$p.value < (0.05 / (length(oneways)))) { # BONFERRONI CORRECTION!
cat('sig\n')
} else {
cat('INSIG:\n')
cat(test$data.name, '\n')
}
}
# Redo tukey's for sanity
tukeys <- lapply(colnames(clus4.wide.st[, -which(colnames(clus4.wide.st) %in% c("cluster"))]), function(col) {
# Doesn't work the oneway way for some reason!
fm <- as.formula(paste(col, '~ cluster'))
TukeyHSD(aov(fm, clus4.wide.st))$cluster
})
names(tukeys) <- colnames(clus4.wide.st[, -which(colnames(clus4.wide.st) %in% c("cluster"))])
# Now output the insignificant diferences only
throwaway <- sapply(names(tukeys), function(name) {
tkdf <- as.data.frame(tukeys[name][[1]])
# Bonferroni correction needed. Notice PDONSET doesn't matter, but I divide by
# tukeys length anyways - just to accomodate for the extra
# sex chi-square comparison
sigs <- rownames(tkdf[tkdf[["p adj"]] >= 0.05 / (length(tukeys)), ])
if (length(sigs) > 0) {
cat(name, ": ", sep = "")
cat(sigs, "\n")
}
})
# Redo for age/sex/pdonset/duratpd/cisitot on c1 not anymore since I check them all
# From nms30 ====
# Assert that we have
# c(509, 97, 249, 49)
# nms30.present <- cbind(raw.omitted, cluster = cl.s$cluster)
nms30.present <- cbind(raw.omitted, cluster = testing$cluster)
# Get rid of domains
nms30.present <- nms30.present[, -which(names(nms30.present) %in% NMS.D)]
# Rearrange factors
# How to determine order: first figure out cluster with revalue, set factor
# levels = c(1, 2, 3, 4, 5, 6). Then observe ordering of factors, and reverse that
nms30.present$cluster <- factor(nms30.present$cluster)
nms30.present$cluster <- revalue(nms30.present$cluster, c("1" = "1", "6" = "2", "5" = "3", "2" = "4",
"4" = "5", "3" = "6"))
nms30.present$cluster <- factor(nms30.present$cluster, levels = c("1", "2", "3", "4", "5", "6"))
nms30.present <- reshape::rename(nms30.present, PUB.MAP)
nms30.present <- reshape::rename(nms30.present, NMS.30.LONG.SHORT.MAP)
nms30.extra.cols <- c("Age", "Sex", "PD_onset", "PD_duration", "CISI_PD_total", "Cluster")
# to.latex(nms30.present[, c(NMS.30.NAMES.PUB, MOTOR.PUB, "Cluster")],
# "../writeup/manuscript/include/nms30_summaries.tex")
# to.latex(nms30.present[, nms30.extra.cols],
# "../writeup/manuscript/include/nms30_extra.tex")
to.latex(nms30.present[, c(NMS.30.NAMES.PUB, MOTOR.PUB, "Cluster")],
"../writeup/manuscript/include/nms30_summaries_6.tex")
to.latex(nms30.present[, nms30.extra.cols],
"../writeup/manuscript/include/nms30_extra_6.tex")
to.latex(nms30.present,
"../writeup/manuscript/include/nms30_6.tex")
# nms30 same drill, anova + tukey ====
# NOTE: cluster is captalized here since I'm using the PUB df
oneways <- lapply(colnames(nms30.present[, -which(colnames(nms30.present) %in% c("Cluster"))]), function(col) {
fm <- substitute(i ~ Cluster, list(i = as.name(col)))
oneway.test(fm, nms30.present)
})
for (test in oneways) {
# Bonferroni correction but I also erroneously check sex, so subtract one
if (test$p.value < (0.05 / (length(oneways)))) { # BONFERRONI CORRECTION!
cat('sig\n')
} else {
cat('INSIG:\n')
cat(test$data.name, '\n')
}
}
# Redo tukey's for sanity
tukeys <- lapply(colnames(nms30.present[, -which(colnames(nms30.present) %in% c("Cluster"))]), function(col) {
# Doesn't work the oneway way for some reason!
fm <- as.formula(paste(col, '~ Cluster'))
TukeyHSD(aov(fm, nms30.present))$Cluster
})
names(tukeys) <- colnames(nms30.present[, -which(colnames(nms30.present) %in% c("Cluster"))])
# Now output the insignificant diferences only
. <- sapply(names(tukeys), function(name) {
tkdf <- as.data.frame(tukeys[name][[1]])
# Tremor and PD onset aren't significant, -2. I check sex later, + 1.
# But sex wasn't sigificant, + 1.
sigs <- rownames(tkdf[tkdf[["p adj"]] >= 0.05 / length(tukeys), ])
if (length(sigs) > 0) {
cat(name, ": ", sep = "")
cat(sigs, "\n")
}
})
# Gender binomial tests ====
print.proportions <- function(mat) {
cat("Sex (\\% Male) ")
sapply(1:dim(mat)[1], function(i) {
v <- mat[i, ]
cat("& ", round(v[1] / (v[1] + v[2]), 2) * 100, " ", sep = "")
})
cat("\\\\\n")
}
combs.1to4 <- combn(1:4, 2)
combs.1to6 <- combn(1:6, 2)
# For nmsd
present.sex <- table(present[c("Cluster", "Sex")])
print.proportions(present.sex)
# Is this p value less than 0.5 / 19. Nope!
chisq.test(present.sex)
# Welp, pairwise prop test is a much easier way to do this
# We would be interested in 0.5 / 18 here
pairwise.prop.test(present.sex, p.adjust = "bonferroni")
# Look for those that are less than 0.5 / ?
# . <- apply(combs.1to4, MARGIN = 2, FUN = function(comb) {
# pt <- prop.test(nms30.sex[comb, ])
# if (pt$p.value < (0.05 / dim(combs.1to4)[2])) { # Bonferroni correction
# cat("SIG:\n")
# cat("Cluster ", comb[1], " and ", comb[2], "\n", sep = "")
# print(pt)
# }
# })
# For nms30
nms30.sex <- table(nms30.present[c("Cluster", "Sex")])
print.proportions(nms30.sex)
chisq.test(nms30.sex)
# For this one we use 0.05 / 40
pairwise.prop.test(nms30.sex, p.adjust = "bonferroni")
# Look for those that are less than 0.05 / 40 if you care about
. <- apply(combs.1to6, MARGIN = 2, FUN = function(comb) {
pt <- prop.test(nms30.sex[comb, ])
if (pt$p.value < (0.05 / dim(combs.1to6)[2])) { # Bonferroni correction
cat("SIG:\n")
cat("Cluster ", comb[1], " and ", comb[2], "\n", sep = "")
print(pt)
}
})
# Correct nmsd heatmap ====
library(tidyr)
# This uses clus.pub from boxplots section
clus.heatmap = clus4
clus.heatmap[-which(colnames(clus.heatmap) == 'cluster')] = scale(clus.heatmap[-which(colnames(clus.heatmap) == 'cluster')])
clus.heatmap.summary = summaryBy(. ~ cluster, clus.heatmap, keep.names = T)
clus.heatmap.summary$cluster = NULL
clus.heatmap.summary = t(clus.heatmap.summary)
clus.heatmap.summary = clus.heatmap.summary[!(rownames(clus.heatmap.summary) %in% NMS.30), ]
# Reorder
clus.heatmap.summary = clus.heatmap.summary[c(6:14, 18, 16, 17, 15, 19, 5, 1, 3, 4), ]
rownames(clus.heatmap.summary) = c(NMS.D.MAP.PUB.N[rownames(clus.heatmap.summary)[1:9]], PUB.MAP[rownames(clus.heatmap.summary)[10:18]])
color.nonmotor = brewer.pal(8, "Dark2")[5]
color.motor = brewer.pal(8, "Dark2")[6]
color.other = brewer.pal(8, "Dark2")[7]
plot.new()
heatmap.2(as.matrix(clus.heatmap.summary), Rowv = FALSE, Colv = FALSE, dendrogram = 'none', trace = 'none',
# cellnote = as.matrix(hm.nms30.data.t),
col = colorRampPalette(rev(brewer.pal(11, 'RdBu')))(n = 250),
# RowSideColors = c(rep(gch[1], 2), rep(gch[2], 4), rep(gch[3], 6), rep(gch[4], 3), rep(gch[5], 3),
# rep(gch[6], 3), rep(gch[7], 3), rep(gch[8], 2), rep(gch[9], 4), rep(gch[10], 4)),
xlab = 'Cluster', key.xlab = 'z-score',
colRow = c(rep(color.nonmotor, 9), rep(color.motor, 5), rep(color.other, 4)),
# RowSideColors = c(rep(color.nonmotor, 9), rep(color.motor, 5), rep(color.other, 4)),
# If ^^^ then make rbind c(0, 4, 0) c(3, 2, 1) c(0, 5, 0)
# and lwid c(0.3, 2, 0.3)
cexCol = 1.5, cexRow = 1.2, srtCol = 0,
margins = c(5, 18),
# Draw lines to separate categories
rowsep = c(9, 14),
sepcolor = "white",
sepwidth = c(0.1, 0.1),
lmat = rbind(c(0,3),c(2,1),c(0,4)),
lwid = c(0.3,2),
lhei = c(0.6,4,1),
keysize = 1,
# key.xtickfun = function() { list(at = NULL) },
key.par = list(mar = c(7, 8, 3, 12)),
density.info = 'none'
)
legend("top", # location of the legend on the heatmap plot
legend = c("Nonmotor (analyzed)", "Motor (analyzed)", "Other (not analyzed)"), # category labels
col = c(color.nonmotor, color.motor, color.other),
lty = 1,
lwd = 10,
bty = 'n',
cex = 0.9
)
if (TRUE) {
# Always write, for now
# NOTE: I crop this in preview afterwards because it still has some
# dead space
dev.copy(pdf, "../figures/nmsd-hm-pub.pdf", width = 7, height = 10)
dev.off()
}
# Correct nms30 heatmap ====
hm.nms30.raw.scaled <- nms30.present
# Gender no need
hm.nms30.raw.scaled$Sex <- NULL
# Nullify cluster then reattach once you've scaled
hm.nms30.raw.scaled$Cluster <- NULL
hm.nms30.raw.scaled <- as.data.frame(scale(hm.nms30.raw.scaled))
hm.nms30.raw.scaled$Cluster <- nms30.present$Cluster
hm.nms30.data <- summaryBy(. ~ Cluster, hm.nms30.raw.scaled, keep.names = T)
hm.nms30.data$Cluster <- NULL
# Re-add the domain number to the first 30
names(hm.nms30.data)[10:39] <- sapply(NMS.30.NAMES, rid.of.middle)
# Reorder so not-analyzed variables are last
hm.nms30.data <- hm.nms30.data[, c(10:39, 1:9)]
hm.nms30.data.t <- as.data.frame(t(hm.nms30.data))
# Reorder
hm.nms30.data.t <- hm.nms30.data.t[rownames(hm.nms30.data.t)[c(1:30, 35:39, 34, 31:33)], ]
plot.new()
heatmap.2(as.matrix(hm.nms30.data.t), Rowv = FALSE, Colv = FALSE, dendrogram = 'none', trace = 'none',
# cellnote = as.matrix(hm.nms30.data.t),
col = colorRampPalette(rev(brewer.pal(11, 'RdBu')))(n = 250),
# RowSideColors = c(rep(gch[1], 2), rep(gch[2], 4), rep(gch[3], 6), rep(gch[4], 3), rep(gch[5], 3),
# rep(gch[6], 3), rep(gch[7], 3), rep(gch[8], 2), rep(gch[9], 4), rep(gch[10], 4)),
colRow = c(rep(color.nonmotor, 30), rep(color.motor, 5), rep(color.other, 4)),
xlab = 'Cluster', key.xlab = 'z-score',
cexCol = 1.5, cexRow = 1.2, srtCol = 0,
margins = c(5, 18),
# Draw lines to separate categories
rowsep = c(2, 6, 12, 15, 18, 21, 24, 26, 30, 35),
sepcolor = "white",
sepwidth = c(0.1, 0.1),
lmat = rbind(c(0,3),c(2,1),c(0,4)),
lwid = c(0.3,2),
lhei = c(0.6,4,1),
keysize = 0.5,
# key.xtickfun = function() { list(at = NULL) },
key.par = list(mar = c(7, 8, 3, 12)),
density.info = 'none'
)
# table(cl$cluster[nms30.present$Cluster == 4])
legend("top", # location of the legend on the heatmap plot
legend = c("Nonmotor (analyzed)", "Motor (analyzed)", "Other (not analyzed)"), # category labels
col = c(color.nonmotor, color.motor, color.other),
lty = 1,
lwd = 10,
bty = 'n',
cex = 0.9
)
if (TRUE) {
# Always write, for now
# NOTE: I crop this in preview afterwards because it still has some
# dead space
# dev.copy(pdf, "../figures/nms30-hm-pub.pdf", width = 7, height = 10)
dev.copy(pdf, "../figures/nms30-hm-pub-6.pdf", width = 7, height = 10)
dev.off()
}
# Redo clustering with nonmotor only ====
# cl.s$cluster, cl$cluster
# Recreate cl.s
# Use nms30 and nms30.s (scaled)
set.seed(0)
cl.s <- kmeans(x = nms30.s, 4, nstart = 25)
# Compute homogeneity/completeness/v-measure and alignment ====
redux.30 <- cl.s$cluster
redux.30 <- factor(redux.30, levels = c("4", "3", "2", "1"))
redux.30 <- revalue(redux.30, c("4" = "1", "3" = "2", "2" = "3", "1" = "4"))
redux.d <- cl$cluster
redux.d <- factor(redux.d, levels = c("1", "2", "3", "4"))
# redux.d <- factor(redux.d, levels = c("4", "1", "3", "2"))
# redux.d <- revalue(redux.d, c("2" = "1", "3" = "2", "4" = "3", "1" = "4"))
cat("Homogeneity/completeness/V-measure: ",
v.measure(redux.30, redux.d), "\n")
cat("Adjusted rand index: ",
mclust::adjustedRandIndex(redux.30, redux.d), "\n")
# Different stacked barplots for 6 cluster solution ====
re6.d <- redux.d
re6.30 <- nms30.present$Cluster
v.measure(re6.d, re6.30)
mclust::adjustedRandIndex(re6.d, re6.30)
align.6.pct <- data.frame(t(rbind(sapply(1:6, function(i) {
cat("Cluster ", i, "\n")
present.dist <- table(re6.d[re6.30 == i])
# Fill in empties
for (i in 1:4) {
if (is.na(present.dist[i])) {
present.dist[i] <- 0
}
}
round(sapply(present.dist, function(n) n / sum(present.dist)), 2)
}))),
compcluster = c("\n1", "\n2", "\n3", "\n4", "\n5", "\n6"),
comparison = rep("\nSymptoms cluster\n", 6)
)
names(align.6.pct) <- c("1", "2", "3", "4", "compcluster", "comparison")
align.6.pct.long <- melt(align.6.pct, id = c("compcluster", "comparison"))
align.6 <- data.frame(t(rbind(sapply(1:6, function(i) {
cat("Cluster ", i, "\n")
present.dist <- table(re6.d[re6.30 == i])
# Fill in empties
for (i in 1:4) {
if (is.na(present.dist[i])) {
present.dist[i] <- 0
}
}
present.dist
}))),
compcluster = c("\n1", "\n2", "\n3", "\n4", "\n5", "\n6"),
comparison = rep("\nSymptoms cluster\n", 6)
)
names(align.6) <- c("1", "2", "3", "4", "compcluster", "comparison")
align.6.long <- melt(align.6, id = c("compcluster", "comparison"))
align.6.2 <- align.6
# Choose pct or normal
comb.6 <- rbind(align.6.long)
# Calculate midpoints of bars
# Bind and plot as one
# comb.6$pos <- as.numeric(sapply(c(1:6, 19:24), function(i) {
# heights <- comb.6[seq(i, i + 18, by = 6), "value"]
# cum.heights <- cumsum(heights)
# cum.heights - ((heights) / 2)
# }))[as.integer(sapply(c(1:6, 19:24), function(i) seq(i, i + 18, length.out = 6)))]
comb.6$fac <- c(rep(c("\n\n\n\n\n\n\n\n1", "\n\n\n\n\n\n\n\n2", "\n\n\n\n\n\n\n\n3", "\n\n\n\n\n\n\n\n4",
"\n\n\n\n\n\n\n\n5", "\n\n\n\n\n\n\n\n6"), 4))
pbar <- ggplot(comb.6, aes(y = value, fill = variable)) +
geom_bar(aes(x = compcluster), position = "stack", stat = "identity") +
xlab("Symptoms cluster") + ylab("Count") +
labs(fill = "Domains\ncluster") +
# scale_y_continuous(labels = percent_format()) +
theme_bw() +
theme_pub() +
theme(strip.background = element_blank(),
strip.text.x = element_text(size=20, lineheight = 0.5),
plot.title = element_text(size=20, lineheight = 0.5),
axis.text.y = element_text(size=18),
axis.text.x = element_text(size=18, lineheight = 0.1),
legend.text = element_text(size = 18),
legend.title = element_text(size = 17)) +
scale_fill_manual(values = brewer.pal(8, "Set2")[1:4])
pbar.pct <- ggplot(comb.6, aes(y = value, fill = variable)) +
geom_bar(aes(x = compcluster), position = "fill", stat = "identity") +
xlab("Symptoms cluster") + ylab("") +
labs(fill = "Domains\ncluster") +
scale_y_continuous(labels = percent_format()) +
theme_bw() +
theme_pub() +
theme(strip.background = element_blank(),
strip.text.x = element_text(size=20, lineheight = 0.5),
plot.title = element_text(size=20, lineheight = 0.5),
axis.text.y = element_text(size=18),
axis.text.x = element_text(size=18),
legend.text = element_text(size = 18),
legend.title = element_text(size = 17)) +
scale_fill_manual(values = brewer.pal(8, "Set2")[1:4])
pbar.pct
# Do the same thing but for the other, I'm not going to rename stuff
align.6.pct <- data.frame(t(rbind(sapply(1:4, function(i) {
cat("Cluster ", i, "\n")
present.dist <- table(re6.30[re6.d == i])
# Fill in empties
for (i in 1:6) {
if (is.na(present.dist[i])) {
present.dist[i] <- 0
}
}
round(sapply(present.dist, function(n) n / sum(present.dist)), 2)
}))),
compcluster = c("\n1", "\n2", "\n3", "\n4"),
comparison = rep("\nSymptoms cluster\n", 4)
)
names(align.6.pct) <- c("1", "2", "3", "4", "5", "6", "compcluster", "comparison")
align.6.pct.long <- melt(align.6.pct, id = c("compcluster", "comparison"))
align.6 <- data.frame(t(rbind(sapply(1:4, function(i) {
cat("Cluster ", i, "\n")
present.dist <- table(re6.30[re6.d == i])
# Fill in empties
for (i in 1:6) {
if (is.na(present.dist[i])) {
present.dist[i] <- 0
}
}
present.dist
}))),
compcluster = c("\n1", "\n2", "\n3", "\n4"),
comparison = rep("\nSymptoms cluster\n", 4)
)
names(align.6) <- c("1", "2", "3", "4", "5", "6", "compcluster", "comparison")
align.6.long <- melt(align.6, id = c("compcluster", "comparison"))
align.6
# Choose pct or normal
comb.6 <- rbind(align.6.long)
# Calculate midpoints of bars
# Bind and plot as one
# comb.6$pos <- as.numeric(sapply(c(1:6, 19:24), function(i) {
# heights <- comb.6[seq(i, i + 18, by = 6), "value"]
# cum.heights <- cumsum(heights)
# cum.heights - ((heights) / 2)
# }))[as.integer(sapply(c(1:6, 19:24), function(i) seq(i, i + 18, length.out = 6)))]
comb.6$fac <- c(rep(c("\n\n\n\n\n\n\n\n1", "\n\n\n\n\n\n\n\n2", "\n\n\n\n\n\n\n\n3", "\n\n\n\n\n\n\n\n4"), 6))
pbar.2 <- ggplot(comb.6, aes(y = value, fill = variable)) +
geom_bar(aes(x = compcluster), position = "stack", stat = "identity") +
xlab("Domains cluster") + ylab("Count") +
labs(fill = "Symptoms\ncluster") +
# scale_y_continuous(labels = percent_format()) +
theme_bw() +
theme_pub() +
theme(strip.background = element_blank(),
strip.text.x = element_text(size=20, lineheight = 0.5),
plot.title = element_text(size=20, lineheight = 0.5),
axis.text.y = element_text(size=18),
axis.text.x = element_text(size=18, lineheight = 0.1),
legend.text = element_text(size = 18),
legend.title = element_text(size = 17)) +
scale_fill_manual(values = brewer.pal(8, "Set2")[1:6])
pbar.pct.2 <- ggplot(comb.6, aes(y = value, fill = variable)) +
geom_bar(aes(x = compcluster), position = "fill", stat = "identity") +
xlab("Domains cluster") + ylab("") +
labs(fill = "Symptoms\ncluster") +
scale_y_continuous(labels = percent_format()) +
theme_bw() +
theme_pub() +
theme(strip.background = element_blank(),
strip.text.x = element_text(size=20, lineheight = 0.5),
plot.title = element_text(size=20, lineheight = 0.5),
axis.text.y = element_text(size=18),
axis.text.x = element_text(size=18),
legend.text = element_text(size = 18),
legend.title = element_text(size = 17)) +
scale_fill_manual(values = brewer.pal(8, "Set2")[1:6])
pbar.pct.2
align.6[1:4, 1:6]
# if (TRUE) {
# dev.copy(pdf, "../figures/cluster-alignment.pdf", width = 10, height = 5)
# dev.off()
# }
# Stacked barplots bar plots bar chart barchart cluster alignment ====
# Distribution of nmsd cluster assignments for those who are in nms30
nmsd.per.nms30 <- data.frame(t(rbind(sapply(1:4, function(i) {
cat("Cluster ", i, "\n")
present.dist <- table(redux.d[redux.30 == i])
# Fill in empties
for (i in 1:4) {
if (is.na(present.dist[i])) {
present.dist[i] <- 0
}
}
round(sapply(present.dist, function(n) n / sum(present.dist)), 2)
}))),
compcluster = c("\n1", "\n2", "\n3", "\n4"),
comparison = rep("\nSymptoms cluster\n", 4)
)
names(nmsd.per.nms30) <- c("1", "2", "3", "4", "compcluster", "comparison")
ndpn30 <- melt(nmsd.per.nms30, id = c("compcluster", "comparison"))
# Distribution of nms30 cluster assignments for those who are in nmsd
nms30.per.nmsd <- data.frame(t(rbind(sapply(1:4, function(i) {
cat("Cluster ", i, "\n")
present.dist <- table(redux.30[redux.d == i])
for (i in 1:4) {
if (is.na(present.dist[i])) {
present.dist[i] <- 0
}
}
round(sapply(present.dist, function(n) n / sum(present.dist)), 2)
}))),
compcluster = c("\n1", "\n2", "\n3", "\n4"),
comparison = rep("\nDomains cluster\n", 4)
)
names(nms30.per.nmsd) <- c("1", "2", "3", "4", "compcluster", "comparison")
n30pnd <- melt(nms30.per.nmsd, id = c("compcluster", "comparison"))
comb <- rbind.fill(n30pnd, ndpn30)
# Calculate midpoints of bars
# Bind and plot as one
comb$pos <- as.numeric(sapply(c(1:4, 17:20), function(i) {
heights <- comb[seq(i, i + 12, by = 4), "value"]
cum.heights <- cumsum(heights)
cum.heights - ((heights) / 2)
}))[as.integer(sapply(c(1:4, 17:20), function(i) seq(i, i + 12, length.out = 4)))]
comb$fac <- c(rep(c("\n\n\n\n\n\n\n\nD[1]", "\n\n\n\n\n\n\n\nD[2]", "\n\n\n\n\n\n\n\nD[3]", "\n\n\n\n\n\n\n\nD[4]"), 4),
rep(c("\n\n\n\n\n\n\n\nS[1]", "\n\n\n\n\n\n\n\nS[2]", "\n\n\n\n\n\n\n\nS[3]", "\n\n\n\n\n\n\n\nS[4]"), 4))
pbar <- ggplot(comb, aes(y = value, fill = variable)) +
geom_bar(data = subset(comb, comparison == "\nDomains cluster\n"), aes(x = compcluster), position = "fill", stat = "identity") +
geom_bar(data = subset(comb, comparison == "\nSymptoms cluster\n"), aes(x = as.character(compcluster)), position = "fill", stat = "identity") +
facet_grid(. ~ comparison, switch = "x", scales = "free_x") +
# geom_text(aes(label = ifelse(value != 0, paste((value * 100), "%", sep = ""), ""), y = pos),
# color = "black", size = 4) +
xlab("") + ylab("") +
geom_text(aes(x = compcluster, y = 0, label = fac), color = rep(brewer.pal(4, "Set2"), 8),
inherit.aes = FALSE, parse = TRUE, size = 7, vjust = 2) +
labs(fill = "Opposite\nclustering") +
scale_y_continuous(labels = percent_format()) +
scale_x_discrete(labels = c(" ", " ", " ", " ")) +
theme_bw() +
theme_pub() +
theme(strip.background = element_blank(),
strip.text.x = element_text(size=20, lineheight = 0.5),
plot.title = element_text(size=20, lineheight = 0.5),
axis.text.y = element_text(size=18),
axis.text.x = element_text(colour = brewer.pal(4, "Set2"), size = 18, lineheight = 0.5),
legend.text = element_text(size = 18),
legend.title = element_text(size = 17)) +
scale_fill_manual(values = brewer.pal(8, "Set2")[1:4]) +
ggtitle(" Symptoms cluster distribution Domains cluster distribution \n")
gtbar <- ggplot_gtable(ggplot_build(pbar))
gtbar$layout$clip[gtbar$layout$name == "panel"] <- "off"
grid.draw(gtbar)
if (TRUE) {
dev.copy(pdf, "../figures/cluster-alignment.pdf", width = 10, height = 5)
dev.off()
}
# Correlation plots without bins ====
everything.wide$cluster <- factor(everything.wide$cluster)
ALPH <- 1/5
SPAN <- 2
XPOS <- 36
# ggplot(everything.wide, aes(x=durat_pd))
facts.of.int <- c("\nAnxiety\n" = "nms9", "\nDepression\n" = "nms10",
"\nCISI_PD_total\n" = "cisitot", "\nTremor\n" = "tremor")
el <- melt(everything.wide, id.var = c("cluster", "durat_pd"))
# Filter only less than 30s, for lack of
# el <- el[el$durat_pd < 30.1, ]
el.sub <- el[el$variable %in% facts.of.int, ]
# No better way to switch the names?
el.sub$variable <- revalue(factor(el.sub$variable), setNames(names(facts.of.int), facts.of.int))
mean_vals <- data.frame(
variable = names(facts.of.int),
value = sapply(names(facts.of.int), function(f) {
mean(el.sub[el.sub$variable == f, ]$value)
})
)
mean_cors <- sapply(names(facts.of.int), function(f) {
el.of.int <- el.sub[el.sub$variable == f, ]
cor(el.of.int$durat_pd, el.of.int$value)
})
mean_text <- data.frame(
label = sapply(1:4, function(i) {
v <- round(mean_vals$value[i], 2)
r <- round(mean_cors[i], 2)
paste("µ = ", v, "\nr = ", r, sep = "")
}),
variable = mean_vals$variable,
x = XPOS,
y = sapply(facts.of.int, function(i) max(el[el$variable == i, ]$value - max(el[el$variable == i, ]$value) / 13))
# y = sapply(facts.of.int, function(i) mean(el[el$variable == i, ]$value + max(el[el$variable == i, ]$value/13)))
)
ggplot(el.sub, aes(x=durat_pd, y=value, color = cluster)) +
geom_point(alpha = ALPH) +
stat_smooth(aes(color = "Overall"), se = FALSE, color = "black", span = SPAN) +
stat_smooth(se = FALSE, span = SPAN) +
geom_jitter(width = 0.7, height = 0.7, alpha = ALPH) +
geom_hline(aes(yintercept = value), mean_vals, linetype='dashed') +
geom_label(data = mean_text, aes(x, y, label = label), inherit.aes = FALSE, size = 6, color = "black", alpha = 0.5) +
facet_wrap(~ variable, nrow = 2, ncol = 2, scales = "free_y") +
theme_bw() +
ylab("Symptom Score\n") +
xlab("\nPD Duration (years)") +
scale_color_manual(values = brewer.pal(8, "Set2")[1:4]) +
labs(color = "Cluster") +
theme_pub() +
theme(strip.text = element_text(lineheight = 0.5))
ggsave("../figures/long4-d.pdf")
# Do the same thing, but on nms30 ====
everything.wide.30 <- everything.wide
everything.wide.30$cluster <- nms30.present$Cluster
el.30 <- melt(everything.wide.30, id.var = c("cluster", "durat_pd"))
# Filter only less than 30s, for lack of
# el.30 <- el.30[el.30$durat_pd < 30.1, ]
el.30.sub <- el.30[el.30$variable %in% facts.of.int, ]
# No better way to switch the names?
el.30.sub$variable <- revalue(factor(el.30.sub$variable), setNames(names(facts.of.int), facts.of.int))
mean_vals.30 <- data.frame(
variable = names(facts.of.int),
value = sapply(names(facts.of.int), function(f) {
mean(el.30.sub[el.30.sub$variable == f, ]$value)
})
)
mean_cors.30 <- sapply(names(facts.of.int), function(f) {
el.of.int <- el.30.sub[el.30.sub$variable == f, ]
cor(el.of.int$durat_pd, el.of.int$value)
})
mean_text.30 <- data.frame(
label = sapply(1:4, function(i) {
v <- round(mean_vals.30$value[i], 2)
r <- round(mean_cors.30[i], 2)
paste("µ = ", v, "\nr = ", r, sep = "")
}),
variable = mean_vals.30$variable,
x = XPOS,
y = sapply(facts.of.int, function(i) max(el.30[el.30$variable == i, ]$value - max(el.30[el.30$variable == i, ]$value) / 13))
)
ggplot(el.30.sub, aes(x=durat_pd, y=value, color = cluster)) +
geom_point(alpha = ALPH) +
stat_smooth(aes(color = "Overall"), se = FALSE, color = "black", span = SPAN) +
stat_smooth(se = FALSE, span = SPAN) +
geom_jitter(width = 0.7, height = 0.7, alpha = ALPH) +
geom_hline(aes(yintercept = value), mean_vals.30, linetype='dashed') +
geom_label(data = mean_text.30, aes(x, y, label = label), inherit.aes = FALSE,
size = 6, color = "black", alpha = 0.5) +
facet_wrap(~ variable, nrow = 2, ncol = 2, scales = "free_y") +
theme_bw() +
ylab("Symptom Score\n") +
xlab("\nPD Duration (years)") +
labs(color = "Cluster") +
theme_pub() +
theme(strip.text = element_text(lineheight = 0.5)) +
ggsave("../figures/long4-30.pdf")
# Final correlation, unbinned ====
durat.cor.everything <- function(symptom) cor(everything.wide$durat_pd, as.numeric(everything.wide[[symptom]]))
durat.cor.test <- function(symptom) cor.test(everything.wide$durat_pd, everything.wide[[symptom]])
correlations.everything <- sapply(names(everything.wide),
durat.cor.everything)
# Get rid of cluster, sex, durat_pd
to.remove <- c("cluster", "sex", "durat_pd", "pdonset", "age")
correlations.everything <- correlations.everything[!names(correlations.everything) %in% to.remove]
names(correlations.everything) <- sapply(names(correlations.everything), function(v) c(NMS.D.MAP.PUB.N, NMS.NUM.TO.PUB, MISC.MAP)[[v]])
correlations.everything <- sort(correlations.everything) # Sort ascending
# Pretty meaningless - no negative correlations!!
is_d.e <- grepl("d", names(correlations.everything))
is_d.e[which(is_d.e == TRUE)] <- "Domain"
is_d.e[which(is_d.e == FALSE)] <- "Symptom"
is_d.e[which(names(correlations.everything) %in% c("Axial", "Bradykinesia", "Rigidity", "Tremor"))] <- "Motor"
is_d.e[which(names(correlations.everything) %in% c("CISI_PD_total", "Age", "PD_onset"))] <- "Other"
correlations.df.e <- data.frame(
names=names(correlations.everything),
r=correlations.everything,
variable=is_d.e
)
correlations.df.e$names <- factor(correlations.df.e$names,
levels=names(sort(correlations.everything)))
# correlations.test.e <- lapply(c(ALL.SYMPTOMS, NMS.30), durat.cor.test)
# names(correlations.test.e) <- c(ALL.SYMPTOMS, NMS.30)
ggplot(correlations.df.e, aes(x=names, y=r, fill=variable)) +
geom_bar(stat="identity", position="identity") +
# geom_text(aes(label=round(r, 2)), position=position_dodge(width=0.9), vjust=2 * (correlations.df.e$r < 0) - .5) +
scale_y_continuous(limits = c(0, 1)) +
ylab("r\n") +
xlab("") +
guides(guides(fill=guide_legend(title="Variable type"))) +
theme_pub() +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
# Only save with different names!
if (TRUE) {
ggsave('../figures/cor-unbinned.pdf', width=15, height=8)
}
# RAY final statistics: durat_pd ====
# less
over.1 = table(clus4[clus4$cluster == 1, 'durat_pd'] < 5)
over.2 = table(clus4[clus4$cluster == 2, 'durat_pd'] < 5)
over.3 = table(clus4[clus4$cluster == 3, 'durat_pd'] < 5)
over.4 = table(clus4[clus4$cluster == 4, 'durat_pd'] < 5)
overs = rbind(over.1, over.2, over.3, over.4)
chisq.test(overs)
over.1[2] / (over.1[1] + over.1[2])
over.2[2] / (over.2[1] + over.2[2])
over.3[2] / (over.3[1] + over.3[2])
over.4[2] / (over.4[1] + over.4[2])
pairwise.prop.test(overs, p.adjust.method = "bonferroni")
# TOTAL
over.total = table(ray.clus4[, 'durat_pd'] < 5)
# Compare to total
over.total.comp = rbind(over.1, over.total)
prop.test(over.total.comp)
# everyone else
over.ee = table(ray.clus4[ray.clus4$cluster != 1, 'durat_pd'] < 5)
# Compare to ee
over.ee.comp = rbind(over.1, over.ee)
prop.test(over.ee.comp)
# RAY: HY ====
# Bind HY
assertthat::are_equal(clus4$age, raw.omitted.full$age)
ray.clus4 = cbind(clus4, hy = raw.omitted.full$hy)
# FULL HY
hy.1 = table(ray.clus4[ray.clus4$cluster == 1, 'hy'])
hy.1[["5"]] = 0
hy.2 = table(ray.clus4[ray.clus4$cluster == 2, 'hy'])
hy.3 = table(ray.clus4[ray.clus4$cluster == 3, 'hy'])
hy.4 = table(ray.clus4[ray.clus4$cluster == 4, 'hy'])
hy.4 = c(0, hy.4)
hy.4 = setNames(hy.4, c("1", "2", "3", "4", "5"))
hys = rbind(hy.1, hy.2, hy.3, hy.4)
# chisq.test(hys) doesn't work, too few data
hy.1[2] / (hy.1[1] + hy.1[2])
hy.2[2] / (hy.2[1] + hy.2[2])
hy.3[2] / (hy.3[1] + hy.3[2])
hy.4[2] / (hy.4[1] + hy.4[2])
t(hys)
table(ray.clus4[, 'hy'])
# HY <= 2
hyp.1 = table(ray.clus4[ray.clus4$cluster == 1, 'hy'] <= 2)
hyp.2 = table(ray.clus4[ray.clus4$cluster == 2, 'hy'] <= 2)
hyp.3 = table(ray.clus4[ray.clus4$cluster == 3, 'hy'] <= 2)
hyp.4 = table(ray.clus4[ray.clus4$cluster == 4, 'hy'] <= 2)
hyps = rbind(hyp.1, hyp.2, hyp.3, hyp.4)
chisq.test(hyps)
hyp.1[2] / (hyp.1[1] + hyp.1[2])
hyp.2[2] / (hyp.2[1] + hyp.2[2])
hyp.3[2] / (hyp.3[1] + hyp.3[2])
hyp.4[2] / (hyp.4[1] + hyp.4[2])
t(hyps)
pairwise.prop.test(hyps, p.adjust.method = "bonferroni")
# TOTAL
hyp.total = table(ray.clus4[, 'hy'] <= 2)
# Compare to total
hyp.total.comp = rbind(hyp.1, hyp.total)
prop.test(hyp.total.comp)
# everyone else
hyp.ee = table(ray.clus4[ray.clus4$cluster != 1, 'hy'] <= 2)
# Compare to ee
hyp.ee.comp = rbind(hyp.1, hyp.ee)
prop.test(hyp.ee.comp)
|
ea454cb3d065d4624402a0760cc89a96621199f4 | 5397b2f52030662f0e55f23f82e45faa165b8346 | /R/j_db-functions.R | b8286602f7ceb1983c243eb79ae3efb2f8af0b0d | [
"MIT"
] | permissive | data-science-made-easy/james-old | 8569dcc8ce74c68bcbb81106127da4b903103fcd | 201cc8e527123a62a00d27cd45d365c463fc1411 | refs/heads/master | 2023-01-12T21:16:23.231628 | 2020-11-19T13:46:17 | 2020-11-19T13:46:17 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,014 | r | j_db-functions.R | j_db_put <- function(meta) { # meta$d0 is data
if (is_yes(meta$j_debug)) print(paste("IN j_db_put"))
db_writable <- !is.null(meta$j_db_path) && 0 == file.access(meta$j_db_path, mode = 2)
if (is_yes(meta$j_debug)) print(paste("db_writable:", db_writable))
if (is_yes(meta$j_debug)) print(paste("j_db_path:", meta$j_db_path))
if (!is_yes(meta$j_db) || !is.character(meta$j_db_table) || !is.character(meta$j_db_path) || !db_writable) return()
con <- DBI::dbConnect(RSQLite::SQLite(), dbname = meta$j_db_path) # :dbname:
if (is_yes(meta$j_debug)) print(paste("dbConnect"))
# Remove data
this_data <- meta$d0
meta$d0 <- NULL
# Add extra meta data statistics
meta$j_db_put_timestamp <- unclass(Sys.time())
meta$j_db_put_path <- getwd()
meta_df <- list_as_df(meta)
meta_df_fields <- colnames(meta_df)
if (!DBI::dbExistsTable(con, meta$j_db_table)) {
DBI::dbWriteTable(con, meta$j_db_table, meta_df)
} else {
if (all(is.element(meta_df_fields, DBI::dbListFields(con, meta$j_db_table)))) {
# We can just simply append
DBI::dbWriteTable(con, meta$j_db_table, meta_df, append = TRUE)
} else {
db_table <- DBI::dbReadTable(con, meta$j_db_table)
db_table_filled <- plyr::rbind.fill(meta_df, db_table)
DBI::dbWriteTable(con, meta$j_db_table, db_table_filled, overwrite = TRUE)
}
}
DBI::dbDisconnect(con)
if (is_yes(meta$j_debug)) print(paste("dbDisconnect"))
}
list_as_df <- function(lst) {
lst_as_df <- as.data.frame(t(unlist(lapply(lst,toString))))
rownames(lst_as_df) <- NULL
lst_as_df
}
j_db_get_stats <- function(j_db_path = c('/Volumes/p_jamesgebruiker/stats/j_db.sqlite', 'M:/p_jamesgebruiker/stats/j_db.sqlite'), j_db_table = "jls") {
for (p in j_db_path) {
if (file.exists(p)) {
j_db_path <- p
break
}
}
con <- DBI::dbConnect(RSQLite::SQLite(), dbname = j_db_path) # :dbname:
db_table <- DBI::dbReadTable(con, j_db_table)
DBI::dbDisconnect(con)
mat <- as.data.frame(unique(cbind(user = db_table$user, timestamp = NA, path = db_table$j_db_put_path)), stringsAsFactors = F)
if (length(nrow(mat))) {
for (i in 1:nrow(mat)) {
index <- which(db_table$user == mat$user[i] & db_table$j_db_put_path == mat$path[i])
mat$timestamp[i] <- as.numeric(max(db_table$j_db_put_timestamp[index]))
}
index <- sort(mat$timestamp, decreasing = T, index.return = TRUE)$ix
mat <- mat[index, ]
mat$timestamp <- as.POSIXct(as.numeric(mat$timestamp), origin = "1970-01-01")
# Enrich user names with full names
un_path <- file.path(stringr:::str_sub(j_db_path, end=-12), "usernames.RData")
if (file.exists(un_path)) {
un <- dget(un_path)
un_vec <- NULL
for (i in 1:nrow(mat)) {
un_vec[i] <- un[which(un[, "username"] == mat$user[i]), 2]
}
mat <- cbind(mat[, 1], un_vec, mat[, 2:ncol(mat)])
colnames(mat)[1:2] <- c("user", "name")
}
}
return(mat)
}
|
155336e654df28f464a194c534936ede196c5375 | d15cc13117e1e179a92874f0623e80682871f9bf | /Week2/Day4/selfAssessment2.r | b35e37035679438653958138d1231057de7164c3 | [] | no_license | mdb2/SignalLearningWork | 415754388f32b829849e10718aa838529d0feb56 | 608e7fa3e886278b5edccc584aa16b7ab2a5c7f7 | refs/heads/master | 2020-12-24T19:13:29.705562 | 2016-05-28T00:49:29 | 2016-05-28T00:49:29 | 57,985,647 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,376 | r | selfAssessment2.r | #Started at 10:02, took lunch break at 12:00 resumed at 12:45 end at 1:18, 3 hours spent
library(psych)
set.seed(1)
#generates alphas and lambdas:
alphaIterOver = seq(0,1,length.out = 11)
lambdaIterOver = 10^seq(1,-2,length.out = 50)
df = msq
noNADF = df
#remove NAs replace with column mean:
for(i in 1:ncol(noNADF)){
noNADF[[i]][is.na(noNADF[[i]])] = mean(noNADF[[i]], na.rm = TRUE)
}
#get features, extraversion, and neuroticism:
features = noNADF[match("active",names(noNADF)):match("scornful",names(noNADF))]
extraFeature = noNADF[match("Extraversion",names(noNADF))]
neuroFeature = noNADF[match("Neuroticism",names(noNADF))]
#rmse helper function:
rmse = function(x, y){
return(sqrt(mean((x-y)^2)))
}
#generate folds:
numFolds = 10
sampleVec = sample(1:nrow(features))
shuffledDF = features[sampleVec,]
shuffledExtra = extraFeature[sampleVec,]
shuffledNeuro = neuroFeature[sampleVec,]
trainFeatList = vector("list", numFolds)
trainExtraList = vector("list", numFolds)
trainNeuroList = vector("list", numFolds)
testFeatList = vector("list", numFolds)
for(i in 1:numFolds){
trainRowLogiVec = ((i-1):(numFolds+i-2))%%(numFolds)<=numFolds-2
trainFeatList[[i]] = shuffledDF[trainRowLogiVec,]
trainExtraList[[i]] = shuffledExtra[trainRowLogiVec]
trainNeuroList[[i]] = shuffledNeuro[trainRowLogiVec]
testFeatList[[i]] = shuffledDF[!trainRowLogiVec,]
}
#create data frame to store the results of computations:
storeComp = data.frame()
storeCompNames = c("Alpha", "Lambda", "CVRMSE-Extra", "CVRMSE-Neuro")
# alphaIterOver = seq(0,1,length.out = 11)
# lambdaIterOver = 10^seq(1,-2,length.out = 50)
library(glmnet)
rmseExtraTot = vector("list", length(alphaIterOver)*length(lambdaIterOver))
rmseNeuroTot = vector("list", length(alphaIterOver)*length(lambdaIterOver))
for(i in 1:length(alphaIterOver)){
print(alphaIterOver[i])
fitListExtra = vector("list", numFolds)
fitListNeuro = vector("list", numFolds)
trainScales = vector("list", numFolds)
for(j in 1:numFolds){
trainScale = scale(trainFeatList[[j]])
trainScales[[j]] = scale(trainFeatList[[j]])
fitListExtra[[j]] = glmnet(trainScale,trainExtraList[[j]],alpha = alphaIterOver[[i]],lambda=lambdaIterOver)
fitListNeuro[[j]] = glmnet(trainScale,trainNeuroList[[j]],alpha = alphaIterOver[[i]],lambda=lambdaIterOver)
}
rmseListExtra = vector("list", length(lambdaIterOver))
rmseListNeuro = vector("list", length(lambdaIterOver))
for(i2 in 1:length(lambdaIterOver)){
print(lambdaIterOver[i2])
predictListExtra = vector("list", numFolds)
predictListNeuro = vector("list", numFolds)
for(j in 1:numFolds){
scalingCenter = attr(trainScales[[j]], "scaled:center")
scalingScale = attr(trainScales[[j]], "scaled:scale")
predictListExtra[[j]] = predict(fitListExtra[[j]], scale(testFeatList[[j]],scalingCenter,scalingScale), lambdaIterOver[[i]])
predictListNeuro[[j]] = predict(fitListNeuro[[j]], scale(testFeatList[[j]],scalingCenter,scalingScale), lambdaIterOver[[i]])
}
rmseExtra[[i2]] = rmse(unlist(predictListExtra), shuffledExtra)
rmseNeuro[[i2]] = rmse(unlist(predictListNeuro), shuffledNeuro)
}
rmseExtraTot[[i]] = rmseExtra
rmseNeuroTot[[i]] = rmseNeuro
}
storeComp = rbind(rep(alphaIterOver,length(lambdaIterOver)), rep(lambdaIterOver,length(alphaIterOver)), rmseExtra, rmseNeuro)
names(storeComp) = storeCompNames
|
491a803d8eb045caa90e1fc9f6efb4e4557924f0 | cd1e96d1deae4efff9c7c3c73302e6e411ba0fd4 | /nyt_scrapeg.R | a40662a16d8cf5e0b7e0f62548c1ce474d48afef | [] | no_license | jtk5469/Karstens_497 | 2fd9983c4f5baf07bf2e385c586c9242d1b96f23 | 6e8ec5da6520a0fcd32ad06bc8173c01dc1ec747 | refs/heads/main | 2023-04-14T07:54:47.038808 | 2021-04-28T04:28:02 | 2021-04-28T04:28:02 | 346,462,950 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,280 | r | nyt_scrapeg.R |
library(jsonlite)
library(dplyr)
library(tidyr)
library(ggplot2)
library(stringr)
##code adapted from Heather Geiger
setwd("C:/Users/Jack Karstens/Documents/PLSC 497")
NYTIMES_KEY <- ("PRBP9pLaQoJsErAvkJh6fSNaH2eCy9vA")
term <- "facebook"
begin_date <- "20200101"
end_date <- "20200401"
baseurl <- paste0("http://api.nytimes.com/svc/search/v2/articlesearch.json?q=",term,
"&begin_date=",begin_date,"&end_date=",end_date,
"&facet_filter=true&api-key=",NYTIMES_KEY, sep="")
initialQuery <- fromJSON(baseurl)
pages_2020 <- vector("list",length=5)
for(i in 0:4){
nytSearch <- fromJSON(paste0(baseurl, "&page=", i), flatten = TRUE) %>% data.frame()
pages_2020[[i+1]] <- nytSearch
Sys.sleep(10) #I was getting errors more often when I waited only 1 second between calls. 5 seconds seems to work better.
}
facebook_2020_articles <- rbind_pages(pages_2020)
summary(facebook_2020_articles)
term <- "facebook"
begin_date <- "20210101"
end_date <- "20210401"
baseurl <- paste0("http://api.nytimes.com/svc/search/v2/articlesearch.json?q=",term,
"&begin_date=",begin_date,"&end_date=",end_date,
"&facet_filter=true&api-key=",NYTIMES_KEY, sep="")
initialQuery <- fromJSON(baseurl)
pages_2021 <- vector("list",length=5)
for(i in 0:5){
nytSearch <- fromJSON(paste0(baseurl, "&page=", i), flatten = TRUE) %>% data.frame()
pages_2021[[i+1]] <- nytSearch
Sys.sleep(10)
}
facebook_2021_articles <- rbind_pages(pages_2021)
#####in-class practice:
### save the results of two different queries from the date range jan 1 2021 - APril 1 2021
save(facebook_2020_articles, file = "nyt1.Rdata")
save(facebook_2021_articles, file = "nyt2.Rdata")
### calculate the proportion of the headlines from each search term assigned to a given section name
mean(facebook_2020_articles)
## create a combined dfm with the text of all of the lead paragraphs
leaddfm <- data.frame(facebook_2021_articles, facebook_2020_articles)
## calculate the average Flesch Reading Ease score (hint: use code form descriptive_2.R) for the lead paragraphs from each search term. Which is higher?
readability(leaddfm, order.by.readability = TRUE)
|
c96b7ce413fb38ecaaa7ae80521aa4e85308f0a4 | 452042d9a5cb876a90a9cb1f4c802d0f4b1453c7 | /man/ff_transactions.Rd | 539310cba7c967dd91ae4ff8b2a1020399462722 | [
"MIT"
] | permissive | jpiburn/ffscrapr | dc420370f6940275aaa8cb040c5ec001a25268b8 | 4e7bda862500c47d1452c84a83adce7ee1987088 | refs/heads/main | 2023-06-02T00:09:09.670168 | 2021-06-12T15:52:23 | 2021-06-12T15:52:23 | 377,976,824 | 1 | 0 | NOASSERTION | 2021-06-17T22:42:26 | 2021-06-17T22:42:26 | null | UTF-8 | R | false | true | 2,656 | rd | ff_transactions.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/0_generics.R, R/espn_transactions.R,
% R/flea_transactions.R, R/mfl_transactions.R, R/sleeper_transactions.R
\name{ff_transactions}
\alias{ff_transactions}
\alias{ff_transactions.espn_conn}
\alias{ff_transactions.flea_conn}
\alias{ff_transactions.mfl_conn}
\alias{ff_transactions.sleeper_conn}
\title{Get League Transactions}
\usage{
ff_transactions(conn, ...)
\method{ff_transactions}{espn_conn}(conn, limit = 1000, ...)
\method{ff_transactions}{flea_conn}(conn, franchise_id = NULL, ...)
\method{ff_transactions}{mfl_conn}(conn, custom_players = deprecated(), ...)
\method{ff_transactions}{sleeper_conn}(conn, week = 1:17, ...)
}
\arguments{
\item{conn}{the list object created by \code{ff_connect()}}
\item{...}{additional args for other methods}
\item{limit}{number of most recent transactions to return}
\item{franchise_id}{fleaflicker returns transactions grouped by franchise id, pass a list here to filter}
\item{custom_players}{\ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#deprecated}{\figure{lifecycle-deprecated.svg}{options: alt='[Deprecated]'}}}{\strong{[Deprecated]}} - now returns custom players by default}
\item{week}{A week filter for transactions - 1 returns all offseason transactions. Default 1:17 returns all transactions.}
}
\value{
A tidy dataframe of transaction data
}
\description{
This function returns a tidy dataframe of transactions - generally one row per player per transaction per team.
Each trade is represented twice, once per each team.
}
\section{Methods (by class)}{
\itemize{
\item \code{espn_conn}: ESPN: returns adds, drops, and trades. Requires private/auth-cookie.
\item \code{flea_conn}: Fleaflicker: returns all transactions, including free agents, waivers, and trades.
\item \code{mfl_conn}: MFL: returns all transactions, including auction, free agents, IR, TS, waivers, and trades.
\item \code{sleeper_conn}: Sleeper: returns all transactions, including free agents, waivers, and trades.
}}
\examples{
\dontrun{
# Marked as don't run because this endpoint requires private authentication
conn <- espn_connect(
season = 2020,
league_id = 1178049,
swid = Sys.getenv("TAN_SWID"),
espn_s2 = Sys.getenv("TAN_ESPN_S2")
)
ff_transactions(conn)
}
\donttest{
conn <- fleaflicker_connect(season = 2020, league_id = 312861)
ff_transactions(conn)
}
\donttest{
dlf_conn <- mfl_connect(2019, league_id = 37920)
ff_transactions(dlf_conn)
}
\donttest{
jml_conn <- ff_connect(platform = "sleeper", league_id = "522458773317046272", season = 2020)
x <- ff_transactions(jml_conn, week = 1:17)
}
}
|
1bb3ab9791965f604ec20da1d5ada98c17bcab33 | b99c606e20930ed0c2ee15a166b6a4053c675c07 | /R/plot-network.R | 4afb6d049c91c12088e6bad8f43606959dfd0181 | [] | no_license | belgareth/scholarnetwork | c95c88a8fc1edd02ecf47231c31c90af41b0a55d | 9cd7fd16c96b8625657db138e9864ccda1e3b4fc | refs/heads/master | 2021-08-26T08:57:20.055506 | 2021-08-09T13:17:38 | 2021-08-09T13:17:38 | 255,119,315 | 0 | 1 | null | 2020-04-12T16:03:10 | 2020-04-12T16:03:09 | null | UTF-8 | R | false | false | 2,195 | r | plot-network.R | #' plotNetwork
#' @export
#'
#' @title
#' Plot collaborators network from Google Scholar page
#'
#' @description
#' Takes value from \code{extractNetwork} function and visualizes network
#' using networkD3.
#'
#' @param nodes Data frame with node information returned by \code{extractNetwork}.
#' @param edges Data frame with edge list returned by \code{extractNetwork}.
#' @param file File where network visualization will be exported to.
#' @param width numeric width for the network graph's frame area in pixels
#' @param height numeric height for the network graph's frame area in pixels.
#' @param opacity numeric value of the proportion opaque you would like the graph elements to be.
#' @param fontsize numeric font size in pixels for the node text labels.
#' @param charge numeric value indicating either the strength of the node repulsion (negative value) or attraction (positive value).
#' @param ... Other options to pass to \code{networkD3} function
#'
#' #' @examples \dontrun{
#' ## Download Google Scholar network data for a sample user
#' d <- extractNetwork(id="jGLKJUoAAAAJ", n=500)
#' ## Plot network into file called \code{network.html}
#' plotNetwork(d$nodes, d$edges, file="network.html")
#' }
#'
plotNetwork <- function(nodes, edges, file='network.html', width=550,
height=400, opacity = .75, fontsize=10,
charge=-400,...){
df <- data.frame(
Source=as.numeric(factor(edges$node1, levels=nodes$label))-1,
Target=as.numeric(factor(edges$node2, levels=nodes$label))-1,
value=edges$weight)
output <- networkD3::forceNetwork(Links = df, Nodes = nodes, Source="Source", Target="Target",
NodeID = "label", Group = "group",linkWidth = 1,
Nodesize = "degree", fontSize=fontsize,
opacity = opacity, charge=charge,
width = width, height = height, ...)
saveNetwork(output, file, selfcontained = FALSE)
}
#d3Network::d3ForceNetwork(
# Links = df, Nodes = nodes, Source="Source", Target="Target",
# NodeID = "label", Group="group", width = width, height = height,
# opacity = opacity, file=file, fontsize=fontsize,
# linkDistance=linkDistance, ...)
|
c8cad3e734b758feb0ceda3bb4707b4e73f4afd4 | f8a99bc9505ecb65f186f4dcb22f0fa9750ec85f | /scripts/bird_continental_tree.R | 25562d568f48fd4ee6144e2064ab07699f3e6c43 | [] | no_license | reptalex/dendromap | 015171627dc6031172db90414c6f5ec8b90e0722 | 3a0cd41f387fdc1ffbcefa7bbab054835173480c | refs/heads/master | 2021-06-12T00:14:57.326415 | 2021-04-15T20:21:22 | 2021-04-15T20:21:22 | 168,759,654 | 0 | 1 | null | 2021-04-15T20:21:23 | 2019-02-01T21:00:48 | R | UTF-8 | R | false | false | 405 | r | bird_continental_tree.R | library(phylofactor)
tr <- NULL
tr$tip.label <- c('Eurasia','NAmerica','Australia','Africa','SAmerica')
tr$edge <- c(6,7,
7,1,
7,2,
6,8,
8,3,
8,9,
9,4,
9,5) %>%
matrix(byrow=T,ncol=2)
tr$edge.length <- rep(1,nrow(tr$edge))
tr$Nnode <- 4
class(tr) <- 'phylo'
saveRDS(tr,'data/birds/continental_tree') |
4007dece0b5ce7806a9a3080651edc6cdd3bf11d | ccbe01aef6cc0dd964215d117435304c7be91c98 | /man/loanbook_demo.Rd | 1c0560da7b5e688a9c54689b642536819faa5c2e | [] | no_license | andybue/r2dii.dataraw | b54964f3f5262953c6136d5f890564276dc4a2a2 | 82034bc91226ea87bed21912871556a0e6b30916 | refs/heads/master | 2020-08-20T00:52:06.401944 | 2019-10-17T20:03:23 | 2019-10-17T20:03:23 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 679 | rd | loanbook_demo.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/loanbook_demo.R
\docType{data}
\name{loanbook_demo}
\alias{loanbook_demo}
\title{A loanbook dataset for demonstration}
\format{An object of class \code{spec_tbl_df} (inherits from \code{tbl_df}, \code{tbl}, \code{data.frame}) with 320 rows and 18 columns.}
\usage{
loanbook_demo
}
\description{
This is a public dataset that may be used as a template for banks to create
their own loanbook datasets. It is also useful for examples and tests.
}
\examples{
loanbook_demo
}
\seealso{
\link{data_dictionary}
Other demo datasets: \code{\link{data_dictionary}}
}
\concept{demo datasets}
\keyword{datasets}
|
1aa33945ecad2eb1f63e76261fc9acf7245aba49 | 2e3288f1e217cc8122ded5520fe30af869bfebec | /man/drawnetwork.Rd | e4a1ba806fb92dc2ca4866972c254f074867f53f | [] | no_license | ClausDethlefsen/deal | 267bbaa32c27fc7cff43a654430ddb9d4cbe83d4 | 81b063fae2444ae3630d6d80389a96fff92a27ab | refs/heads/master | 2022-12-03T06:25:09.296100 | 2022-11-09T19:08:40 | 2022-11-09T19:08:40 | 153,797,426 | 1 | 1 | null | 2018-12-05T08:40:50 | 2018-10-19T14:40:14 | R | UTF-8 | R | false | false | 3,606 | rd | drawnetwork.Rd | % -*- Mode: Rd -*-
% drawnetwork.Rd ---
% Author : Claus Dethlefsen
% Created On : Sat May 25 23:01:44 2002
% Last Modified By: Claus Dethlefsen
% Last Modified On: Thu Dec 04 13:15:16 2008
% Update Count : 50
% Status : Unknown, Use with caution!
%
\name{drawnetwork}
\alias{drawnetwork}
%- Also NEED an `\alias' for EACH other topic documented here.
\title{Graphical interface for editing networks}
\description{\code{drawnetwork} allows the user to specify a Bayesian network through a point and click interface.
}
\encoding{latin1}
\usage{
drawnetwork(nw,df,prior,trylist=vector("list",size(nw)),
unitscale=20,cexscale=8,
arrowlength=.25,nocalc=FALSE,
yr=c(0,350),xr=yr,...)
}
%- maybe also `usage' for other objects documented here.
\arguments{
\item{nw}{an object of class \code{\link{network}} to be edited.}
\item{df}{a data frame used for learning the network, see
\code{\link{network}}.}
\item{prior}{a list containing parameter priors, generated by
\code{\link{jointprior}}.}
\item{trylist}{a list used internally for reusing learning of nodes,
see \code{\link{maketrylist}}.}
\item{cexscale}{a numeric passed to the plot method for network
objects. Measures the scaled size of text and symbols.}
\item{arrowlength}{a numeric passed to
the plot method for network
objects. Measures the length of the edges of the arrowheads.}
\item{nocalc}{a logical. If \code{TRUE}, no learning procedure is called, see eg. \code{\link{rnetwork}}.}
\item{unitscale}{a numeric passed to
the plot method for network
objects. Scale parameter for chopping off arrow heads.}
\item{xr}{a numeric vector with two components containing the range on x-axis.}
\item{yr}{a numeric vector with two components containing the range on y-axis.}
\item{...}{additional plot arguments, passed to the plot method for network
objects.}
}
\details{
To insert an arrow from node 'A' to node 'B', first click node 'A' and
then click node 'B'. When the graph is finished, click 'stop'.
To specify that an arrow must not be present, press 'ban' (a toggle)
and draw the arrow. This is shown as a red dashed arrow. It is possible
to ban both directions between nodes. The ban list is stored with the
network in the property \code{banlist}. It is a matrix with two
columns. Each row is the 'from' node index and the 'to' node index,
where the indices are the column number in the data frame.
Note that the network score changes as the network is re-learned
whenever a change is made (unless \code{nocalc} is \code{TRUE}).
}
\value{A list with two elements that may be accessed using
\code{\link{getnetwork}} and \code{\link{gettrylist}}. The elements are
\item{nw}{an object of class \code{\link{network}} with the final network.}
\item{trylist}{an updated list used internally for reusing learning
of nodes, see \code{\link{maketrylist}}.}
}
\seealso{\code{\link{network}}
}
% \references{
% Further information about \bold{deal} can be found at:\cr
% \url{http://www.math.aau.dk/~dethlef/novo/deal}.
% }
\author{
Susanne Gammelgaard Bottcher, \cr
Claus Dethlefsen \email{rpackage.deal@gmail.com}.
}
\examples{
data(rats)
rats.nw <- network(rats)
rats.prior <- jointprior(rats.nw,12)
rats.nw <- getnetwork(learn(rats.nw,rats,rats.prior))
\dontrun{newrat <- getnetwork(drawnetwork(rats.nw,rats,rats.prior))}
}
\keyword{models}
|
4f3ebfe081cb70932af5bdc2dbfed2ff870418b2 | 9158695e09e952d685bf7a00804c79a79db734d9 | /R/Fnames.r | 4863d9cec531f20c64a4114dcaec5004fbf7f557 | [
"MIT"
] | permissive | hdeng88/publishr | fc7bfed9f1c32aeb1ed8889117998a69cd0d37c5 | 7f1b2c9836713c1f7d5f2633020509a753902ff2 | refs/heads/master | 2023-08-31T23:31:47.799351 | 2021-03-02T19:42:39 | 2021-03-02T19:42:39 | 61,814,621 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 308 | r | Fnames.r | #----------------------------------------------------------------------------#
#' @title Factor names
#' @description Return a list of a Factor variables
#' @param x a dataframe to deal with
#' @export
Fnames = function (x)
{
flist <- sapply(x, is.factor)
flist <- colnames(x[, flist])
return(flist)
}
|
1f51ba1571426ab634d77c4bbb20f0863c83cb90 | b1fb0f1a62f14b2626a511611578deec69dd87d7 | /dataprods/clusterTester/ui.R | 3aef670d9ebbeb9e90bbce7f1446881093581463 | [
"MIT"
] | permissive | jjdelvalle/datasciencecoursera | e37a5ad6156eb78590dcc18ccb2fb415b3b5fde9 | 5afd476b713df421524f6c9b7a0125cc838bc33b | refs/heads/master | 2021-10-24T23:20:20.922665 | 2019-03-29T18:41:18 | 2019-03-29T18:41:18 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,046 | r | ui.R | #
# This is the user-interface definition of a Shiny web application. You can
# run the application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("MPG Clusters"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("fields",
"Variable to contrast MPG to:",
names(mtcars)[2:11],
selected = "hp"),
br(),
sliderInput("clusters",
"Number of clusters:",
min = 1,
max = 10,
value = 2),
br(),
h3("Dictionary of variables:"),
strong("mpg:"), span("Miles/(US) gallon"),
br(), strong("cyl:"), span("Number of cylinders"),
br(), strong("disp:"), span("Displacement (cu.in.)"),
br(), strong("hp:"), span("Gross horsepower"),
br(), strong("drat:"), span("Rear axle ratio"),
br(), strong("wt:"), span("Weight (1000 lbs)"),
br(), strong("qsec:"), span("1/4 mile time"),
br(), strong("vs:"), span("Engine (0 = V-shaped, 1 = straight)"),
br(), strong("am:"), span("Transmission (0 = automatic, 1 = manual)"),
br(), strong("gear:"), span("Number of forward gears"),
br(), strong("carb:"), span("Number of carburetors")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot"),
h1("What is MPG Clusters?"),
p("This is an exploratory data analysis (EDA) app that allows you to assess data from the famous `mtcars` data by allowing you to set what variables you want to contraste and how many clusters you want to create."),
h3("What does that name even mean?"),
p("First we have to define a few terms. MPG means (US) Miles per gallon. What does cluster mean? A cluster is a group of data points defined either manually of algorithmically (systematically, automatically)."),
p("So what this app does is let you compare different variables to the overall MPG a car would have. The comparison is done by plotting the selected variable against the resulting MPG."),
h3("How does this work and what do the controls even do?"),
p("First you need to realize that clustering is done in a 2-dimensional space in this app. This means that we need another (a second variable) variable to compare MPG against. This is what the first control does (the select/combo box)"),
p("The second control is all about how many clusters you want your data to be segmented in. This is all in the user's control and is usually set empirically as to what is optimal. This is a visualization tool though, which means it will help you explore the data at your own pace using your own criteria. For this reason we allow the number of clusters to be set."),
br()
)
)
))
|
7510690120927a88beaae3bf8b5540c37bbc5284 | 092092a600d529414d172ab1c4726e935c5489e4 | /ising/ising_functions.R | b4fa3d1960a219501c6f0c15fc08f58cd8a1786c | [
"MIT"
] | permissive | niloyb/LlagCouplings | a17ba8e28fc02820edb1a3ecc33f49b52c67002c | 6db8067655fcbd2084fdb70ce4ed95de327bf194 | refs/heads/master | 2022-02-03T01:47:21.484315 | 2022-02-01T23:16:01 | 2022-02-01T23:16:01 | 188,317,660 | 11 | 1 | null | null | null | null | UTF-8 | R | false | false | 6,010 | r | ising_functions.R | # Functions for the Ising model SSG and PT chains
Rcpp::sourceCpp("ising/ising.cpp")
# get_ising_ssg_kernel returns the kernels of a single SSG and a coupled SSG chain
get_ising_ssg_kernel <- function(size, beta) {
# precomputed probability for single-site flips, given sum of neighbors
ss <- c(-4, -2, 0, 2, 4)
probas <- exp(ss * beta) / (exp(ss * beta) + exp(-ss * beta))
# initialization of Gibbs chain for Ising model
ising_rinit <- function(size = 32){
initial_values <- 2 * rbinom(size*size, 1, 0.5) - 1
state <- matrix(initial_values, nrow = size, ncol = size)
return(state)
}
# one step of Gibbs sampler, i.e. one full sweep over all components
ising_single_kernel <- function(chain_state, probas){
chain_state <- ising_gibbs_sweep_(chain_state, probas)
return(chain_state)
}
# one step of coupled Gibbs sampler, i.e. one full sweep over all components
ising_coupled_kernel <- function(chain_state1, chain_state2, probas){
res_ <- ising_coupled_gibbs_sweep_(chain_state1, chain_state2, probas)
return(list(chain_state1 = res_$state1, chain_state2 = res_$state2))
}
return(list(
init = function() {
res <- ising_rinit(size)
return(list(
chain_state = res,
current_pdf = NA
))
},
kernel = function(chain_state, current_pdf, iteration) {
res <- ising_single_kernel(chain_state, probas)
return(list(
chain_state = res,
current_pdf = NA
))
},
coupled_kernel = function(chain_state1, chain_state2, current_pdf1, current_pdf2, iteration) {
res <- ising_coupled_kernel(chain_state1, chain_state2, probas)
return(list(
chain_state1 = res$chain_state1,
chain_state2 = res$chain_state2,
current_pdf1 = NA,
current_pdf2 = NA
))
}
))
}
get_ising_pt_kernel <- function(size, betas, proba_swapmove) {
# The functions here are adapted from ising.R in the unbasedmcmc package to avoid computing
# unnecessary state which is not used in our results.
nchains <- length(betas)
# precomputed probability for single-site flips, given sum of neighbors
ss <- c(-4,-2,0,2,4)
probas <- sapply(betas, function(beta) exp(ss * beta) / (exp(ss * beta) + exp(-ss * beta)))
ising_ssg_kernel <- list()
for (i in 1:length(betas)) {
ising_ssg_kernel[[i]] <- get_ising_ssg_kernel(size, betas[i])
}
ising_pt_rinit <- function() {
chain_states <- list()
for (ichain in 1:nchains) {
res <- ising_ssg_kernel[[ichain]]$init()
chain_states[[ichain]] <- res$chain_state
}
return(list(
chain_state = chain_states,
current_pdf = NA
))
}
ising_pt_single_kernel <- function(chain_states, current_pdf, iteration) {
u_iteration <- runif(1)
nchains <- length(chain_states)
if (u_iteration < proba_swapmove) {
# swap move
sumstates <- unlist(lapply(chain_states, ising_sum_))
nswap_attempts <- 1
for (ichain in 1:(nchains-1)) {
tXi <- sumstates[ichain]
tXip1 <- sumstates[ichain+1]
swapaccept_logprob <- (betas[ichain] - betas[ichain+1]) * (tXip1 - tXi)
swapaccept_u <- runif(1)
if (log(swapaccept_u) < swapaccept_logprob) {
# do swap
tmp <- chain_states[[ichain]]
chain_states[[ichain]] <- chain_states[[ichain+1]]
chain_states[[ichain+1]] <- tmp
tmp <- sumstates[ichain]
sumstates[ichain] <- sumstates[ichain+1]
sumstates[ichain+1] <- tmp
}
}
} else {
# Gibbs move
for (ichain in 1:nchains) {
res <- ising_ssg_kernel[[ichain]]$kernel(chain_states[[ichain]], NA, iteration)
chain_states[[ichain]] <- res$chain_state
}
}
return(list(
chain_state = chain_states,
current_pdf = NA
))
}
ising_pt_coupled_kernel <- function(chain_states1, chain_states2, current_pdf1, current_pdf2, iteration) {
nchains <- length(chain_states1)
u_iteration <- runif(1)
if (u_iteration < proba_swapmove) {
# swap move
sumstates1 <- unlist(lapply(chain_states1, ising_sum_))
sumstates2 <- unlist(lapply(chain_states2, ising_sum_))
for (ichain in 1:(nchains-1)){
tXi_1 <- sumstates1[ichain]
tXip1_1 <- sumstates1[ichain+1]
tXi_2 <- sumstates2[ichain]
tXip1_2 <- sumstates2[ichain+1]
deltabeta <- betas[ichain] - betas[ichain+1]
# swapaccept_logprob <- tXi * (-deltabeta) + tXip1 * deltabeta
swapaccept_logprob1 <- deltabeta * (tXip1_1 - tXi_1)
swapaccept_logprob2 <- deltabeta * (tXip1_2 - tXi_2)
swapaccept_u <- runif(1)
if (log(swapaccept_u) < swapaccept_logprob1){
# do swap
tmp <- chain_states1[[ichain]]
chain_states1[[ichain]] <- chain_states1[[ichain+1]]
chain_states1[[ichain+1]] <- tmp
tmp <- sumstates1[ichain]
sumstates1[ichain] <- sumstates1[ichain+1]
sumstates1[ichain+1] <- tmp
}
if (log(swapaccept_u) < swapaccept_logprob2){
# do swap
tmp <- chain_states2[[ichain]]
chain_states2[[ichain]] <- chain_states2[[ichain+1]]
chain_states2[[ichain+1]] <- tmp
tmp <- sumstates2[ichain]
sumstates2[ichain] <- sumstates2[ichain+1]
sumstates2[ichain+1] <- tmp
}
}
} else {
# Gibbs move
for (ichain in 1:nchains){
res <- ising_ssg_kernel[[ichain]]$coupled_kernel(chain_states1[[ichain]], chain_states2[[ichain]], NA, NA, iteration)
chain_states1[[ichain]] <- res$chain_state1
chain_states2[[ichain]] <- res$chain_state2
}
}
return(list(
chain_state1 = chain_states1,
chain_state2 = chain_states2,
current_pdf1 = NA,
current_pdf2 = NA
))
}
return(list(
init = ising_pt_rinit,
kernel = ising_pt_single_kernel,
coupled_kernel = ising_pt_coupled_kernel
))
}
|
ebc74caaa548a5cad5d36e35b53cfb1bcf84d66c | 75db022357f0aaff30d419c13eafb9dddfce885a | /inst/Requests/scofo.r | 29a697a6d275f06c8e194299d2e94d3253ec333d | [] | no_license | LobsterScience/bio.lobster | d4c553f0f55f561bb9f9cd4fac52c585e9cd16f8 | b2af955291cb70c2d994e58fd99d68c6d7907181 | refs/heads/master | 2023-09-01T00:12:23.064363 | 2023-08-23T16:34:12 | 2023-08-23T16:34:12 | 60,636,005 | 11 | 5 | null | 2017-01-20T14:35:09 | 2016-06-07T18:18:28 | R | UTF-8 | R | false | false | 1,882 | r | scofo.r |
p = bio.lobster::load.environment()
la()
p$current.assessment.year = p$current.assessment.year - 1 ########### check the year ############### !!!!!!!!!!!
figdir = file.path(project.datadirectory("bio.lobster"),"figures")
p$lfas = c("27", "28", "29", "30", "31A", "31B", "32","33","34","35","36","38") # specify lfas for data summary
p$subareas = c("27N","27S", "28", "29", "30", "31A", "31B", "32","33E","33W","34","35","36","38") # specify lfas for data summary
CPUE.data<-CPUEModelData(p,redo=T)
cpueData= CPUEplot(CPUE.data,lfa= p$lfas,yrs=1982:2018,graphic='R')$annual.data
mu = with(subset(cpueData,YEAR<2017&YEAR>1989),tapply(CPUE,LFA,median))
mu = mu[1:8]
x11(width=7,height=8)
par(mfrow=c(6,2),mar=c(0,0,0,0),omi=c(0.3,0.6,0.2,0.2),las=1,tcl=0.3)
for(i in 1:length(p$lfas)){
crd = subset(cpueData,LFA==p$lfas[i],c("YEAR","CPUE"))
crd = merge(crd,data.frame(YEAR=min(crd$YEAR):max(crd$YEAR)),all=T)
usr = mu[i] * 0.8
lrp = mu[i] * 0.4
# plot
x = ifelse(i%in%c(11,12),'s','n')
y = ifelse(i%in%seq(1,11,2),'s','n')
CatchRatePlot(data = crd ,usr = usr,lrp=lrp,lfa = p$lfas[i],fd=figdir,ylim=c(0,2.8),xlim=c(1985,2018),rm=F,title.line=-1,xaxt=x,yaxt=y,regions=T)
}
mtext("CPUE (kg / trap haul)",2,outer=T,las=0,line=2.6)
savePlot(file.path(figdir,'scofoCPUE.png'),type='png')
x11(width=17,height=8)
# Stacked Bar Plot with Colors and Legend
ann.land = lobster.db('annual.landings')
sea.land = lobster.db('seasonal.landings')
land = cbind(subset(ann.land,YR>1987,-c(8,10:15)), sea.land[13:43,-1],subset(ann.land,YR>1987,15))
landings=t(land[,-1])
barplot(landings, main="Total Landings (t)", xlab="", col=rainbow_hcl(nrow(landings)), names.arg=1988:2018, legend = rownames(landings),args.legend=list(x='topleft',bty='n'))
savePlot(file.path(figdir,'scofoLAND.png'),type='png')
|
b47f0f5b878cc68ff9816784c2ce76fc6a1d3501 | 82d128a4b47a0a3a85e6c768b25df5848b7f3b54 | /dvlp/survival.R | a7328a3239a0afe75699bb7cde8e89f7d3dc4064 | [] | no_license | tetomonti/CBMRtools | 37e19db6a23c46882ec850df64a0a664f39d57f6 | 6ea11896423219a1df91528eed7ba7744e1d27d0 | refs/heads/master | 2021-03-27T10:27:51.753463 | 2020-02-06T19:03:14 | 2020-02-06T19:03:14 | 35,168,993 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 8,163 | r | survival.R | ##################################################################
# Coxph-based gene ranking
##################################################################
coxph.pvalue <- function( x, digits=3, logtest=FALSE )
{
# this is copied from the procedure print.coxph. It simply implements
# the computation of the wald statistic z and corresponding p-value.
#
# INPUT: x is the object returned from a call to coxph()
# OUTPUT: the wald statistic and the corresponding p-value
coef <- x$coef
se <- sqrt(diag(x$var))
if(is.null(coef) | is.null(se))
stop("Input is not valid")
z <- coef/se
# p-value of logtest
#
if ( logtest )
{
lt <- -2 * (x$loglik[1] - x$loglik[2])
df <- if (is.null(x$df)) sum(!is.na(coef)) else round(sum(x$df),2)
p <- signif(1 - pchisq(lt, df),digits)
}
# alternatively, p-value of coefficient
#
else {
p <- signif(1 - pchisq((coef/se)^2, 1), digits )
}
return ( c(z,p) )
}
gene.coxph <- function( x, y, bare=FALSE, verbose=FALSE, singular.ok=FALSE )
{
# INPUT:
# - x (m x n) matrix for m genes and n experiments
# - y Surv object
# - bare if true, return p-value only
#
# OUPUT:
# (m x 2) matrix reporting z-statistic and p-value as
# computed by coxph for each gene
#
if ( !is.Surv(y) )
stop( "y must be of type Surv" )
z <- t(apply( x,1,function(w){ coxph.pvalue( coxph(y~w,singular.ok=singular.ok) ) } ))
colnames(z) <- c("z","p")
if ( bare )
return( z[,2] )
else
return(z)
}
perm.coxph <- function( x, y, nperm=100, seed=NULL, verbose=FALSE, online=TRUE, two.sided=FALSE )
{
if ( two.sided )
{
VERBOSE( verbose, "Two-sided test.\n" )
score <- function(x,cls,verbose) { gene.coxph( x, y=cls, bare=FALSE, verbose=verbose )[,1] }
x.perm <-
perm.2side( x, y, nperm=nperm, score=score, seed=seed, online=online, rnd=3, verbose=verbose )$pval
}
else
{
VERBOSE( verbose, "One-sided test.\n" )
score <- function(x,cls,verbose) { gene.coxph( x, y=cls, bare=FALSE, verbose=verbose )[,2] }
x.perm <-
perm.1side( x, y, nperm=nperm, score=score, seed=seed, online=online, rnd=3, verbose=verbose )$pval
}
x.perm <- x.perm[,c("score","p2","fdr","maxT")]
pval <- gene.coxph(x,y,bare=TRUE)
x.perm <- cbind(x.perm,asymp.p=pval,asymp.fdr=pval2fdr(pval))
x.perm
}
##################################################################
# KM-based gene ranking
##################################################################
survdiff.pvalue <- function( sobj )
{
if ( !is.list(sobj) | names(sobj)[5]!="chisq" ) stop( "Survdiff object expected" )
return( 1-pchisq(sobj$chisq,length(sobj$n)-1) )
}
survdiff.matrix <- function(sobj)
{
out <- cbind(N=sobj$n,
Observed=round(sobj$obs,2),
Expected=round(sobj$exp,2),
'(O-E)^2/E'=round((sobj$obs-sobj$exp)^2/sobj$exp,3),
'(O-E)^2/B'=round(diag((sobj$obs-sobj$exp)^2/sobj$var),3))
out <- cbind(out,chisq=round(sobj$chis,2))
out <- cbind(out,pval=signif(survdiff.pvalue(sobj),2))
out
}
km.survfit <- function( x, S, nmin=1, probs=NULL, digits=3, debug=FALSE )
{
# INPUT:
# - x n-sized vector of predictive values
# - S n-sized Surv object
# - nmin min acceptable number of observations in a split
# - probs prequantize x by calling quantile(x,probs=probs)
#
# OUPUT:
# 3-tuple with:
# - thresh the selected threshold in the range of x
# - p.value the p.value returned by survfit regressed on 'x>thresh'
# - geq the number of x's for which x>thresh is true
#
if ( !is.Surv(S) )
stop( "S must be a Surv object" )
if ( nmin>(length(x)-1)/2 )
stop( paste("nmin too large", nmin) )
if ( nmin<1 )
stop( paste("nmin too small:", nmin) )
if ( !is.null(probs) & nmin>1 )
warning( "nmin>1 with quantization deprecated" )
n <- length(unique(x))
if ( n<nmin*2 )
stop( paste("not enough x values for given nmin:",n,"(", nmin*2,"needed )") )
if ( !is.null(probs) & n<length(probs) )
stop( paste("not enough x values for given quantiles:",n,"(", length(probs),"needed )") )
idx <- !is.na(x)
x <- x[idx]
S <- S[idx,]
# define the set of candidate thresholds
#
x.srt <- sort(unique(x))
x.thresh <- if ( is.null(probs) )
( x.srt[-1] + x.srt[-length(x.srt)] ) / 2
else
quantile(x.srt,probs)
if (is.null(probs))
x.thresh <- x.thresh[nmin:(length(x.thresh)-nmin+1)]
# x.split is a matrix with as many columns as thresholds, with each
# column indicating which x-values are less than or equal to (FALSE) and
# greater than (TRUE) the corresponding threshold
#
x.split <- t(apply(matrix(x,length(x),length(x.thresh)),1,'>',x.thresh))
x.p <- apply( x.split,2,function(z){(1-pchisq(survdiff(S~z)$chisq,1))} )
best <- which.min( x.p )
if ( !is.null(digits) ) x.p <- signif(x.p,digits)
if ( !debug )
return( c( x.thresh[best], # best trheshold
x.p[best], # p-value associated to best threshold
sum(x.split[,best]), # no. of obs greater than threshold
sum(S[x.split[,best],1])>sum(S[!x.split[,best],1]))
# does greater than threshold predict good prognosis
)
else
return( cbind(x.thresh, x.p, apply(x.split,2,sum)) )
}
gene.km.survfit <- function( x, surv, nmin=1, srt=FALSE, probs=NULL, bare=FALSE, debug=FALSE, ... )
{
x.km <- t(apply( x,1,km.survfit,surv,nmin=nmin,probs=probs,debug=debug))
if ( debug ) return(x.km)
# ELSE ..
#
colnames(x.km) <- c( "thresh", "p.value", "gt", "prognosis" )
if ( srt ) {
x.ord <- order(x.km[,2])
x.km <- cbind( x.km[x.ord,],x.ord )
colnames(x.km)[ncol(x.km)] <- "order"
}
if (bare)
return (x.km[,2])
else
return (x.km)
}
plot.km.survfit <- function( gct, surv, km, r, col=c("blue","red"), lty=c(1,2) )
{
i.pv <- match( "p.value", colnames(km) ); if (is.na(i.pv)) stop("p.value not found" )
i.th <- match( "thresh", colnames(km) ); if (is.na(i.th)) stop("thresh not found" )
i.gt <- match( "gt", colnames(km) ); if (is.na(i.gt)) stop("gt not found" )
i.od <- match( "order", colnames(km) );
if ( is.na(i.od) )
{
warning( "order not found, genes sorted automatically\n" )
ord <- order(km[,i.pv])
km <- cbind( km[ord,], ord )
colnames(km)[ncol(km)] <- "order"
i.od <- ncol(km)
}
gname <- rownames(km)[r]
n <- nrow(surv)
nx <- max(surv[,1])
off <- .05*nx
x.t <- as.vector(sign(gct[km[r,i.od],]>km[r,i.th]))
plot( survfit(surv~x.t), col=col, lty=lty )
legend( off, .01, col=col, lty=lty, yjust=0,
legend=paste( gname, c("<=",">"), round(km[r,i.th],2), sep="") )
legend( nx-off,.01,col=col,lty=lty,xjust=1, yjust=0,
legend=paste("n=",c(nrow(surv)-km[r,i.gt],km[r,i.gt])))
text( x=nx-off, y=1, labels=paste("p-value =",km[r,i.pv]), adj=c(1,0) )
#cat("offset:", off, "\n" )
#cat("p-value =", km[r,i.pv], "\n" )
}
perm.survfit <- function( x, surv, nperm, nmin=1, probs=NULL, seed=NULL, online=TRUE, verbose=FALSE )
{
# define the score function
#
score <- function(x,surv,nmin,probs,verbose)
{
gene.km.survfit( x, surv, nmin=nmin, probs=probs, bare=TRUE, verbose=FALSE )
}
x.obs <- gene.km.survfit(x, surv, nmin=nmin, probs=probs, bare=FALSE, verbose=FALSE )
# call the generic permutation routine
#
x.prm <- perm.1side( x, surv, nperm=nperm, score=score, seed=seed,
online=online, verbose=verbose, nmin=nmin, probs=probs )
list(pval=cbind(x.obs[,c("thresh","gt")],x.prm$pval),nperm=x.prm$nperm)
}
debug.perm.survfit <- function()
{
source("read.res.R")
library(survival)
gct.x <- read.gct("~/wi/scripts/tests/t_Survfit.gct" )
gct.y <- read.table("~/wi/scripts/tests/t_Survfit.txt",header=TRUE)[,c(4,3)]
gct.s <- Surv(gct.y[,1],gct.y[,2])
x.km <- gene.km.survfit( gct.x, gct.s, probs=seq(.1,.9,.1),nmin=1 )
x.prm <- perm.survfit( gct.x, gct.s, nperm=100, probs=seq(.2,.8,.1), nmin=1, verbose=TRUE )
}
# source("~/dvlp/R/survival.R")
|
b326f64df63a7491b3b6741041a548e6172565eb | 72d9009d19e92b721d5cc0e8f8045e1145921130 | /bpnreg/man/fit.bpnr.Rd | c2cf3cd76624aae0064a19f26195ae59740dedc9 | [] | no_license | akhikolla/TestedPackages-NoIssues | be46c49c0836b3f0cf60e247087089868adf7a62 | eb8d498cc132def615c090941bc172e17fdce267 | refs/heads/master | 2023-03-01T09:10:17.227119 | 2021-01-25T19:44:44 | 2021-01-25T19:44:44 | 332,027,727 | 1 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,080 | rd | fit.bpnr.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/classfunctions.R
\name{fit.bpnr}
\alias{fit.bpnr}
\title{Model fit for a Bayesian circular regression model}
\usage{
\method{fit}{bpnr}(object)
}
\arguments{
\item{object}{a \code{bpnr object} obtained from the function \code{bpnr()}.}
}
\value{
a matrix containing the computed log pointwise predictive density
(lppd), Deviance Information Criterion (DIC), an alternative version of the
DIC (DIC_alt), and the Watanabe-Akaike Information Criterion computed in
two different ways (WAIC, WAIC2). The matrix also contains the number of
parameters or 'effective number' of parameters that the several statistics
are based on. Computation of the criteria is done according to Gelman et.al
(2014) in *Bayesian Data Analysis*.
}
\description{
Outputs several model fit statistics for the Bayesian circular regression
model
}
\examples{
library(bpnreg)
fit.Motor <- bpnr(pred.I = Phaserad ~ 1 + Cond, data = Motor,
its = 100, burn = 10, n.lag = 3)
fit(fit.Motor)
}
|
e9cbce11da883fe3dcb5f113361c487ba8d007e8 | 041e37f557b9814921851fe1c4f0fb2b40a9edfc | /Evaluations/aveMetrics.R | 66e277b04d3bb8c4193203cd93747ec1ee7769b4 | [] | no_license | kuan0911/ISDEvaluation | 81aeb4b2ed6cfb10f13dea19857e02fc09c87ae7 | 0dbf2da9cdb85d287f9c4d3c94b8ec791ca3d7d0 | refs/heads/master | 2023-08-31T20:08:16.841262 | 2023-08-29T05:28:17 | 2023-08-29T05:28:17 | 236,837,046 | 2 | 0 | null | 2020-01-28T20:42:25 | 2020-01-28T20:42:24 | null | UTF-8 | R | false | false | 5,212 | r | aveMetrics.R | #source('Data/synthesizeDataN.R')
source('analysisMaster.R')
# source('Data/syntheticData/syntheticDataN1.R')
# source('Data/syntheticData/syntheticDataN2.R')
# source('Data/syntheticData/syntheticDataN3.R')
# source('Data/syntheticData/syntheticDataN4.R')
# source('Data/syntheticData/syntheticDataN5.R')
aveMetrics = function(ISD,show=T,std=F,LL=T,LLTest=T) {
if(!is.null(ISD)) {
if(length(ISD$survivalCurves)>2) {print('aveMetrics can not work with more than one model')}
if(show==T){print(paste(ISD$results$Model[1],' N =',ISD$results$N[1],sep=' '))}
C = mean(ISD$results$Concordance)
Cstd = sd(ISD$results$Concordance)
if(show==T&std==T){print(paste('Conc:',trunc(C*1000)/1000,'+/-',trunc(Cstd*1000)/1000,sep=' '))}
else if(show==T&std==F) {print(paste('Conc:',trunc(C*1000)/1000,sep=' '))}
B = mean(ISD$results$BrierInt)
Bstd = sd(ISD$results$BrierInt)
if(show==T&std==T){print(paste('Brier:',trunc(B*1000)/1000,'+/-',trunc(Bstd*1000)/1000,sep=' '))}
else if(show==T&std==F) {print(paste('Brier:',trunc(B*1000)/1000,sep=' '))}
L = mean(ISD$results$L1Loss)
Lstd = sd(ISD$results$L1Loss)
if(show==T&std==T){print(paste('L1Loss:',trunc(L*1000)/1000,'+/-',trunc(Lstd*1000)/1000,sep=' '))}
else if(show==T&std==F) {print(paste('L1Loss:',trunc(L*1000)/1000,sep=' '))}
if(LL) {
LL = mean(ISD$results$Neg_loglik)
LLstd = sd(ISD$results$Neg_loglik)
if(show==T&std==T){print(paste('Neg-Loglik:',trunc(LL*1000)/1000,'+/-',trunc(LLstd*1000)/1000,sep=' '))}
else if(show==T&std==F) {print(paste('Neg-Loglik:',trunc(LL*1000)/1000,sep=' '))}
}else {
LL = NA
LLstd = NA
}
if(LLTest) {
LLTest = mean(ISD$results$Neg_loglik_test)
LLTeststd = sd(ISD$results$Neg_loglik_test)
if(show==T&std==T){print(paste('Neg-Loglik-test:',trunc(LLTest*1000)/1000,'+/-',trunc(LLTeststd*1000)/1000,sep=' '))}
else if(show==T&std==F) {print(paste('Neg-Loglik-test:',trunc(LLTest*1000)/1000,sep=' '))}
}else {
LLTest = NA
LLTeststd = NA
}
D = ISD$results$DCalibration[1]
if(show==T){print(paste('DCal:',trunc(D*1000)/1000,sep=' '))}
}else{
print("input is null")
C=NA;Cstd=NA;B=NA;Bstd=NA;L=NA;Lstd=NA;D=NA;LL = NA;LLstd = NA;LLTest = NA;LLTeststd = NA
}
return(list(Model=ISD$results$Model[1],Concordance=C,Concordance_std=Cstd,BrierInt=B,BrierInt_std=Bstd,L1Loss=L,L1Loss_std=Lstd,DCalibration=D,neg_Loglik=LL,neg_Loglik_std=LLstd,neg_Loglik_test=LLTest,neg_Loglik_test_std=LLTeststd))
}
# multipleRuns = function(numRuns = 10, data_id=1, censorMode = 'random',censorRate = NULL) {
# resultsVec1 = rep(NA,numRuns)
# resultsVec2 = rep(NA,numRuns)
# for(iter in 1:numRuns) {
# print(iter)
# if(data_id==1) {
# survivalDataset = sythesizeN1(n=10000,"Data/syntheticData/syntheticDataN1.csv")
# }else if(data_id==2) {
# survivalDataset = sythesizeN2(n=10000,"Data/syntheticData/syntheticDataN2.csv")
# }else if(data_id==3) {
# survivalDataset = sythesizeN3(n=10000,"Data/syntheticData/syntheticDataN3.csv")
# }else if(data_id==4) {
# survivalDataset = sythesizeN4(n=10000,"Data/syntheticData/syntheticDataN4.csv")
# }else if(data_id==5) {
# survivalDataset = sythesizeN5(n=10000,"Data/syntheticData/syntheticDataN5.csv")
# }
# survivalDataset = sample_n(survivalDataset,1000)
# groundTruth = survivalDataset
# if(!is.null(censorRate)) {
# maxTime = quantile(survivalDataset$time,censorRate)
# }else {
# maxTime = 1000
# }
#
# if(censorMode=='random' | censorMode=='endpoint') {
# survivalDataset = randomCensor(survivalDataset,mode=censorMode,rate=1,maxTime=maxTime)
# }else if(censorMode == 'both') {
# survivalDataset = randomCensor(survivalDataset,mode='endpoint',rate=1,maxTime=maxTime)
# survivalDataset = randomCensor(survivalDataset,mode='random',rate=1,maxTime=maxTime)
# }
#
# if(data_id==5) {
# survivalDataset[survivalDataset$delta==0,'time'][runif(1,1,nrow(survivalDataset[survivalDataset$delta==0,]))] = max(survivalDataset$time)*30
# }
#
# ISD_decensor1 = analysisMaster(survivalDataset, DecensorModel = T, FS = F, numberOfFolds = 5,groundTruth = groundTruth,useAllData=T,testOnlyCensored=T,Ltype="Uncensored",decensorType='KM/C',curveExtend='slope',survivalPredictionMethod="Mean",L2=T,ModCmp=T,verbose=F)
# res_decensor1 = aveMetrics(ISD_decensor1,show=F)
# resultsVec1[iter] = res_decensor1$L1Loss
#
# ISD_decensor2 = analysisMaster(survivalDataset, DecensorModel = T, FS = F, numberOfFolds = 5,groundTruth = groundTruth,useAllData=T,testOnlyCensored=T,Ltype="Uncensored",decensorType='KM/C',curveExtend='truncate',survivalPredictionMethod="Mean",L2=T,ModCmp=T,verbose=F)
# res_decensor2 = aveMetrics(ISD_decensor2,show=F)
# resultsVec2[iter] = res_decensor2$L1Loss
# }
#
# #cat('Mean: ');cat(mean(resultsVec));cat(' std: ');cat(sd(resultsVec));cat('\n')
#
# return(list(resultsVec1=resultsVec1,resultsVec2=resultsVec2))
# }
showResultsVec = function(resultsVec) {
cat('Mean: ');cat(mean(resultsVec));cat(' std: ');cat(sd(resultsVec));cat('\n')
}
|
9e95c2bec98e1e0cd9c5e21514acc52f1f0badc6 | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/SBmedian/man/SBmedian.Rd | a02692a0f0ea727a4de574c0e5f104ef3f78830a | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | R | false | true | 446 | rd | SBmedian.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/package-SBmedian.R
\docType{package}
\name{SBmedian}
\alias{SBmedian}
\alias{SBmedian-package}
\title{Scalable Bayes with Median of Subset Posteriors}
\description{
Median-of-means is a generic yet powerful framework for scalable and robust estimation.
A framework for Bayesian analysis is called M-posterior, which estimates a median of subset posterior measures.
}
|
2aa3ec64a49b603dd6fd786d8d06d59adaeba1ee | a7d8102b6044c950af756432737aee3c501d9be5 | /caribou-location-tracking/src/clean-raw-data.R | afce7f5d5b09cd2285dc4f6cdd363ec5283e606b | [] | no_license | rjake/data | 28d6451e709f5774a32c93823d6a40bf1969991f | a0330c6923d0d9d3f884dea08b476fdedaca4ff1 | refs/heads/master | 2023-01-30T19:37:47.033332 | 2020-12-08T18:20:09 | 2020-12-08T18:20:09 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,270 | r | clean-raw-data.R |
# Load libraries
library(tidyverse)
library(janitor)
# Import data
individuals_raw <- read_csv("./caribou-location-tracking/raw/Mountain caribou in British Columbia-reference-data.csv")
locations_raw <- read_csv("./caribou-location-tracking/raw/Mountain caribou in British Columbia-gps.csv")
# Clean individuals
individuals <- individuals_raw %>%
clean_names() %>%
transmute(animal_id,
sex = animal_sex,
# Getting rid of whitespace to address inconsistent spacing
# NOTE: life stage is as of the beginning of deployment
life_stage = str_remove_all(animal_life_stage, " "),
reproductive_condition = animal_reproductive_condition,
# Cause of death "cod" is embedded in a comment field
death_cause = str_remove(animal_death_comments, ".*cod "),
study_site,
deploy_on_longitude,
deploy_on_latitude,
# Renaming to maintain consistency "deploy_on_FIELD" and "deploy_off_FIELD"
deploy_on_comments = deployment_comments,
deploy_off_longitude,
deploy_off_latitude,
deploy_off_type = deployment_end_type,
deploy_off_comments = deployment_end_comments) %>%
# reproductive_condition actually has two dimensions
separate(reproductive_condition, into = c("pregnant", "with_calf"), sep = ";", fill = "left") %>%
mutate(pregnant = str_remove(pregnant, "pregnant: ?"),
with_calf = str_remove(with_calf, "with calf: ?")) %>%
# TRUE and FALSE are indicated by Yes/No or Y/N
mutate_at(vars(pregnant:with_calf), ~ case_when(str_detect(., "Y") ~ TRUE,
str_detect(., "N") ~ FALSE,
TRUE ~ NA))
# Clean locations
locations <- locations_raw %>%
clean_names() %>%
transmute(event_id,
animal_id = individual_local_identifier,
study_site = comments,
season = study_specific_measurement,
timestamp,
longitude = location_long,
latitude = location_lat)
# Write to CSV
write_csv(individuals, "./caribou-location-tracking/individuals.csv")
write_csv(locations, "./caribou-location-tracking/locations.csv") |
e4438e3fdafe0e0768e54ad1cfb8a70b507cc0d1 | 3026f0f01ff036e69ec97461392d37b2e17b6428 | /plot1.R | 857867a407d649008ad34b58cc72b9f419f59bed | [] | no_license | LegsTech007/ExData_Plotting1 | 41e5a6cd214309a376deb4a381af9fcf9440abc8 | aad2835078a68b80c07dd81b818d21dc2489886b | refs/heads/master | 2021-01-17T01:14:25.341602 | 2015-06-05T17:58:25 | 2015-06-05T17:58:25 | 36,770,232 | 0 | 0 | null | 2015-06-03T00:40:22 | 2015-06-03T00:40:22 | null | UTF-8 | R | false | false | 534 | r | plot1.R | ##Read file, set date range as set variables as numeric
hp_data <- read.table("household_power_consumption.txt", header = T, sep=";", stringsAsFactors=FALSE)
hp_data <- hp_data[which(hp_data$Date=="1/2/2007" | hp_data$Date=="2/2/2007"),]
hp_data$Global_active_power=as.numeric(hp_data$Global_active_power)
##Plot to PNG
png("plot1.png", width=480, height=480)
hist(hp_data$Global_active_power, main="Global Active Power", xlab="Global Active Power (kilowatts)", ylab="Frequency", xlim=c(0, 6), ylim=c(0, 1200), col = "red")
dev.off() |
5b271cd5b2283a14556e71b25a4d770d1486214d | eb127bbb4e75966296b4a2234250ba6819e513b1 | /code_analysis_obj/plot_nsexacts.R | d925d61f9f616abc9d926d14c9ac15f4f5783b60 | [] | no_license | davidchampredon/stiagent | 29cc33cc8e1a54763ccd5f12f05949ac80354575 | dc6cd187b7649ee4517fc27ea66aff377c8ff892 | refs/heads/master | 2021-01-10T12:50:45.273558 | 2016-03-21T03:45:58 | 2016-03-21T03:45:58 | 43,753,973 | 0 | 0 | null | 2015-11-18T01:53:12 | 2015-10-06T13:56:06 | C++ | UTF-8 | R | false | false | 1,039 | r | plot_nsexacts.R | library(plyr)
library(ggplot2)
load("/Users/davidchampredon/Dropbox/MyStudies/Syphilis_vax/simul-results/2016-02-01/compScen_A_0.2_1_0p05.RData")
scen.name <- list()
pop.scen <- list()
for (i in 1:length(all.scen)) {
x <- all.scen[[i]]
scen.name[[i]] <- x[[length(x)]]
x[[length(x)]] <- NULL
pop <- list()
for (mc in 1:length(x)) {
pop[[mc]] <- as.data.frame(x[[mc]]$population)
}
pop.scen[[i]] <- do.call("rbind",pop)
pop.scen[[i]]$scen <- scen.name[[i]]
}
df <- do.call("rbind",pop.scen)
df$sa <- df$nSexActs_lifetime/(df$age-df$age1sex)
df1 <- subset(df,riskgroup==2)
df2 <- ddply(df1,c("scen","riskgroup"),#,"gender"),
summarize,
m=mean(sa),
qlo=quantile(sa,probs = 0.25),
qhi=quantile(sa,probs = 0.75))
df2
ddply(df,c("scen"),summarize,n=mean(riskgroup))
ddply(df,c("scen"),summarize,n=mean(sa))
plot(df$age,df$nSexActs_lifetime)
# g <- ggplot(df1)+geom_bar(aes(x=factor(riskgroup),
# y=mean(nSexActs_lifetime+1),
# colour=scen), position="dodge",stat="identity")
# plot(g)
|
b1ed97f51f537b0db6da873e1f8bbfe88234a74b | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/abd/examples/Trematodes.Rd.R | 7c80a0b8aaf40169903b5538c3a5df514df91c89 | [] | no_license | surayaaramli/typeRrh | d257ac8905c49123f4ccd4e377ee3dfc84d1636c | 66e6996f31961bc8b9aafe1a6a6098327b66bf71 | refs/heads/master | 2023-05-05T04:05:31.617869 | 2019-04-25T22:10:06 | 2019-04-25T22:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 183 | r | Trematodes.Rd.R | library(abd)
### Name: Trematodes
### Title: Frequencies of Fish Eaten by Trematode Infection Level
### Aliases: Trematodes
### Keywords: datasets
### ** Examples
demo(sec9.3)
|
85604f9c45c887718b867a629e80dc41130bd6a2 | 915bbce1893c4ee2dcef7065147a2b54542ced80 | /R/bridge_methods.R | 22580920eda310d6df070e39fa77e444e5d97bd2 | [] | no_license | quentingronau/bridgesampling | 8cea941a20ad0fd7874f8c3af25b5edfeffdcf2a | 6793386ffe30205d649d2fe5ce9597c0bff83142 | refs/heads/master | 2023-06-08T11:05:31.273244 | 2023-05-31T00:32:58 | 2023-05-31T00:32:58 | 85,564,272 | 31 | 16 | null | 2023-04-12T14:33:06 | 2017-03-20T10:32:46 | R | UTF-8 | R | false | false | 5,107 | r | bridge_methods.R | #' Methods for bridge and bridge_list objects
#'
#' Methods defined for objects returned from the generic \code{\link{bridge_sampler}} function.
#'
#' @param object,x object of class \code{bridge} or \code{bridge_list} as returned from \code{\link{bridge_sampler}}.
#' @param na.rm logical. Should NA estimates in \code{bridge_list} objects be removed? Passed to \code{\link{error_measures}}.
#' @param ... further arguments, currently ignored.
#'
#' @return
#' The \code{summary} methods return a \code{data.frame} which contains the log marginal likelihood plus the result returned from invoking \code{\link{error_measures}}.
#'
#' The \code{print} methods simply print and return nothing.
#'
#'
#' @name bridge-methods
NULL
# summary methods
#' @rdname bridge-methods
#' @method summary bridge
#' @export
summary.bridge <- function(object, na.rm = TRUE, ...) {
if( ! (object$method %in% c("normal", "warp3"))) {
stop('object$method needs to be either "normal" or "warp3".', call. = FALSE)
}
if (object$method == "normal") {
em <- error_measures(object)
out <- data.frame("Logml_Estimate" = object$logml,
"Relative_Mean_Squared_Error" = em$re2,
"Coefficient_of_Variation" = em$cv,
"Percentage_Error" = em$percentage,
"Method" = object$method,
"Repetitions" = 1,
stringsAsFactors = FALSE)
} else if (object$method == "warp3") {
out <- data.frame("Logml_Estimate" = object$logml,
"Method" = object$method,
"Repetitions" = 1)
}
class(out) <- c("summary.bridge", "data.frame")
return(out)
}
#' @rdname bridge-methods
#' @method summary bridge_list
#' @export
summary.bridge_list <- function(object, na.rm = TRUE, ...) {
if( ! (object$method %in% c("normal", "warp3"))) {
stop('object$method needs to be either "normal" or "warp3".', call. = FALSE)
}
em <- error_measures(object, na.rm = na.rm)
out <- data.frame("Logml_Estimate" = median(object$logml, na.rm = na.rm),
"Min" = em$min,
"Max" = em$max,
"Interquartile_Range" = em$IQR,
"Method" = object$method,
"Repetitions" = object$repetitions)
class(out) <- c("summary.bridge_list", "data.frame")
return(out)
}
# print summary methods
#' @rdname bridge-methods
#' @method print summary.bridge
#' @export
print.summary.bridge <- function(x, ...) {
if (x[["Method"]] == "normal") {
cat('\nBridge sampling log marginal likelihood estimate \n(method = "',
as.character(x[["Method"]]),
'", repetitions = ', x[["Repetitions"]], '):\n\n ',
x[["Logml_Estimate"]],
'\n\nError Measures:\n\n Relative Mean-Squared Error: ',
x[["Relative_Mean_Squared_Error"]],
'\n Coefficient of Variation: ', x[["Coefficient_of_Variation"]],
'\n Percentage Error: ', x[["Percentage_Error"]],
'\n\nNote:\nAll error measures are approximate.\n\n', sep = "")
} else if (x[["Method"]] == "warp3") {
cat('\nBridge sampling log marginal likelihood estimate \n(method = "',
as.character(x[["Method"]]),
'", repetitions = ', x[["Repetitions"]], '):\n\n ',
x[["Logml_Estimate"]],
'\n\nNote:\nNo error measures are available for method = "warp3"',
'\nwith repetitions = 1.',
'\nWe recommend to run the warp3 procedure multiple times to',
'\nassess the uncertainty of the estimate.\n\n', sep = "")
}
}
#' @rdname bridge-methods
#' @method print summary.bridge_list
#' @export
print.summary.bridge_list <- function(x, ...) {
cat('\nBridge sampling log marginal likelihood estimate \n(method = "',
as.character(x[["Method"]]), '", repetitions = ', x[["Repetitions"]],
'):\n\n ', x[["Logml_Estimate"]],
'\n\nError Measures:\n\n Min: ', x[["Min"]],
'\n Max: ', x[["Max"]],
'\n Interquartile Range: ', x[["Interquartile_Range"]],
'\n\nNote:\nAll error measures are based on ', x[["Repetitions"]],
' estimates.\n\n', sep = "")
}
# print methods
#' @rdname bridge-methods
#' @method print bridge
#' @export
print.bridge <- function(x, ...) {
cat("Bridge sampling estimate of the log marginal likelihood: ",
round(x$logml, 5), "\nEstimate obtained in ", x$niter,
" iteration(s) via method \"", x$method, "\".\n", sep = "")
}
#' @rdname bridge-methods
#' @method print bridge_list
#' @export
print.bridge_list <- function(x, na.rm = TRUE, ...) {
cat("Median of ", x$repetitions, " bridge sampling estimates\nof the log marginal likelihood: ",
round(median(x$logml, na.rm = na.rm), 5), "\nRange of estimates: ", round(range(x$logml, na.rm = na.rm)[1], 5), " to ",
round(range(x$logml, na.rm = na.rm)[2], 5),
"\nInterquartile range: ", round(stats::IQR(x$logml, na.rm = na.rm), 5), "\nMethod: ", x$method, "\n", sep = "")
if (any(is.na(x$logml))) warning(sum(is.na(x$logml))," bridge sampling estimate(s) are NAs.", call. = FALSE)
}
|
a7b7d1a42ce23ed1410ea739b054cf042f2f2353 | e85b4314da671b63f08bbd00c33c8c6ceda10726 | /Fusion_and_Proto_Visualisation/sa_test_gridded_in.R | dd03f5b408e02492052cc39323ce6460bab8c228 | [
"CC-BY-3.0"
] | permissive | XSpacious/SpaceApps2013 | fbe9c8b3f2f48c027a14f9192cd5b4fdd60750e5 | dbdeb42a44fe4d9f52f8d2ded1810aebc88a0306 | refs/heads/master | 2021-01-19T13:49:48.032404 | 2013-05-01T19:58:57 | 2013-05-01T19:58:57 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,043 | r | sa_test_gridded_in.R | # XSpacious
# International Space Apps Challenge 2013
#
# Licensed under a Creative Commons Attribution 3.0 Unported License.
# http://creativecommons.org/licenses/by/3.0/
#
# When using this code please attribute as follows
# including code authors and team members:
#
# This code was developed by the XSpacious project team
# as part of the International Space Apps Challenge 2013.
#
# Code Authors:
# Matthew C. Forman
#
# Team Members:
# Abdulrazaq Abba
# Rallou Dadioti
# Matthew C. Forman
# Ron Herrema
# Joel Mitchelson, Ogglebox Sensory Computing Ltd.
# Konstantina Saranti
# Andy Schofield
# Tim Trent
#
# Quick Test for gridded data on matrix. Resamples incoming data set to new grid.
require(akima)
jet.colours <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", "yellow",
"#FF7F00", "red", "#7F0000"))
# Read in gridded data matrix.
# Note: Test data set cannot be distributed, however simply contains 240 (h) x 121 (v) gridded area samples.
tab2d.dat.in <- as.matrix(read.table(file="Source data/era_tcwv_jul_rmse.dat"))
# Define coordinate system.
x.coord.vals <- ((0:(ncol(tab2d.dat.in)-1)) * 1.5) - 179.25
y.coord.vals <- ((0:(nrow(tab2d.dat.in)-1)) * 1.5) - 90
# Convert to matrix.
mat.dat.in <- t(tab2d.dat.in[nrow(tab2d.dat.in):1, ])
# Plot a quick check (contours).
filled.contour(x.coord.vals, y.coord.vals, mat.dat.in, color.palette=jet.colours)
# *** Resample to new grid.
# Replicate coordinate values to produce full sample position set.
x.coords.all <- matrix(rep(x.coord.vals, length(y.coord.vals)), byrow=T, nrow=length(y.coord.vals))
y.coords.all <- matrix(rep(y.coord.vals, length(x.coord.vals)), byrow=F, ncol=length(x.coord.vals))
# Define destination grid.
x.dest <- seq(-179.25, 179.25, length.out=240)
y.dest <- seq(-90, 90, length.out=121)
# Interpolate.
f.interp <- interp(x.coords.all, y.coords.all, t(mat.dat.in),
xo=x.dest, yo=y.dest)
dev.new()
# Plot as raster image on new grid.
image(f.interp$x, f.interp$y, f.interp$z, col=jet.colours(100))
|
f36a80037c6888d6de986601aca08d16223c98eb | fefa61346e5d97f339baaa4bd3bee36d2da401ec | /alternative_solution_with_dplyr_tmaps_htmlTable/eu_maps.R | 24749bc59a74eb94dd19f02a5e8890c0833f58a8 | [] | no_license | pablo14/EU_health | cdb0bcc0a6dac32ec97493dc83a6b9f435ae84ac | 2eb7d2a96ed7e1bfbd9f96ef2f6084c02766e777 | refs/heads/master | 2021-01-22T17:57:19.097132 | 2016-02-09T19:03:38 | 2016-02-09T19:03:38 | 32,360,049 | 3 | 7 | null | 2016-02-09T19:03:38 | 2015-03-16T23:50:29 | HTML | UTF-8 | R | false | false | 2,346 | r | eu_maps.R | library(magrittr)
library(knitr)
library(markdown)
library(dplyr)
library(tmap)
library(ISOcodes)
library(htmlTable)
## Read data (this data has already some data preparation)
data=read.delim("data.txt", header=TRUE)
data("ISO_3166_1") # countrycodes
data("Europe")
ISO_3166_1 %<>% transmute( iso_a2 = Alpha_2, iso_a3 = Alpha_3, Country = Name)
data %<>% mutate( iso_a2 = Country) %>% select(-Country)
data %<>% left_join(ISO_3166_1, by= "iso_a2")
data_hea_lif <- data %>% filter(Variable == "Healthy life years") %>%
group_by(Country) %>% summarise(Healthy_life=mean(X2012))
data_lif_exp <- data %>% filter(Variable == "Life expectancy") %>%
group_by(Country) %>% summarise(Life_Expectancy=mean(X2012))
data_merged <- left_join(data_hea_lif, data_lif_exp, by="Country") %>% mutate(age_gap=Life_Expectancy-Healthy_life) %>%
filter(Country != "NA")
Europe@data %>% left_join(ISO_3166_1, by="iso_a3") %>% left_join(data_merged, by="Country") -> Europe@data
map_1<- tm_shape(Europe) +
tm_fill("Healthy_life", textNA="NA") +
tm_borders() +
tm_text("iso_a3", cex="AREA", root=5) +
tm_layout_Europe("Healthy life years")
map_2 <- tm_shape(Europe) +
tm_fill("Life_Expectancy", textNA="NA") +
tm_borders() +
tm_text("iso_a3", cex="AREA", root=5) +
tm_layout_Europe("Life expectancy")
map_3 <- tm_shape(Europe) +
tm_fill("age_gap", textNA="NA") +
tm_borders() +
tm_text("iso_a3", cex="AREA", root=5) +
tm_layout_Europe("Age gap")
# #####################################
# ## Top 3 countries (healty and expectancy)
# ######################################
top3_hea_lif <- data_merged %>% arrange(desc(Healthy_life)) %>% select(Country, Healthy_life) %>% head(3)
top3_lif_exp <- data_merged %>% arrange(desc(Life_Expectancy)) %>% select(Country, Life_Expectancy) %>% head(3)
tables_top3 <- bind_cols(top3_hea_lif,top3_lif_exp)
# #####################################
# ## Top 3 countries (gap)
# ######################################
# ## Order data for both variables, and keeping the highest top 3
top3_highest_gap <- data_merged %>% arrange(desc(age_gap) ) %>% head(3)
top3_lowest_exp <- data_merged %>% arrange(desc(age_gap) ) %>% tail(3)
tables_top3_gap <- bind_cols(top3_highest_gap,top3_lowest_exp)
#knit("output.Rmd",encoding="UTF-8")
#markdownToHTML("output.md", "EU Geo Report.html")
|
c6c1a01ce99d7eb1a862a984f297328fdd9f9c82 | 55998a12f0e624e76ebd18e43c43ad937bb7c0f2 | /man/model_info.Rd | 06299c53ffa6a090bd36cdf5628fdf4d95f7e84b | [] | no_license | garrettgman/modelglyphs | e9294c88c5fe0abe5c2d31a1ab6c426a1bf84baf | e000f76928ca1f5c882cebef3ef0b3179ac7793f | refs/heads/master | 2021-01-10T20:13:45.175563 | 2012-03-27T19:58:04 | 2012-03-27T19:58:04 | 3,650,689 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 283 | rd | model_info.Rd | \name{model_info}
\alias{model_info}
\alias{model_info<-}
\title{Get/set the model info attribute of an mg_ensemble object.}
\usage{
model_info(x)
}
\arguments{
\item{x}{An object of class mg_ensemble}
}
\description{
model_info should be the output of \code{\link{model}}.
}
|
f956d239d101171e5887ed1dff2afeb654194819 | 082ef57530c810147354b42cefc5ae7a0de1a6f8 | /man/MQTAd.Rd | d3ef5f2b53680b21da001d8f53a152bc96817610 | [] | no_license | baolinwu/MTAR | 9ec1f387d3721cf4d74bc98ab8a32dc817c6f2d5 | 0e170a15a0b78d589e4c057ee866c82f1510fad8 | refs/heads/master | 2021-08-22T21:39:44.439376 | 2018-10-30T21:18:51 | 2018-10-30T21:18:51 | 115,526,658 | 5 | 0 | null | null | null | null | UTF-8 | R | false | true | 838 | rd | MQTAd.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mdm.R
\name{MQTAd}
\alias{MQTAd}
\title{Multiple quantitative trait association test with differing covariates}
\usage{
MQTAd(obj, G)
}
\arguments{
\item{obj}{fitted null model from MDM.null}
\item{G}{genotype vector}
}
\value{
\describe{
\item{p.value}{ three association p-values: an ombinus m-DF Wald test; two 1-DF Wald tests assuming common effect or common scaled effect (see ref) }
\item{coef}{ estimated variant regression coefficients for all traits}
}
}
\description{
Fast computation of genome-wide association test of multiple quantitative traits.
}
\references{
Wu,B. and Pankow,J.S. (2018) Fast and accurate genome-wide association test of multiple quantitative traits. \emph{Computational and mathematical methods in medicine}, in press.
}
|
d1d78c515be0f0c52d80748c4cc34c31cb8170c6 | bef5e21ee3a7fb88e714d22e3e21b3a2162335a4 | /scripts/additional_analysis/analysis_paper_loda.R | dea6a7e3aaf934a98fc1b3bc58f6cda01cf29842 | [] | no_license | lisa-sousa/xci_epigenetic_control | 6afbe40a75fca87105a285eadc30e2c4560940b3 | 99b06220923e31c816b16bfd731c6b798939e326 | refs/heads/master | 2021-07-08T11:45:30.531661 | 2020-01-28T15:31:29 | 2020-01-28T15:31:29 | 222,667,602 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 10,824 | r | analysis_paper_loda.R | ###################################################################################
#libraries
###################################################################################
library(ggplot2)
library(RColorBrewer)
library(here)
###################################################################################
#directories
###################################################################################
output_dir = "plots/additional_analysis"
input_dir_clones = "data/modelling/model/clones"
predictions_clones = c("predictions_clones_86.txt","predictions_clones_87.txt","predictions_clones_109.txt","predictions_clones_190.txt","predictions_clones_228.txt","predictions_clones_273.txt")
input_dir = "data/annotation_files/xist_transgenes"
clone = c("86","87","109","190","228","273")
chr = c("chrX","chrX","chrX","chrX","chr12","chr12")
###################################################################################
#parameters
###################################################################################
pseudocount = 0.001
thr_foldchange = c()
B=1000
###################################################################################
#functions to calculate normalized AER, do permutation test and plot clone distribution
###################################################################################
###read in clone data -> AER
get_clone_table <- function(file, chr){
table_clone = read.table(file=file,header = T)
table_clone = table_clone[grep(chr,table_clone$coord),]
table_clone = table_clone[,c(1,6)]
colnames(table_clone) = c("Genes","ratio")
return(table_clone)
}
###calculate normalized AER
get_foldchange <- function(input_dir,chr,clone,pseudocount){
table_clone_no_Dox_rep1 = get_clone_table(here(paste(input_dir,"/",chr,"_clones",sep=""),paste(clone,"_noDox_1.txt",sep="")),chr)
table_clone_no_Dox_rep2 = get_clone_table(here(paste(input_dir,"/",chr,"_clones",sep=""),paste(clone,"_noDox_2.txt",sep="")),chr)
table_clone_no_Dox = merge(table_clone_no_Dox_rep1,table_clone_no_Dox_rep2,by="Genes")
table_clone_no_Dox$mean_ratio = rowMeans(table_clone_no_Dox[,2:3])
table_clone_five_days_rep1 = get_clone_table(here(paste(input_dir,"/",chr,"_clones",sep=""),paste(clone,"_5Days_1.txt",sep="")),chr)
table_clone_five_days_rep2 = get_clone_table(here(paste(input_dir,"/",chr,"_clones",sep=""),paste(clone,"_5Days_2.txt",sep="")),chr)
table_clone_five_days = merge(table_clone_five_days_rep1,table_clone_five_days_rep2,by="Genes")
table_clone_five_days$mean_ratio = rowMeans(table_clone_five_days[,2:3])
table_clone = merge(table_clone_no_Dox,table_clone_five_days,by="Genes")
table_clone = data.frame(Genes = table_clone$Genes, no_Dox = table_clone$mean_ratio.x+pseudocount, five_days = table_clone$mean_ratio.y+pseudocount)
if(chr == "chrX"){table_clone = table_clone[table_clone$no_Dox > 0.2 & table_clone$no_Dox < 0.8,]}
if(chr == "chr12"){table_clone = table_clone[table_clone$no_Dox > 0.46 & table_clone$no_Dox < 0.86,]}
#table_clone$foldchange = table_clone$five_days/table_clone$no_Dox
table_clone$foldchange = (table_clone$five_days/(1-table_clone$five_days))*((1-table_clone$no_Dox)/table_clone$no_Dox)
return(table_clone)
}
####Permutation test
empirical_p_value <- function(B,table_clone_predictions,n,x){
fraction = rep(0,B)
for(i in 1:B){
boot_idx = sample(nrow(table_clone_predictions),n,replace = F)
boot_table = table_clone_predictions[boot_idx,]
fraction[i] = nrow(boot_table[boot_table$class == 0,])/nrow(boot_table)
}
p_value = sum(fraction > x)/B
return(list(p_value,fraction))
}
###scatterplot of normalized AER vs gene predictions
scatterplot_dense_colors <- function(x1, x2, xlab, ylab, main){
df = data.frame(x1,x2)
## Use densCols() output to get density at each point
x = densCols(x1,x2, colramp=colorRampPalette(c("black", "white")))
df$dens = as.factor(col2rgb(x)[1,] + 1L)
## Map densities to colors
cols = colorRampPalette(c("#000099", "#00FEFF", "#45FE4F", "#FCFF00", "#FF9400", "#FF3100"))(256)
cols = colorRampPalette(c("grey","black"))(256)
df$col = cols[df$dens]
cor = cor.test(x1,x2)
## Plot it, reordering rows so that densest points are plotted on top
ggplot = ggplot(data=df[order(df$dens),]) +
geom_point(aes(x1,x2,color=dens),size=0.5) +
scale_color_grey(start=0.7,end=0) +
labs(title=main, subtitle = paste('r=',round(cor$estimate,2),"\np=",signif(cor$p.value,2),sep="")) +
geom_smooth(aes(x1,x2),method = "lm", se = FALSE,color="#ff8080", size=0.5) +
scale_x_continuous(name=xlab, limits = c(0,1)) +
scale_y_continuous(name=ylab) +
theme_minimal(base_family = "Source Sans Pro") +
theme(panel.grid.minor = element_blank(), panel.grid.major.x = element_blank(),axis.text.x = element_text(size=8), axis.text.y = element_text(size=8),
axis.title=element_text(size=8), legend.position = "none",plot.title = element_text(size=8), plot.subtitle = element_text(size=7))
print(ggplot)
}
###################################################################################
#perform permutation test and plot results
###################################################################################
cairo_pdf(here(output_dir,"analysis_paper_loda.pdf"),width = 4,height = 4,onefile = T)
clone_performance = NULL
clone_fc = NULL
bootstrap_performance = as.data.frame(matrix(0,nrow = B,ncol = length(clone)))
for(i in 1:length(clone)){
print(paste("clone:",clone[i]))
table_clone = get_foldchange(input_dir,chr[i],clone[i],pseudocount)
print(paste("genes in clone:",nrow(table_clone)))
predictions = read.table(file = here(input_dir_clones,predictions_clones[i]),header = T)
table_clone_predictions = merge(table_clone,predictions,by="Genes")
table_clone_predictions = table_clone_predictions[table_clone_predictions$class == 0 | table_clone_predictions$class == 1,]
clone_fc = rbind(clone_fc,data.frame(foldchange=table_clone_predictions$foldchange,clone=clone[i],chr=chr[i]))
print(paste("genes with predictions:",nrow(table_clone_predictions)))
thr_foldchange = 0.9
table_clone_predictions_fc = table_clone_predictions[table_clone_predictions$foldchange < thr_foldchange,]
print(paste("genes with fc <",thr_foldchange,"are: ",nrow(table_clone_predictions_fc)))
x = nrow(table_clone_predictions_fc[table_clone_predictions_fc$class == 0,])/nrow(table_clone_predictions_fc)
p_value = empirical_p_value(B,table_clone_predictions,nrow(table_clone_predictions_fc),x)
print(paste("accuracy:",round(x,3),"p-value:",p_value[[1]]))
clone_performance = rbind(clone_performance,table(table_clone_predictions_fc$class)/nrow(table_clone_predictions_fc))
bootstrap_performance[,i] = p_value[[2]]
print(paste("silenced:",nrow(table_clone_predictions_fc[table_clone_predictions_fc$class == 0,])))
print(paste("not silenced:",nrow(table_clone_predictions_fc[table_clone_predictions_fc$class == 1,])))
cortest = cor.test(table_clone_predictions$vote,table_clone_predictions$foldchange)
scatterplot_dense_colors(table_clone_predictions$vote,table_clone_predictions$foldchange,"vote(class0)","foldchange",paste("clone",clone[i]))
table_clone_predictions$class = as.factor(table_clone_predictions$class)
wilcox =wilcox.test(table_clone_predictions$foldchange[table_clone_predictions$class==0],table_clone_predictions$foldchange[table_clone_predictions$class==1])$p.value
gg_box = ggplot(table_clone_predictions, aes(x=class,y=foldchange)) +
geom_boxplot(colour = "#4d4d4d",alpha = 0.7,outlier.size=0.1,lwd=0.4) +
labs(title=paste("clone",clone[i]), subtitle = paste("Wilcox-Test:",signif(wilcox,3))) +
theme_minimal(base_family = "Source Sans Pro") +
theme(panel.grid.minor = element_blank(), panel.grid.major.x = element_blank(),
axis.text.x = element_text(size=8, hjust=1), axis.text.y = element_text(size=8),
axis.title=element_text(size=8),plot.title = element_text(size=8),plot.subtitle = element_text(size=7)) +
scale_x_discrete(name = "silencing class") + scale_y_continuous(name = "folchange",limits = c(0,2))
print(gg_box)
}
###plot histogram and boxplots
colnames(bootstrap_performance) = clone
performance = data.frame(ind = factor(clone), y = clone_performance[,1]*100)
mean = data.frame(ind = factor(clone), y = colMeans(bootstrap_performance)*100)
ggplot(stack(bootstrap_performance*100), aes(x = ind, y = values)) +
geom_boxplot(notch=FALSE,fill = "lightgrey", colour = "grey",alpha = 0.7,outlier.shape = "",width=0.5) +
geom_jitter(position=position_jitter(h = 1,w=0.25),size=0.01,color="grey") +
stat_summary(fun.y="mean", geom="point", color = 'black',pch="_",size=18) +
theme_minimal(base_family = "Source Sans Pro") +
theme(panel.grid.minor = element_blank(), panel.grid.major.x = element_blank(),axis.text=element_text(size=8),
axis.title=element_text(size=8), plot.title = element_text(size=8)) +
scale_x_discrete(name = "clone") + scale_y_continuous(name = "genes predicted as silenced (%)", limits = c(20,90)) +
geom_point(data = data.frame(x = factor(clone), y = clone_performance[,1]*100),aes(x=x, y=y, size=15),color = 'red',pch="_",size=18)
dev.off()
#plot histogram of clone predictions
cairo_pdf(here(output_dir,"paper_figures_loda_histogram.pdf"),width = 2.7,height = 2.7,onefile = T)
ggplot(stack(bootstrap_performance*100), aes(x = values)) +
geom_histogram(binwidth=0.9, colour="black", fill="white",lwd=0.3) +
facet_grid(ind ~ .) +
geom_vline(aes(xintercept = y),performance, size=0.4, colour="red") +
geom_vline(aes(xintercept = y),mean, size=0.4, colour="black",linetype="dashed") +
scale_y_continuous(breaks=c(0,300),name = "# permutations") + scale_x_continuous(name="genes predicted as silenced (%)") +
theme_minimal(base_family = "Source Sans Pro") +
theme(panel.grid.minor = element_blank(), panel.grid.major.x = element_blank(),axis.text=element_text(size=8),
axis.title=element_text(size=8), plot.title = element_text(size=8))
dev.off()
#print AER distribution for each clone
cairo_pdf(here(output_dir,"paper_figures_loda_AER_density.pdf"),width = 5,height = 3,onefile = T)
ggplot(clone_fc, aes(x=foldchange,colour=clone)) +
geom_density(aes(linetype=clone),data=clone_fc,alpha=.4, lwd=0.5) +
scale_x_continuous(limits=c(0,2), name='normalized allelic expression ratio (AER)') +
scale_y_continuous(name='distribution of normalized AER') +
theme_minimal(base_family = "Source Sans Pro") +
theme(panel.grid.minor = element_blank(), panel.grid.major.x = element_blank(),axis.text=element_text(size=8),
axis.title=element_text(size=8), plot.title = element_text(size=8), legend.title = element_text(size=8),
legend.text = element_text(size=8))
dev.off()
|
f12b60846ab1872b2cf10216b21fe0eb9d9e8cdc | 7e9d0fb831546f65c9a5a091a734d1decbae298a | /run_analysis.r | d82216db5b25393613e3e2f25788686ee9e0916b | [] | no_license | LaurenR/tidyData | 4dd3fc6e9949c715e2195be88c6bb7f011d561c4 | c08013f8a52f608d83b4bc846a7fc189dc7fdb33 | refs/heads/master | 2020-12-24T14:45:05.562976 | 2015-06-20T20:04:21 | 2015-06-20T20:04:21 | 37,742,488 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,532 | r | run_analysis.r | setwd("C:/Users/Lauren/Documents/Data/tidy/UCI HAR Dataset") #SET WORKING DIRECTORY TO INSIDE FIRST FILE
list.files() #LIST FILES IN DIRECTORY
setwd("C:/Users/Lauren/Documents/Data/tidy/UCI HAR Dataset/test") #SET WORKING DIRECTORY TO FIRST DATA FILES NAMED TEST
subject_test <- read.table("subject_test.txt") #READ IN EACH TABLE (SUBJECT, X_Test, Y_Test) AS IT'S OWN VARIABLE
x_test <- read.table("x_test.txt")
y_test <- read.table("y_test.txt")
testFrame <- cbind(subject_test, y_test, x_test) #COMBINE EACH VARIABLE COLUMN WISE TO SAME DATA FRAME, NAME TESTFRAME
setwd("C:/Users/Lauren/Documents/Data/tidy/UCI HAR Dataset/train") #LOCATE TRAIN DATASET
subject_train <- read.table("subject_train.txt")
x_train <- read.table("X_train.txt")
y_train <- read.table("y_train.txt")
subject_train <- read.table("subject_train.txt")
trainFrame <- cbind(subject_train, y_train, x_train) #READ EACH TABLE AS OWN VARIABLE AND COMBINE COLUMN WISE FOR TRAIN DATA FRAME AS FOR TEST DATA
HARframe <- rbind(testFrame, trainFrame) #COMBINE TRAIN AND TEST DATA SETS TO COMPLETE STEP 2 (MERGE TRAINING AND TEST SETS TO CREATE ONE DATA SET)
colnames(HARframe)[1] <- "Subject" #NAME FIRST COLUMN SUBJECT, PART OF STEP 4
colnames(HARframe)[2] <- "Activity" #NAME SECOND COLUMN ACTIVITY, PART OF STEP 4
setwd("C:/Users/Lauren/Documents/Data/tidy/UCI HAR Dataset") #SET WD TO FILE THAT CONTAINS DATA LABELS - NAMED FEATURES
features <- read.table("features.txt", stringsAsFactors = FALSE) #LOCATE AND READ IN COLUMN LABELS FROM FEATURES.TXT
features <- features[,2] #EXTRACT ONLY THE NAMES OF VARIABLES
colnames(HARframe)[3:563] <- features #ASSIGN THESE NAMES TO COLUMN NAMES
dataLabels <- colnames(HARframe)[1:563]
#STEP 2:Extracts only the measurements on the mean and standard deviation for each measurement
Mean <- dataLabels[grepl("mean", dataLabels)] #FIND ALL COLUMNS WITH WORD MEAN IN THEM
Std <- dataLabels[grepl("std", dataLabels)] #FIND ALL COLUMNS WITH THE VARIABLE STD IN THEM
meanFrame <- HARframe[,Mean] #SUBSET BY MEAN VARIABLES
stdFrame <- HARframe[,Std] #SUBSET BY STD VARIABLES
labelFrame <- HARframe[,1:2] #SUBSET BY SUBJECT AND ACTIVITY COLUMNS
meanSTD <- cbind(labelFrame, meanFrame, stdFrame) #CREATE DATA FRAME OF ONLY STD AND MEAN VARIABLES WITH SUBJECT AND ACTIVITY LABELS RESTORED
#STEP 3 COMPLETE: Extracts only the measurements on the mean and standard deviation for each measurement.
meanSTD$Activity <- as.character(meanSTD$Activity)
meanSTD$Activity[meanSTD$Activity == "1"] <- "Walking"
meanSTD$Activity[meanSTD$Activity == "2"] <- "WalkingUpstairs"
meanSTD$Activity[meanSTD$Activity == "3"] <- "WalkingDownstairs"
meanSTD$Activity[meanSTD$Activity == "4"] <- "Sitting"
meanSTD$Activity[meanSTD$Activity == "5"] <- "Standing"
meanSTD$Activity[meanSTD$Activity == "6"] <- "Laying"
meanSTD$Activity <- as.factor(meanSTD$Activity)
meanSTD$Subject <- as.factor(meanSTD$Subject)
#CONVERT ACTIVITY COLUMN TO CHARACTER AND ASSIGN DESCRIPTIONS, CONVERT BACK INTO FACTOR.
#CONVERT SUBJECT COLUMN TO FACTOR
#COMPLETE STEP 4:Uses descriptive activity names to name the activities in the data set
#STEP 5: From the data set in step 4, creates a second, independent tidy data set with
# the average of each variable for each activity and each subject.
library(reshape2) #LOAD RESHAPE2 PACKAGE
meanSTD$Subject_Activity = paste(meanSTD$Subject, meanSTD$Activity, sep = "_") #CREATE NEW COLUMN THAT COMBINES ACTIVITY AND SUBJECT VARIABLES
Variables = as.character(names(meanSTD[, 3:81])) #CREATE CHARACTER VECTOR OF VARIABLE NAMES
melt_frame = melt(meanSTD, id.vars= "Subject_Activity", measure.vars=Variables) #MELT DATA FRAME BY NEW COLUMN Subject_Activity
untidy_final_data = dcast(melt_frame, Subject_Activity ~ variable, mean) #CALCULATE MEAN OF EACH VARIABLE FOR EACH COMBINATION OF SUBJECT AND ACTIVITY
library(tidyr) #LOAD TIDYR PACKAGE TO CLEAN UP FINAL TABLE
variableVector <- names(untidy_final_data[,2:80]) #CREATE CHARACTER VECTOR OF VARIABLE NAMES
tidierData <- gather(untidy_final_data, Subject_Activity) #GATHER AND SEPARATE FRAME BY SUBJECT AND ACTIVITY
tidyData <- separate(data = tidierData, col = Subject_Activity, into = c("Subject", "Activity"))
names(tidyData) <- c("Subject", "Activity", "Variable", "Mean") #CLEAN UP COLUMN NAMES OF FINAL DATASET
write.table(tidyData, file = "~/Data/tidy/tidyData.txt", row.name = FALSE) #SAVE DATASET TO TXT FILE
|
c813aaec3ef0b22c43a32e06dd35b8d08efd41ef | 9d5c605c42f230411e601e552267ea5680ddb7c2 | /figures/plot_usd_jpy.R | 6d930cc1a0eaccbb6d9c386e02aa1238756bb5c8 | [
"CC-BY-4.0"
] | permissive | asclearuc/ndr-2018 | 5d13a5e553714314562a6b9954fac238bf0d463a | 93ffc5323f1279a3e3e0208dd400306f7ef4f308 | refs/heads/master | 2020-03-22T06:24:45.589272 | 2018-06-05T14:51:14 | 2018-06-05T14:51:14 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 510 | r | plot_usd_jpy.R | library("tidyverse")
usd_jpy <- read_csv("usd_jpy.csv")
phi <- (1 + sqrt(5)) / 2
(usd_jpy %>% ggplot(mapping = aes(x = dt, y = price)) +
geom_line() +
geom_vline(xintercept = as.Date("1995-01-17"), lty = 2) +
scale_x_date(date_breaks = "1 month", date_labels = "%b %Y") +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(x = "", y = "USD/JPY")) %>%
ggsave(filename = "usd_jpy.pdf",
width = 5 * phi, height = 5)
|
9fce8547416b955152ca07eb256e8484a3f9b943 | 8f67330a4700bc888d13dd92c62220e20e6b6828 | /R/shapes.r | 8b4b03389589d8780be4f716b645beb7a3d325ac | [] | no_license | cran/clusterSim | cfcc584e368fa9f6d1d86887b0f61cc2f3676b32 | 54764dbd65330165e71fc1af2fadf75942915769 | refs/heads/master | 2023-06-25T15:51:42.061284 | 2023-06-10T17:30:02 | 2023-06-10T17:30:02 | 17,695,119 | 2 | 6 | null | 2015-12-05T19:09:43 | 2014-03-13T04:16:30 | R | UTF-8 | R | false | false | 6,930 | r | shapes.r | .numObjects<-function(numObjects,numClusters){
if(length(numObjects)<numClusters){
numObjects<-rep(numObjects,numClusters)
}
if(length(numObjects)>numClusters){
numObjects<-numObjects[1:numClusters]
}
numObjects
}
.toCsv<-function(file,data,klasy,outputRowNames,outputColNames,csv2){
if(paste(file,"",sep="")!=""){
if(csv2){
write.table(cbind(1:dim(data)[1],klasy,data),file=file,sep=";",dec=",",row.names=outputRowNames,col.names=outputColNames)
}
else{
write.table(cbind(1:dim(data)[1],klasy,data),file=file,row.names=outputRowNames,col.names=outputColNames)
}
}
}
shapes.worms<-function(numObjects=180,shape1x1=-2,shape1x2=2,shape2x1=-0.5,shape2x2=2.5,shape2a=1.5,shape2b=5.5,tol=0.1,outputCsv="", outputCsv2="", outputColNames=TRUE, outputRowNames=TRUE){
f1<-function(x){
x^2
}
f2<-function(x,shape2a,shape2b){
-(x-shape2a)^2+shape2b
}
worm<-function(lo,shape1x1,shape1x2,shape2x1,shape2x2,shape2a,shape2b,tol){
data<-array(0,c(sum(lo),2))
lim<-seq(shape1x1,shape1x2,length.out=lo[1])
for(i in 1:lo[1]){
data[i,1]<-lim[i]+rnorm(1,0,tol)
data[i,2]<-f1(lim[i])+rnorm(1,0,tol)
}
lim<-seq(shape2x1,shape2x2,length.out=lo[2])
for(i in 1:lo[2]){
data[i+lo[1],1]<-lim[i]+rnorm(1,0,tol)
data[i+lo[1],2]<-f2(lim[i],shape2a,shape2b)+rnorm(1,0,tol)
}
data
}
lo<-.numObjects(numObjects,2)
klasy<-c(rep(1,lo[1]),rep(2,lo[2]))
data<-worm(lo,shape1x1,shape1x2,shape2x1,shape2x2,shape2a,shape2b,tol)
.toCsv(outputCsv,data,klasy,outputColNames, outputRowNames,FALSE)
.toCsv(outputCsv2,data,klasy, outputColNames, outputRowNames,TRUE)
list(data=data,clusters=klasy)
}
shapes.circles2<-function(numObjects=180, shape1rFrom=0.75,shape1rTo=0.9,shape2rFrom=0.35,shape2rTo=0.5,outputCsv="", outputCsv2="", outputColNames=TRUE, outputRowNames=TRUE){
lo<-.numObjects(numObjects,2)
t1 <- 2 * pi * runif(lo[1])
t2 <- 2 * pi * runif(lo[2])
y2<-x2<-y1<-x1<-NULL
for(t in t1) x1 <- c(x1,cos(t)*runif(1,shape1rFrom,shape1rTo))
for(t in t1) y1 <- c(y1,sin(t)*runif(1,shape1rFrom,shape1rTo))
X1 <- t(as.matrix(rbind(x1, y1)))
for(t in t2) x2 <- c(x2,cos(t)*runif(1,shape2rFrom,shape2rTo))
for(t in t2) y2 <- c(y2,sin(t)*runif(1,shape2rFrom,shape2rTo))
X2 <- t(as.matrix(rbind(x2, y2)))
data <- as.matrix(rbind(X1, X2))
klasy<-c(rep(1,lo[1]),rep(2,lo[2]))
.toCsv(outputCsv,data,klasy,outputColNames, outputRowNames,FALSE)
.toCsv(outputCsv2,data,klasy, outputColNames, outputRowNames,TRUE)
list(data=data,clusters=klasy)
}
shapes.circles3<-function(numObjects=180,shape1rFrom=0.15,shape1rTo=0.3,shape2rFrom=0.55,shape2rTo=0.7,shape3rFrom=1.15,shape3rTo=1.3,outputCsv="", outputCsv2="", outputColNames=TRUE, outputRowNames=TRUE){
lo<-.numObjects(numObjects,3)
t1 <- 2 * pi * runif(lo[1])
t2 <- 2 * pi * runif(lo[2])
t3 <- 2 * pi * runif(lo[3])
y3<-x3<-y2<-x2<-y1<-x1<-NULL
for(t in t1) x1 <- c(x1,cos(t)*runif(1,shape1rFrom,shape1rTo))
for(t in t1) y1 <- c(y1,sin(t)*runif(1,shape1rFrom,shape1rTo))
X1 <- t(as.matrix(rbind(x1, y1)))
for(t in t2) x2 <- c(x2,cos(t)*runif(1,shape2rFrom,shape2rTo))
for(t in t2) y2 <- c(y2,sin(t)*runif(1,shape2rFrom,shape2rTo))
X2 <- t(as.matrix(rbind(x2, y2)))
for(t in t3) x3 <- c(x3,cos(t)*runif(1,shape3rFrom,shape3rTo))
for(t in t3) y3 <- c(y3,sin(t)*runif(1,shape3rFrom,shape3rTo))
X3 <- t(as.matrix(rbind(x3, y3)))
data <- as.matrix(rbind(X1,X2,X3))
klasy<-c(rep(1,lo[1]),rep(2,lo[2]),rep(3,lo[3]))
.toCsv(outputCsv,data,klasy,outputColNames, outputRowNames,FALSE)
.toCsv(outputCsv2,data,klasy, outputColNames, outputRowNames,TRUE)
list(data=data,clusters=klasy)
}
shapes.bulls.eye<-function(numObjects=180, shape1rFrom=0.75,shape1rTo=0.95,shape2rTo=0.45,outputCsv="", outputCsv2="", outputColNames=TRUE, outputRowNames=TRUE){
shapes.circles2(numObjects, shape1rFrom,shape1rTo,shape2rFrom=0,shape2rTo,outputCsv, outputCsv2, outputColNames,outputRowNames)
}
shapes.two.moon<-function(numObjects=180,shape1a=-0.4,shape2b=1,shape1rFrom=0.8, shape1rTo=1.2,shape2rFrom=0.8, shape2rTo=1.2, outputCsv="", outputCsv2="", outputColNames=TRUE, outputRowNames=TRUE){
lo<-.numObjects(numObjects,2)
x <- matrix(0, nrow=sum(lo), ncol=2)
for(i in 1:sum(lo)){
alpha<-runif(1,0,2*pi)
if(i>lo[1]){
r=runif(1,shape2rFrom,shape2rTo)
}
else{
r=runif(1,shape1rFrom,shape1rTo)
}
x[i,1]<-r*cos(alpha)
x[i,2]<-r*sin(alpha)
if(i<=lo[1]){
x[i,1]=shape1a+abs(x[i,1])
}
else{
x[i,1]=-abs(x[i,1])
x[i,2]=x[i,2]-shape2b
}
}
data<-x
klasy<-c(rep(1,lo[1]),rep(2,lo[2]))
.toCsv(outputCsv,data,klasy,outputColNames, outputRowNames,FALSE)
.toCsv(outputCsv2,data,klasy, outputColNames, outputRowNames,TRUE)
list(data=data,clusters=klasy)
}
shapes.blocks3d<-function(numObjects=180,shapesUnitSize=0.5, shape2coordinateX=1.2,shape2coordinateY=1.2,shape2coordinateZ=1.2, outputCsv="", outputCsv2="", outputColNames=TRUE, outputRowNames=TRUE){
lo<-.numObjects(numObjects,2)
x <- matrix(0, nrow=sum(lo), ncol=3)
for(i in 1:sum(lo)){
t<-sample(1:4,1)
if(t==1){
x[i,1]<-runif(1,0,shapesUnitSize)
x[i,2]<-runif(1,0,shapesUnitSize)
x[i,3]<-runif(1,0,shapesUnitSize)
}
if(t==2){
x[i,1]<-runif(1,0,shapesUnitSize)
x[i,2]<-runif(1,0,shapesUnitSize)
x[i,3]<-runif(1,shapesUnitSize,shapesUnitSize*2)
}
if(t==3){
x[i,1]<-runif(1,0,shapesUnitSize)
x[i,2]<-runif(1,shapesUnitSize,shapesUnitSize*2)
x[i,3]<-runif(1,0,shapesUnitSize)
}
if(t==4){
x[i,1]<-runif(1,shapesUnitSize,shapesUnitSize*2)
x[i,2]<-runif(1,0,shapesUnitSize)
x[i,3]<-runif(1,0,shapesUnitSize)
}
if(i>lo[1]){
x[i,]<-c(shape2coordinateX,shape2coordinateY,shape2coordinateZ)-x[i,]
}
}
data<-x
klasy<-c(rep(1,lo[1]),rep(2,lo[2]))
.toCsv(outputCsv,data,klasy,outputColNames, outputRowNames,FALSE)
.toCsv(outputCsv2,data,klasy, outputColNames, outputRowNames,TRUE)
list(data=data,clusters=klasy)
}
|
1d0fc905215d02a1825c214ebbe970489b9db9ed | 64d5df27325f07af9c602ddf85a81ff4f0aec189 | /R/ref_df.R | bbf1bb8c7f3c0e5d6ff8223186c3500adf2198aa | [] | no_license | cran/stacomiR | 0641860bef2f4b5c05490d06de2c58fe3fe30059 | 981c67ba5d18ee9a5c357192e4ba4f9e864ec039 | refs/heads/master | 2022-07-22T14:11:55.680662 | 2022-07-18T08:20:02 | 2022-07-18T08:20:02 | 95,473,811 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,083 | r | ref_df.R | #' Class 'ref_df'
#'
#' Representation of a fishway, contains description data of all fishways from
#' the database along with the selected fishways (df) (integer)
#' Objects from the Class: Objects can be created by calls of the form
#' \code{new('ref_df', df_selected=integer(), ouvrage=integer(),
#' data=data.frame())}.
#' @param df_selected Object of class \code{'integer'} The identifier of the fishway
#' @param ouvrage Object of class \code{'integer'} The attached dam
#' @param data Object of class \code{'data.frame'} Data concerning the fishway
#' @author cedric.briand@eptb-vilaine.fr
#' @family referential objects
setClass(Class = "ref_df", representation = representation(df_selected = "integer",
ouvrage = "integer", data = "data.frame"))
setValidity("ref_df", method = function(object) {
if (length(object@df_selected) != 0) {
if (nrow(object@data) > 0) {
concord <- object@df_selected %in% object@data$df
if (any(!concord)) {
return(paste("No data for DF", object@df_selected[!concord]))
} else {
return(TRUE)
}
} else {
return("You tried to set a value for df_selected without initializing the data slot")
}
} else return(TRUE)
})
#' Loading method for DF referential objects
#' @param object An object of class \link{ref_df-class}
#' @return An object of class ref_df with df loaded
#' @author Cedric Briand \email{cedric.briand@eptb-vilaine.fr}
#' @examples
#' \dontrun{
#' object=new('ref_df')
#' charge(object)
#' }
setMethod("charge", signature = signature("ref_df"), definition = function(object) {
requete = new("RequeteDB")
requete@sql = paste("select dis_identifiant as DF,", " dis_date_creation,", " dis_date_suppression,",
" dis_commentaires,", " dif_ouv_identifiant,", " ouv_libelle,", " dif_code as DF_code,",
" dif_localisation,", " dif_orientation,", " tdf_libelle as type_DF", " from ",
get_schema(), "tg_dispositif_dis", " JOIN ", get_schema(), "t_dispositiffranchissement_dif ON dif_dis_identifiant=dis_identifiant",
" JOIN ", get_schema(), "tj_dfesttype_dft ON dif_dis_identifiant=dft_df_identifiant",
" JOIN ", get_schema(), "t_ouvrage_ouv on dif_ouv_identifiant=ouv_identifiant",
" JOIN ref.tr_typedf_tdf ON tdf_code=dft_tdf_code", " ORDER BY dis_identifiant;",
sep = "")
requete <- stacomirtools::query(requete)
object@data <- requete@query
return(object)
})
#' Command line interface to choose a fishway
#'
#' the choice_c method is intended to have the same behaviour as choice (which creates a
#' widget in the graphical interface) but from the command line. The parameters for dF are transformed to integer as the ref_df only
#' takes integer in the df slots.
#' DF are third in hierarchy in the stacomi database Station>ouvrage>DF>DC>operation. This class is only used in the
#' report_df class.
#' @param object an object of class \link{ref_df-class}
#' @param df a character vector of df chosen
#' @author Cedric Briand \email{cedric.briand@eptb-vilaine.fr}
#' @return An object of class ref_df with df selected
#' @examples
#' \dontrun{
#' win=gwindow()
#' group=ggroup(container=win,horizontal=FALSE)
#' object=new('ref_df')
#' object<-charge(object)
#' objectreport=new('report_mig_mult')
#' choice_c(object=object,objectreport=objectreport,dc=1)
#' }
setMethod("choice_c", signature = signature("ref_df"), definition = function(object,
df) {
# object<-ref_df
if (inherits(df, "numeric")) {
df <- as.integer(df)
} else if (inherits(df, "character")) {
suppressWarnings(expr = {df <- as.integer(as.numeric(df))})
}
if (any(is.na(df)))
stop("NA values df")
object@df_selected <- df
object@ouvrage = object@data$dif_ouv_identifiant[object@data$df %in% object@df_selected]
validObject(object)
# the method validObject verifies that the df is in the data slot of
# ref_df
assign("ref_df", object, envir = envir_stacomi)
return(object)
})
|
20bb5046f2499d6e123b5589ea492cbf726675a9 | 75440e14f1ecfae3d0f67992ce49a38f77e14d46 | /bin/roxygenize.R | ee616db367b14cf92fa45def85e4b2b4997065ef | [] | no_license | eshilts/glmnetPlots | ec0538db90b2dbe49f4fb173f0aea8506aec1f05 | 640008c143c3acd5d15ca5f437444039d2dd256c | refs/heads/master | 2020-05-30T18:32:52.312121 | 2012-08-08T15:20:16 | 2012-08-08T15:20:16 | 5,343,894 | 2 | 0 | null | null | null | null | UTF-8 | R | false | false | 144 | r | roxygenize.R | #!/usr/bin/env Rscript
system("echo 'roxygenizing the package.'")
library(methods)
library(utils)
library(roxygen2)
roxygenize('.', copy=FALSE)
|
d207ccaaf8123745117cb83664eeb4215f65dda6 | 82206536bb4e70b11bc07ba01000e3fe7484759c | /R/builtTable.R | 601548bc5a0f0d8212c64284f9f593e252a50f86 | [] | no_license | pablorodrig16/summaryFunctions | 68905d0c5c23fa9cbff3da83c88d14c163c1ce38 | 188491ef940042b830d017ba12f1605b55282683 | refs/heads/master | 2023-04-07T19:50:41.923249 | 2023-03-29T19:08:32 | 2023-03-29T19:08:32 | 190,251,633 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 14,586 | r | builtTable.R | #' Creates a summary statistics table of data comparing by group with the appropiated statistical test
#' @title Summary table with statistical tests for groups comparison
#' @param data is a vector with data
#' @param group is a factor vector for grouping
#' @param non.parametric is a logical vector. FALSE allows the function to choose the test according to the distribution. If TRUE, the function uses non parametric tests by default.
#' @export
#' @examples
#' buildTable (mtcars$mpg, mtcars$cyl, non.parametric=FALSE)
buildTable<-function (data, group=1, non.parametric=FALSE){
if (missing(data)){
warning("Data vectors are missing")
}else{
if (any(length (group)!=1 & (table(group)<3 | table(group)>5000))){
warning("Table can not be computed. Data size is outside of range (3-5000 per group).")
return(NA)
}else{
#################Procesamiento de variables de agrupamiento###########
####Identificar variables cuantitativas y cualitativas: escribir el numero de columna####
data<-as.data.frame(data)
var.analizar<-1:length (data)
###convierte variables character a factor########
for (a in 1:length (data)){
if (is.character(data[,a])){
data[,a]<-as.factor(data[,a])
}
}
tabla <-c()
filas<-1
for (k in 1:length (data)){
if (is.numeric(data[,k])||is.integer(data[,k])){
if (length(levels(as.factor(group)))==2)
{
#######variables cuantitatitvas group = 2 levels #####################
if(is.normal(as.numeric(data[,k]),group) & !non.parametric)
{
linea<-c(tapply (as.numeric(data[,k]),group, meanSD),
meanSD (as.numeric(data[,k])),
is.normal(as.numeric(data[,k]),group),
sum (is.na(data[,k])),
p.Ttest(data[,k],group))
tabla<-rbind(tabla,linea)
}
else
{
linea<-c(tapply (as.numeric(data[,k]),group, medianIQR),
medianIQR (as.numeric(data[,k])),
is.normal(as.numeric(data[,k]),group),
sum (is.na(data[,k])),
p.Wilcox(data[,k],group))
tabla<-rbind(tabla,linea)
}
rownames(tabla)[filas]<-names(data[var.analizar[k]])
filas<-filas+1
} else if (length(levels(as.factor(group)))>2)
{
#######variables cuantitatitvas group > 2 levels#####################
if(is.normal(as.numeric(data[,k]),group) & !non.parametric)
{
linea<-c(tapply (as.numeric(data[,k]),group, meanSD),
meanSD (as.numeric(data[,k])),
is.normal(as.numeric(data[,k]),group),
sum (is.na(data[,k])),
p.Anova (data[,k],group))
tabla<-rbind(tabla,linea)
}else
{
linea<-c(tapply (as.numeric(data[,k]),group, medianIQR),
medianIQR (as.numeric(data[,k])),
is.normal(as.numeric(data[,k]),group),
sum (is.na(data[,k])),
p.Kruskal(data[,k],group))
tabla<-rbind(tabla,linea)
}
rownames(tabla)[filas]<-names(data[var.analizar[k]])
filas<-filas+1
} else {
#######variables cuantitatitvas group = 1 o nada levels #####################
if(is.normal(as.numeric(data[,k])) & !non.parametric)
{
linea<-c(meanSD (as.numeric(data[,k])),
is.normal(as.numeric(data[,k])),
sum (is.na(data[,k])))
tabla<-rbind(tabla,linea)
}
else
{
linea<-c(medianIQR (as.numeric(data[,k])),
is.normal(as.numeric(data[,k]),group),
sum (is.na(data[,k])))
tabla<-rbind(tabla,linea)
}
rownames(tabla)[filas]<-names(data[var.analizar[k]])
filas<-filas+1
}
}else{
if (length(levels(as.factor(group)))==2)
{
#######variables cualitatitvas#####################
#####analisis de variables TRUE y FALSE#####
if (is.logical(data[,k])==TRUE)
{
linea<-c(
paste (tapply (na.omit(data[,k]),group[!is.na(data[,k])], sum),
" (",
round(
tapply (na.omit(data[,k]),group[!is.na(data[,k])], sum)*100/
tapply (na.omit(data[,k]), group[!is.na(data[,k])], length)
,2),
"%)", sep=""),
paste (sum (na.omit (data[,k])), " (",
round (
sum (na.omit (data[,k]))*100/length(na.omit(data[,k])),2),
"%)", sep=""),
"no normal",
sum (is.na(data[,k])),
p.Fisher (data[,k],group))
tabla<-rbind(tabla,linea)
rownames(tabla)[filas]<-names(data[var.analizar[k]])
filas<-filas+1
}
#####analisis de variables cualitativas no logical####
else
{
for (l in 1:length (levels(as.factor(data[,k]))))
{
nivel<-levels(as.factor(data[,k]))[l]
linea<-c(
paste (tapply (na.omit(data[,k])==nivel,group[!is.na(data[,k])], sum),
" (",
round(
tapply (na.omit(data[,k])==nivel,group[!is.na(data[,k])], sum)*100/
tapply (na.omit(data[,k]), group[!is.na(data[,k])], length)
,2),
"%)", sep=""),
paste (sum (na.omit (data[,k])==nivel), " (",
round (
sum (na.omit (data[,k])==nivel)*100/length(na.omit(data[,k])),2),
"%)", sep=""),
"no normal",
sum (is.na(data[,k])),
p.Chisq (data[,k],group))
tabla<-rbind(tabla,linea)
rownames(tabla)[filas]<-paste(names(data[var.analizar[k]]),nivel)
filas<-filas+1
}
}
}else if (length(levels(as.factor(group)))>2)
{
#######variables cualitatitvas#####################
#####analisis de variables TRUE y FALSE#####
if (is.logical(data[,k])==TRUE)
{
linea<-c(
paste (tapply (na.omit(data[,k]),group[!is.na(data[,k])], sum),
" (",
round(
tapply (na.omit(data[,k]),group[!is.na(data[,k])], sum)*100/
tapply (na.omit(data[,k]), group[!is.na(data[,k])], length),
2),
"%)", sep=""),
paste (sum (na.omit (data[,k])), " (",
round (
sum (na.omit (data[,k]))*100/length(na.omit(data[,k])),2),
"%)", sep=""),
"no normal",
sum (is.na(data[,k])),
p.Chisq (data[,k],group))
tabla<-rbind(tabla,linea)
rownames(tabla)[filas]<-names(data[var.analizar[k]])
filas<-filas+1
}
#####analisis de variables cualitativas no logical####
else
{
for (l in 1:length(levels(as.factor(data[,k])))){
nivel<-levels(as.factor(data[,k]))[l]
linea<-c(
paste (tapply (na.omit(data[,k])==nivel,group[!is.na(data[,k])], sum),
" (",
round(
tapply (na.omit(data[,k])==nivel,group[!is.na(data[,k])], sum)*100/
tapply (na.omit(data[,k]), group[!is.na(data[,k])], length),
2),
"%)", sep=""),
paste (sum (na.omit (data[,k])==nivel), " (",
round (
sum (na.omit (data[,k])==nivel)*100/length(na.omit(data[,k])),2),
"%)", sep=""),
"no normal",
sum (is.na(data[,k])),
p.Chisq (data[,k],group))
tabla<-rbind(tabla,linea)
rownames(tabla)[filas]<-paste(names(data[var.analizar[k]]),nivel)
filas<-filas+1
}
}
}else{
#######variables cualitatitvas#####################
#####analisis de variables TRUE y FALSE#####
if (is.logical(data[,k])==TRUE)
{
linea<-c(
paste (sum (na.omit (data[,k])), " (",
round (
sum (na.omit (data[,k]))*100/length(na.omit(data[,k])),2),
"%)", sep=""),
"no normal",
sum (is.na(data[,k])))
tabla<-rbind(tabla,linea)
rownames(tabla)[filas]<-names(data[var.analizar[k]])
filas<-filas+1
}
#####analisis de variables cualitativas no logical####
else
{
for (l in 1:length (levels(as.factor(data[,k]))))
{
nivel<-levels(as.factor(data[,k]))[l]
linea<-c(
paste (sum (na.omit (data[,k])==nivel), " (",
round (
sum (na.omit (data[,k])==nivel)*100/length(na.omit(data[,k])),2),
"%)", sep=""),
"no normal",
sum (is.na(data[,k])))
tabla<-rbind(tabla,linea)
rownames(tabla)[filas]<-paste(names(data[var.analizar[k]]),nivel)
filas<-filas+1
}
}
}
}
}
####asigna nombres a las columnas####
l<-length (levels (as.factor(group)))
if (l<2){
colnames(tabla)<-c("Stat","Is normal","Missing")
return (tabla)
}
colnames(tabla)<-c(levels (as.factor(group)),"All","Is normal","Missing","P")
nLine<-character()
for (i in 1:l){
nLine[i]<-paste("(n=",
summary (as.factor(group))[i],
")",
sep="")
}
nLine<-c(nLine,
paste("(n=",
nrow(data),
")",
sep = ""),
"","","")
#for (i in 1:l){
# colnames(tabla)[i]<-paste(colnames(tabla)[i],
# " (n=",
# summary (as.factor(group))[i],
# ")", sep="")
#}
tabla<-rbind(nLine,tabla)
row.names(tabla)[1]<-""
####Devuelve la tabla como resultado de la funcion
return(tabla)
}
}
}
|
19d6c984c12ee741be74ea2ee96830a54d24e1ba | 5d8846b18c132985cdf876ba399ca05d7436b060 | /02_R_Basic/R(20210708).R | b444f3a8ca6d1ce837f2f9cf5603e8c797b6a986 | [] | no_license | kjs34590/MC_data_review | 8b3d5f71e6bebbfc39e5c2f32f2465e9b1f11df8 | c08ca8cde719696ab491334edc3d6201bbcb65bd | refs/heads/master | 2023-08-26T23:18:11.334006 | 2021-10-28T16:22:24 | 2021-10-28T16:22:24 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 7,023 | r | R(20210708).R | # EDA(exploratory Data Analysis)
# 탐색적 데이터 분석 (데이터 전처리 + 시각화 + 통계분석)
# 통계분석 위한 가설 수립
# 데이터 전처리
# 1. 데이터 탐색(조회)
# 2. 결측값 처리
# 3. 이상치 발견하고 처리
# 4. 코딩변경(컬럼명 변경, 파생변수), 데이터 조작
# 5. 탐색적 분석을 위한 시각화
# 가설 검증
######
# 연습
library(ggplot2)
midwest.df <- as.data.frame(midwest)
str(midwest.df)
names(midwest.df)
head(midwest.df)
# 전체인구 -> total 변경
# 아시아인구 -> asian 변경
midwest.df <- rename(midwest.df, total = poptotal)
midwest.df <- rename(midwest.df, asian = popasian)
# total, asian 변수를 이용해서 '전체인구대비 아시아 인구 백분율'
# 파생변수 percasian 만들고
# 히스토그램으로 만들어 도시들이 어떻게 분포하는지 보기
midwest.df <- midwest.df %>%
mutate(percasian = (asian/total)*100)
hist(midwest.df$percasian)
# 3. 아시아 인구 백분율 전체 평균을 구하고 평균을 초과하면 'over',
# 그 외에는 'under'를 부여하는 파생변수 생성
midwest.df <- midwest.df %>%
mutate(asian_mean_ou = ifelse(
percasian > mean(percasian), 'over', 'under'
))
View(midwest.df)
# 4. mean에 대한 빈도를 확인 -> 막대그래프 시각화
table(midwest.df$mean)
barplot(table(midwest.df$asian_mean_ou))
ggplot(midwest.df, aes(x = mean)) +
geom_col(col = 'blue', width = .8, fill = 'blue')
# 5. 전체인구대비 미성년 인구 백분율 추가(percyouth)
midwest.df <- midwest.df %>%
mutate(percyouth = ((total-popadults)/total)*100)
View(midwest.df)
# 6. 미성년 인구 백분율이 가장 높은 상위 5개 지역
mw_percyouth <- midwest.df %>%
arrange(desc(percyouth))
mw_percyouth[1:5,c('PID','county','state','percyouth')]
# 7. 전체 인구 대비 아시안 인구 백분율 ratio_asian 파생변수 추가
# 하위 10개 지역 state
midwest.df %>%
mutate(ratio_asian = (asian/total)*100) %>%
arrange(ratio_asian) %>%
select(state, county, ratio_asian) %>%
head(10)
# 8. 미성년자 등급 변수 추가 (gradeyouth)
# 40% 이상 large, 30~40 middle, 30미만 small. 빈도를 시각화
midwest.df <- midwest.df %>%
mutate(gradeyouth = ifelse(percyouth >= 40, 'large',
ifelse(percyouth >= 30, 'middle', 'small')))
ggplot(midwest.df, aes(gradeyouth)) +
geom_bar()
####
eda.data <- read.csv('C:/R_STUDY/data/service_data_new_data_eda.csv')
str(eda.data)
dim(eda.data)
# resident2, gender2 범주형 변환하고 두 변수의 분포 확인
eda.data$resident2 <- as.factor(eda.data$resident2)
eda.data$gender2 <- as.factor(eda.data$gender2)
str(eda.data)
class(table(eda.data$resident2, eda.data$gender2))
resident.gender.tbl <- table(eda.data$resident2, eda.data$gender2)
barplot(resident.gender.tbl,
legend = row.names(resident.gender.tbl),
col = c('pink', 'skyblue', 'orange', 'yellow', 'green'))
# ggplot 쓰려면 tbl -> df로 변경해야
resident.gender.df <- as.data.frame(resident.gender.tbl)
resident.gender.df
ggplot(resident.gender.df) +
geom_bar(aes(x = Var2 ,y = Freq,fill = Var1),
stat = 'identity',
position = 'dodge')
# job2, age2 범주형 변환하고 분포 확인
eda.data$job2 <- as.factor(eda.data$job2)
eda.data$age2 <- as.factor(eda.data$age2)
class(table(eda.data$job2, eda.data$age2))
job.age.tbl <- table(eda.data$job2, eda.data$age2)
barplot(job.age.tbl,
legend = row.names(job.age.tbl))
job.age.df <- as.data.frame(job.age.tbl)
ggplot(job.age.df) +
geom_bar(aes(x = Var2 ,y = Freq,fill = Var1),
stat = 'identity',
position = 'dodge')
# 직업유형에 따른 나이 비율?
ggplot(data = eda.data,
aes(x=age, fill=job2)) +
geom_bar()
result <- c(10,20,30,40,50) * 10
print(result[4])
# service_data_visualization_seoul_subway
seoul_sub <- read.csv('C:/R_STUDY/data/service_data_visualization_seoul_subway.csv')
head(seoul_sub)
str(seoul_sub)
# x 축을 평균일 승차인원(AVG_ONEDAY)으로 설정하고
# y 축을 각 노선의 운행횟수(RUNNINGTIMES_WEEKDAYS)로 설정하고
# 평균 혼잡도(AVG_CROWDEDNESS)로 산점도를 그려보자
ggplot(seoul_sub,
aes(x = AVG_ONEDAY, y = RUNNINGTIMES_WEEKDAYS)) +
geom_point(aes(col = LINE, size = AVG_CROWDEDNESS))
# x 축 각 노선(LINE)으로 일평균 막대그래프를 만들어보자
ggplot(seoul_sub,
aes(x = LINE, y = AVG_ONEDAY)) +
geom_bar(stat = 'identity')
# 데이터 전처리
dataset <- read.csv(file.choose(), header = T)
str(dataset)
head(dataset)
names(dataset)
# 결측값 확인
table(is.na(dataset))
dataset[!complete.cases(dataset), ]
# 결측값 제거 ( caret 패키지 )
dataset.new <- na.omit(dataset)
table(is.na(dataset.new))
str(dataset.new)
# 평균으로 결측값 대체
price <- dataset$price
ifelse(is.na(dataset$price), mean(dataset$price, na.rm = T), price)
# 통계적 방법으로 처리
price.avg <- mean(dataset$price, na.rm = T)
dataset$type <- rep(1:3, 100)
# type : 1 * 1.5 , 2 * 1.0, 3 * 0.5
# 가변수 priceState
dataset %>% mutate(priceState = ifelse(type==1, type*1.5,
ifelse(type==2, type*1, type*0.5)))
# 이상치
str(dataset)
gender <- dataset$gender
range(gender)
table(gender)
gender.subset <- subset(dataset , gender == 1 | gender == 2)
gender.subset$gender <- as.factor(gender.subset$gender)
str(gender.subset)
# 변수의 유형이 연속형이라면
# 어떻게 이상치를 제거할까요?
seq.price <- dataset$price
length(seq.price)
summary(seq.price)
boxplot(seq.price)
# low whisker : 중앙값 - 1.5 * IQR : 2.2875
# high whisker : 중앙값 + 1.5 * IQR : 8.2125
dataset <- subset(dataset , seq.price >= 2.2875 & seq.price <= 8.2125)
seq.price <- dataset$price
boxplot(dataset)
# age
summary(dataset$age)
na.age <- na.omit(dataset$age)
sum(is.na(na.age))
table(is.na(na.age))
boxplot(na.age , horizontal = F)
# 리코딩
# 데이터의 가독성을 위해서 연속형변수 -> 범주형
dataset$resident
length(dataset$resident)
range(dataset$resident)
# 1 : 서울 , 2 : 부산 , 3: 광주 , 4: 대전 , 5 : 대구
# dataset$resident.new 추가한다면?
dataset$resident.new[dataset$resident == 1] <- '서울'
dataset$resident.new[dataset$resident == 2] <- '부산'
dataset$resident.new[dataset$resident == 3] <- '광주'
dataset$resident.new[dataset$resident == 4] <- '대전'
dataset$resident.new[dataset$resident == 5] <- '대구'
dataset %>% mutate(resident.new = ifelse(resident == 1, '서울',
ifelse(resident == 2, '부산',
ifelse(resident == 3, '광주',
ifelse(resident == 4, '대전', '대구')))))
# NA -> 행정수도인 대전
dataset$resident.new <- ifelse(is.na(dataset$resident.new), '대전' , dataset$resident.new)
dataset$job
|
b4280a2370db9896dbc22079679a9607b99fa0ca | 39d8220db6f690b905d96fd5ec4bf589612f23c4 | /packrat/lib/x86_64-apple-darwin15.6.0/3.4.3/scales/tests/testthat/test-bounds.r | 188f28b9bfe58b6e74a16cb2f5974c5a8f82bd90 | [] | no_license | alecri/kappa | ce398645e2430422d7b8263c10b3fa5d2b368c21 | 40307284fa59bc5469c96f51fa1f9b7069b05bc9 | refs/heads/master | 2021-01-11T19:59:58.977086 | 2018-03-14T10:03:26 | 2018-03-14T10:03:26 | 79,352,378 | 1 | 3 | null | null | null | null | UTF-8 | R | false | false | 2,125 | r | test-bounds.r | context("Bounds")
test_that("rescale_mid returns correct results", {
x <- c(-1, 0, 1)
expect_equal(rescale_mid(x), c(0, 0.5, 1))
expect_equal(rescale_mid(x, mid = -1), c(0.5, 0.75, 1))
expect_equal(rescale_mid(x, mid = 1), c(0, 0.25, 0.5))
expect_equal(rescale_mid(x, mid = 1, to = c(0, 10)), c(0, 2.5, 5))
expect_equal(rescale_mid(x, mid = 1, to = c(8, 10)), c(8, 8.5, 9))
})
test_that("rescale_max returns correct results", {
expect_equal(rescale_max(0), NaN)
expect_equal(rescale_max(1), 1)
expect_equal(rescale_max(.3), 1)
expect_equal(rescale_max(c(4, 5)), c(0.8, 1.0))
expect_equal(rescale_max(c(-3, 0, -1, 2)), c(-1.5, 0, -0.5, 1))
expect_equal(rescale_max(c(-3, 0, -1, 2)), c(-1.5, 0, -0.5, 1))
})
test_that("zero range inputs return mid range", {
expect_that(rescale(0), equals(0.5))
expect_that(rescale(c(0, 0)), equals(c(0.5, 0.5)))
})
test_that("censor and squish ignore infinite values", {
expect_equal(squish(c(1, Inf)), c(1, Inf))
expect_equal(censor(c(1, Inf)), c(1, Inf))
})
test_that("scaling is possible with dates and times", {
dates <- as.Date(c("2010-01-01", "2010-01-03", "2010-01-05", "2010-01-07"))
expect_equal(rescale(dates, from = c(dates[1], dates[4])), seq(0,1,1/3))
expect_equal(rescale_mid(dates, mid = dates[3])[3], 0.5)
dates <- as.POSIXct(c("2010-01-01 01:40:40",
"2010-01-01 03:40:40",
"2010-01-01 05:40:40",
"2010-01-01 07:40:40"))
expect_equal(rescale(dates, from = c(dates[1], dates[4])), seq(0, 1, 1/3))
expect_equal(rescale_mid(dates, mid = dates[3])[3], 0.5)
})
test_that("scaling is possible with integer64 data", {
x <- bit64::as.integer64(2^60) + c(0:3)
expect_equal(
rescale_mid(x, mid = bit64::as.integer64(2^60) + 1),
c(0.25, 0.5, 0.75, 1))
})
test_that("scaling is possible with NULL values", {
expect_null(rescale(NULL))
expect_null(rescale_mid(NULL))
})
test_that("scaling is possible with logical values", {
expect_equal(rescale(c(FALSE, TRUE)), c(0, 1))
expect_equal(rescale_mid(c(FALSE, TRUE), mid = 0.5), c(0, 1))
})
|
e98996060f6384827ab4cbff8d92d09dc53deaf2 | d2922aa04644cb228c0a33488fc8a6f7c4783050 | /R/CohortPercent.R | 89ef7cf14b81b55fc4f92788be0c34882ea8d201 | [] | no_license | caiostat/churnFunc | 76277eb02b75e96732cfa16135fe74709c59fd02 | 0eb3c100b2c027d1d353afef2df46c6a5820dee1 | refs/heads/master | 2020-03-22T05:54:03.704590 | 2018-08-01T14:49:17 | 2018-08-01T14:49:17 | 139,586,240 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 934 | r | CohortPercent.R | #' @title Functions to help reporting churn
#'
#' @description function calculates the churn cohortwise
#'
#' @param c
#'
#' @return A bar graph describing churn patterns, discriminated by c.
#'
#' @examples
#'
#' @export CohortPercent
CohortPercent <- function(df, c, var, cols, cols2){
x <- df %>% mutate(ChurnAlvo = ifelse(MotivoCancelamento %in% c, "Sim", "Não")) %>%
mutate(MesCriacao = as.yearmon(DataCriacao)) %>%
group_by(!!!as_quosure(cols)) %>% dplyr::summarise(n=n()) %>%
group_by(!!!as_quosure(cols2)) %>% mutate(Total = sum(n),Percentual = round((n/Total)*100,1))
ggplot(x, aes(y=Percentual, x=MesCriacao, fill = ChurnAlvo)) +
geom_col() +
facet_grid(reformulate(".",var)) +
theme_few() +
theme(legend.position = "bottom") +
geom_text(data = x %>% filter(ChurnAlvo != "Não"), aes(y= Percentual, x=MesCriacao, label= Percentual)) +
labs(title = paste(c, collapse = " e "))
}
|
8bcd887bf13fcfed1055f15071b96c2cebb420fe | 16f3ef5d42a94be44e73dbfa938476945ea0e954 | /Reconstructions/reproducing survival meta analysis/metaData.R | 712b09475b2e6f7ae4636f8932d659f5e6fb104b | [] | no_license | gabriben/survThief-Validation | 93b57093ccce3e8ea863b99c1036b32cf09c9a24 | f6e7b99459b1f4b75b54685c7665414d9cb2e1a8 | refs/heads/master | 2020-05-30T15:49:05.781925 | 2019-06-03T09:30:30 | 2019-06-03T09:30:30 | 189,829,056 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,130 | r | metaData.R | setwd("/Users/gabrielbenedict/Google_Drive/docs/UNIS/KU Leuven/Courses/Master Thesis/Reconstructions/reproducing survival meta analysis/Reconstructed")
studies <- list.dirs(getwd(), recursive = F, full.names = F)
## each dataset is saved in an object "img" in .RData format.
## loading RData does not allow for reassigning objects to other names, so img is kept all along.
load(paste0(studies[1], "/", studies[1], ".RData"))
d <- cbind(img$survData, study = studies[1])
for(i in studies[-1]){
load(paste0(i, "/", i, ".RData"))
d <- rbind(d, cbind(img$survData, study = i))
}
d <- d[order(d$time),]
d$medAge <- 65 * (d$study == "Benrashid") * (d$stratum == "hybrid") +
55 * (d$study == "Benrashid") * (d$stratum == "open") +
63 * (d$study == "Shrestha") * (d$stratum == "hybrid") +
62 * (d$study == "Shrestha") * (d$stratum == "open") +
63 * (d$study == "Preventza") * (d$stratum == "hybrid") +
68 * (d$study == "Preventza") * (d$stratum == "open") +
74.7 * (d$study == "Yoshitake") * (d$stratum == "hybrid") +
67.8 * (d$study == "Yoshitake") * (d$stratum == "open")
setwd("../")
save(d, file = "meta.RData")
|
89f8a339774b8f136053967a04752a7174294abc | e78d0e86220c20477869ecd67ca6d2030598021f | /man/monday_list_columns.Rd | f7c815cfbe9e98a0fcff846fca8fbbd78cda8a53 | [] | no_license | lynuhs/MondayR | 0774a689a00f708c556bf9095bb40ff336a5b334 | 296f45c44dd131307bc2a9bbb96befef31bc8267 | refs/heads/master | 2023-03-18T11:57:55.572419 | 2021-02-20T11:22:05 | 2021-02-20T11:22:05 | 336,251,131 | 2 | 1 | null | null | null | null | UTF-8 | R | false | true | 391 | rd | monday_list_columns.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/monday_list_columns.R
\name{monday_list_columns}
\alias{monday_list_columns}
\title{A data frame of columns}
\usage{
monday_list_columns(board_id)
}
\arguments{
\item{board_id}{The id of a Monday.com board}
}
\description{
Get the columns of a Monday.com board
}
\examples{
monday_list_columns(board_id = 1234)
}
|
013d7f80488436edcac99ca867cfe1ad87dcd5c6 | cce85d168debacecc97c225c340fda2891772e1b | /3/1.r | 3665613a9aa7f51b92f7b558877bd5bff80bfeb7 | [] | no_license | sisu/uml | e58de0c009e42750f52deba36a712d6e9b452a43 | 61023ce8ec1100be43d68559e92e51f33f8c4922 | refs/heads/master | 2021-01-25T05:23:13.236569 | 2013-03-24T12:02:37 | 2013-03-24T12:02:37 | 7,877,643 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 2,608 | r | 1.r | library('MASS')
n <- 2000
genData <- function(theta, var, center) {
data <- cbind(rnorm(n),rnorm(n))
R <- t(matrix(c(cos(theta), sin(theta), -sin(theta), cos(theta)),2,2)) # Rotation matrix
D <- matrix(c(var[1],0,0,var[2]),2,2)# Dilation matrix
A <- D%*%R # First dilate, then rotate
data = apply(data, 1, "%*%", A)
data = data.frame(data[1,],data[2,])
cm <- t(matrix(center, 2, n))
data + cm
}
dat1 <- genData(1.5, c(.6,.9), c(-2,2))
dat2 <- genData(pi/8, c(1,.1), c(2,2))
prob1 <- 0.5
choises <- rbinom(n, 1, prob1)
chmat <- matrix(choises, n, 2)
dat <- as.matrix(chmat*dat1 + (1-chmat)*dat2)
plotdat <- function() plot(dat, pch=16, cex=1, col='blue', xlim=c(-6,6), ylim=c(0,4))
# X: t*n matrix, t is the number of samples and n the number of dimensions
# m: the desired number of cluster
emCluster <- function(X, m) {
t <- dim(X)[1]
n <- dim(X)[2]
posdef <- function(M) M %*% t(M)
C <- lapply(1:m, function(c) posdef(matrix(rnorm(n*n),n,n)))
mu <- matrix(rnorm(n*m), n,m)
p <- runif(m)
p <- p / sum(p)
# X <- t(X)
calcQ <- function(c,t,invC,constf) exp(-.5 * t(X[t,]-mu[,c]) %*% invC %*% (X[t,]-mu[,c])) * constf
objs <- NULL
prevobj <- -1e100
qn <- NULL
for(i in 1:10) {
# maximization
# invCs <- lapply(1:m, function(c) solve(C[[c]]))
# constfs <- sapply(1:m, function(c) p[c] / sqrt(det(C[[c]])))
q <- sapply(1:m, function(c) sapply(1:t, calcQ, c=c, invC=solve(C[[c]]), constf=p[c]/sqrt(det(C[[c]]))))
# q <- sapply(1:m, function(c) exp(-.5* t(X-mu[,c]) %*% solve(C[[c]]) %*% (X-mu[,c])) * p[c] / sqrt(det(C[[c]])) )
# print(dim( t(X-mu[,1]) %*% C[[1]] %*% (X-mu[,1]) ))
qn <- t(apply(q, 1, function(x) x/sum(x)))
mu <- sapply(1:m, function(c) colSums(qn[,c]*X) / sum(qn[,c]))
C <- lapply(1:m, function(c) Reduce('+', lapply(1:t, function(t) qn[t,c] * (X[t,]-mu[,c]) %*% t(X[t,]-mu[,c]))) / sum(qn[,c]))
p <- colSums(qn) / t
# print(C)
# print(mu)
# print(dim(mu))
# print(length(p))
# expectation
calcObj <- function(c,t,invC,constt) (-.5*t(X[t,]-mu[,c])%*%invC%*%(X[t,]-mu[,c]) + constt) * qn[t,c]
obj <- sum(sapply(1:m, function(c) sapply(1:t, calcObj, c=c, invC=solve(C[[c]]), constt=log(p[c])-.5*log(abs(det(C[[c]])))-log(2*pi)**(n/2))))
# if (obj < prevobj+1e-5) break
if (abs(obj - prevobj) < 1e-5) break
# print(obj)
objs <- c(objs,obj)
}
res <- NULL
res$cov <- C
res$mean <- mu
res$prob <- p
res$obj <- objs
res$map <- apply(qn,1,which.max) - 1
res
}
plotChoises <- function(ch) {
x1 <- dat[ch==0,]
x2 <- dat[ch==1,]
plot(x1, pch=16, cex=1, col='blue', xlim=c(-6,6), ylim=c(0,4))
points(x2, pch=16, cex=1, col='red')
}
|
4cf8bf8b10d568df06b20181cda64a941f9d30ae | ae5805f9864f273b198e62a3e5a11d13f543f325 | /R/fun_expExtract.R | 23f3529b35bcc3b40fe736581564bd66440c3fb2 | [] | no_license | jacintoArias/exreport | a5a457e5fe594fabff2667279844b86aeead0048 | ac61cb5a88a64458ced16b47f28f3b1abc97f0e8 | refs/heads/master | 2021-07-03T13:40:40.524529 | 2021-06-03T10:48:36 | 2021-06-03T10:48:36 | 37,213,723 | 9 | 3 | null | null | null | null | UTF-8 | R | false | false | 2,023 | r | fun_expExtract.R | #' Extract statistically equivalent methods from a multiple comparison test
#'
#' This functions generates a new experiment incluing the methods that obtained
#' an equivalent performance with statisticall significance in the multiple
#' comparison test i.e. those whose hypotheses were not rejected
#'
#' @export
#' @param ph A testMultipleControl test object
#' @return an experiment object
#'
#'
#' @examples
#' # First we create an experiment from the wekaExperiment problem and prepare
#' # it to apply the test:
#' experiment <- expCreate(wekaExperiment, name="test", parameter="fold")
#' experiment <- expReduce(experiment, "fold", mean)
#' experiment <- expInstantiate(experiment, removeUnary=TRUE)
#'
#' # Then we perform a testMultiplePairwise test procedure
#' test <- testMultipleControl(experiment, "trainingTime", "min")
#'
#' expExtract(test)
#'
expExtract <- function(ph){
# Extracts the experiment from a post hoc control test object. It is a subset of the experiment that was used
# by the test, remaining the experiments whose p-value is equal or greater than the alpha used.
#
# Args:
# ph: the testMultipleControl object
#
# Returns:
# a experiment object to be used in the toolbox
# PARAMETER VALIDATION:
# Check if parameters are correct
if (!is.testMultipleControl(ph))
stop(.callErrorMessage("wrongParameterError", "ph", "testMultipleControl"))
e <- ph$experiment
remaining <- ph$names[ph$pvalue>=ph$tags$alpha | is.na(ph$pvalue),]
# As well as in expInstantiate, we mix the parameters and the method (to compare names)
e$data <- e$data[interaction(e$data[,c(e$method,e$parameters)],sep = ",",drop=TRUE) %in% remaining,,drop=FALSE]
#Append this operation in the historic
phDescription <- sprintf("%s post-hoc test with %s p-value adjustment for output %s", ph$tags$scope, ph$tags$method, ph$tags$target)
e$historic <- c(e$historic, list(paste("Subset of experiment based on the results of the", phDescription,sep=" ")))
e
} |
e08d170ce246e95048b7a1cb49a8b948c43ed40a | 73b8d80e4be9df5e6f38bae7bd9643315b4366a9 | /HW06_Week07_Armstrong_DigitRecognition.R | 839be26ac3568dde78242f49bbfe929a12b0a2f5 | [] | no_license | larmstrong/ist707_handwrititen_digit_recognition_1 | a010f73f2f9df537890ee1ab9e1faa3e398a8f2d | c9190380391cbddb0f5fd2e537b8c4ae75737816 | refs/heads/main | 2023-05-06T05:09:40.559384 | 2021-06-05T19:31:35 | 2021-06-05T19:31:35 | 374,196,981 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 20,806 | r | HW06_Week07_Armstrong_DigitRecognition.R |
## title: "HW07 - Digit Recognition"
## author: "Leonard Armstrong"
## date: "2/23/2019"
##-------------------------------------------------------------------------------------------------
## CLEAN START
# Remove any non-default packages
default_packages <- union(getOption("defaultPackages"), "base")
loaded_packages <- .packages()
extra_packages <- setdiff(x = loaded_packages, y = default_packages)
invisible(
sapply(
X = extra_packages,
FUN = function(x) detach(name = paste("package:", x, sep=""), character.only = TRUE)))
# Remove all variables and functions from the global environment
rm(list = ls())
##-------------------------------------------------------------------------------------------------
## LOAD LIBRARIES
##
## This section loads all required libraries.
##
## Library | Purpose
## ------------ | ---------------------------------------------------------------------
## assertthat | Create and manage assertions for ensuring proper states in the code.
## e1071 | Naive Bayes functionality.
## ggplot2 | Graphing and plotting functions.
## gridExtra | Grid layout for graphics.
## here | Working directory utilities.
## rattle | Decision tree graphing functions.
## RColorBrewer | Color palette definitions.
## rpart | Decision tree models.
## scales | ggplot2 axis scaling functions.
## stringi | String management functions.
library(assertthat)
library(e1071)
library(ggplot2)
library(gridExtra)
library(here)
library(rattle)
library(RColorBrewer)
library(rpart)
library(scales)
library(stringi)
##-------------------------------------------------------------------------------------------------
## READ PROVIDED DATA SETS
##
# Set the random seed
set.seed(100163)
# Define observation sizes
image_height <- 28
image_width <- 28
image_size <- image_height * image_width
record_size <- image_size + 1 # Add one for the label field.
# Define the relevant directories, file names, and file paths.
cwd <- here::here()
data_subdir <- "../data"
training_filename <- "Kaggle-digit-train-sample-small-1400.csv"
training_fullfilepath <- file.path(cwd, data_subdir, training_filename)
test_filename <- "Kaggle-digit-test-sample1000.csv"
test_fullfilepath <- file.path(cwd, data_subdir, test_filename)
# Define training data datatypes as numerics.
numeric_coltypes <-
c("factor", # Label field
rep(x = "numeric", times = image_size)) # 28x28 pixel image greyscale byte fields.
# Read the training data.
train_num <- read.csv(
file = training_fullfilepath, header = TRUE, colClasses = numeric_coltypes, na.strings = "")
pixel_min <- min(train_num[, -1])
pixel_max <- max(train_num[, -1])
cat("The minumim training data value is", pixel_min, "\n")
cat("The maximum training data value is", pixel_max, "\n")
# Create a factorized training data set.
pixel_levels <- as.character(pixel_min:pixel_max)
pixel_fac <- data.frame(lapply(
X = train_num[, -1],
FUN = function(x) factor(x = x, levels = pixel_levels, labels = pixel_levels)))
train_fac <- data.frame(label = train_num$label, pixel_fac)
# Define number of folds for k-folds testing and the size of a fold.
k_folds <- 10
fold_size <- round(nrow(train_num)/k_folds)
# Read the test data.
test_data <- read.csv(
file = test_fullfilepath, header = TRUE, colClasses = numeric_coltypes, na.strings = "")
binary_test_data <- data.frame(label = test_data$label, sign(test_data[, -1] > 32))
binary_fac <- data.frame(lapply(
X = binary_test_data[, -1],
FUN = function(x) factor(x = x, levels = c("0", "1"), labels = c("0", "1"))))
test_binfac <- data.frame(label = rep("0", times = 1000), binary_fac)
digit_labels <- c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
test_binfac$label <- factor(x = test_binfac$label, labels = digit_labels, levels = digit_labels)
# Remove unneeded data
rm(cwd, data_subdir, test_filename, test_fullfilepath, training_filename, training_fullfilepath)
rm(pixel_fac, pixel_levels)
rm(numeric_coltypes)
##-------------------------------------------------------------------------------------------------
## REVIEW AND CLEAN (IF NEEDED) PROVIDED DATA SETS
##
## In this section, the data sets will be reviewed for "cleanliness" and cleaned if needed.
# Review NAs in the data
cat("There are NAs in the numeric training data:", any(is.na(train_num)), "\n")
cat("There are NAs in the factor training data:", any(is.na(train_fac)), "\n")
##-------------------------------------------------------------------------------------------------
## EXPLORATORY DATA ANALYSIS - DATA SUMMARIES
##
## This section, consists of numeric exploratory analysis of the data.
# Show basic statistic summary of the training data.
cat("Summary of the training data:\n", sep="")
summary(as.numeric(train_num$label))
cat("Standard deviation of the training data: ", sd(as.numeric(train_num$label)), "\n", sep="")
# Review the means and standard deviations of each pixel and determine which pixels have zeros
# for all training cases.
all_means <- apply(X=train_num[, -1], MARGIN = 2, FUN = mean)
all_sds <- apply(X=train_num[, -1], MARGIN = 2, FUN = sd)
all_zeros <- all_means[all_means == 0]
cat(NROW(all_zeros), " pixels have zeros for every record.\n", sep="")
# Remove unnecessary data
rm (all_means, all_sds, all_zeros)
##-------------------------------------------------------------------------------------------------
## EXPLORATORY DATA ANALYSIS - DATA VISUALIZATIONS
##
## This section, consists of visual exploratory analysis of the data.
# Create a support dataframe of labels, label counts and label percentages
lcount <- table(train_num$label)
lpct <- c(lcount/sum(lcount), use.names = FALSE)
pctlab <- sprintf("%5.2f%%", lpct*100)
pct_df <- data.frame(
name = rownames(lcount),
count = lcount,
pct = lpct, label = pctlab,
use.name = FALSE)
# Plot a bar chart of percentage used for each digit from the pct_df source.
ghisto <- ggplot(data <- pct_df, mapping = aes(x = name, y = pct, label = label)) +
geom_col(fill = "goldenrod") +
geom_text(vjust = 2) +
scale_y_continuous(name = "Percentage", labels = percent) +
labs(
title = "Distribution of Digit Representations Across 1400 Samples",
x = "Handwritten Digit",
fill = "Digit")
# Display the plot.
ghisto
##-------------------------------------------------------------------------------------------------
## VISUAL EDA
#' create_spread_plot - Generate a dot plot of the distribution of each digit across the input
#' data set.
#'
#' @param x Input data set assumed to have a field named "label"
#' @param subtitle Subtitle for the plot to be returned.
#'
#' @return A dot plot of the digit distributions in the input data frame.
#' @export
#'
#' @examples create_spread_plot(train_num, "Original distribution")
create_spread_plot <- function (x, subtitle) {
# Create a helper dataframe consisting of the data index (row) as an integer and the
# data value (digit label) as a character string.
spread_df <- data.frame(
index = as.integer(1:nrow(x)),
value = as.character(x[, "label"]),
stringsAsFactors = FALSE)
# Create a dotplot from the spread_df helper dataframe.
gdot <- ggplot(data = spread_df, mapping = aes(x = value, y = index)) +
geom_point(size = 1) +
scale_y_continuous(name = "Observation", breaks = seq(from = 0, to = nrow(x), by = 100)) +
labs(
title = "Spread of Each Digit Across All Observations",
subtitle = subtitle,
x = "Digit")
# Return the generated dotplot
return(gdot)
}
# Plot the distribution of the original data.
gdot_original <- create_spread_plot(train_num, "Original distribution")
gdot_original
# Now try shuffling and replotting
train_num_shuffle1 <- train_num[sample(nrow(train_num)), ]
gdot_shuffle1 <- create_spread_plot(train_num_shuffle1, "Suffled Distribution #1")
gdot_shuffle1
# Shuffle and replot one more time.
train_num_shuffle2 <- train_num_shuffle1[sample(nrow(train_num_shuffle1)), ]
gdot_shuffle2 <- create_spread_plot(train_num_shuffle2, "Suffled Distribution #2")
gdot_shuffle2
# Create a 1x2 grid display of the two shuffled plots.
grid.arrange(gdot_shuffle1, gdot_shuffle2, nrow = 1)
# Keep the first shuffle to be used in the first analysis
train1 <- train_num_shuffle1
# Create a factorized training data set with the same shuffle as train1.
pixel_levels <- as.character(pixel_min:pixel_max)
pixel_fac <- data.frame(lapply(
X = train1[, -1],
FUN = function(x) factor(x = x, levels = pixel_levels, labels = pixel_levels)))
train_fac <- data.frame(label = train1$label, pixel_fac)
rm (train_num_shuffle1, train_num_shuffle2)
rm(pixel_levels, pixel_fac)
##-------------------------------------------------------------------------------------------------
#' display_image - Display a digitized version of the hand-drawn image from a single observation.
#'
#' @param x Image record consisting of a label field and 784 pixel fields.
#' This function requires that the pixel fields are numerics.
#'
#' @return A ggplot of the digitized image.
#' @export
#'
#' @examples display_image(train_num[123,])
display_image <- function (x) {
# Define error messages
emsg_recordlen <- "Incorrect record length sent to display_image. Expected 785 values."
emsg_vartype <- "Incorrect data types sent to display_image. Numeric pixel values expected."
# Verify that a record of the proper length was input
assert_that(ncol(x) == 785, msg = emsg_recordlen)
# Verify that the pixel fields are all numeric.
assert_that(all(apply(X = x[, -1], MARGIN = 2, FUN=is.number)), msg = emsg_vartype)
rownums <- as.vector(sapply(X=c(1:28), FUN= function(x) rep(x, times=28)))
colnums <- rep(c(1:28), times = 28)
df <- data.frame(drow = rownums, dcol = colnums, ddat = unlist(x[2:785]), row.names = NULL)
g <- ggplot(data = df, mapping = aes(x = dcol, y = -drow, fill = ddat)) +
geom_tile() +
scale_fill_continuous(low = "white", high = "black") +
coord_fixed(ratio = 4/3) +
theme(
legend.position = "none",
axis.text.x=element_blank(), axis.ticks.x=element_blank(),
axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
labs(x = paste("Value = ", x$label, sep=""))
return(g)
}
# Create a list of n random images.
ilist <- list()
num_images <- 28
sample_value <- round(runif(n = num_images, min=1, max = 1400))
for (i in 1:num_images) {
# Create an image graphic
ilist[[i]] <- display_image(train_num[sample_value[i],])
}
# Display all created images in a grid.
g <- grid.arrange(
ilist[[1]], ilist[[2]], ilist[[3]], ilist[[4]],
ilist[[5]], ilist[[6]], ilist[[7]], ilist[[8]],
ilist[[9]], ilist[[10]], ilist[[11]], ilist[[12]],
ilist[[13]], ilist[[14]], ilist[[15]], ilist[[16]],
ilist[[17]], ilist[[18]], ilist[[19]], ilist[[20]],
ilist[[21]], ilist[[22]], ilist[[23]], ilist[[24]],
ilist[[25]], ilist[[26]], ilist[[27]], ilist[[28]],
nrow = 4)
# Plot a barchart from a run's results.
# df: Input data frame of run result data
# st: Subtitle to be used on the plot.
barchart_results <- function (df, st) {
# Plot a bar chart of percentage used for each digit from the pct_df source.
the_plot <- ggplot(data = df, mapping = aes(x = label)) +
stat_count(mapping = aes(fill = pred)) +
scale_fill_brewer(palette = "Spectral") +
labs(
title = "Results of Final Fold Testing",
subtitle = st,
x = "Digit",
y = "Count",
fill = "Predicted Digit")
# Display the plot.
return(the_plot)
}
##-------------------------------------------------------------------------------------------------
## ANALYSIS #1 - NAIVE BAYES WITH NUMERIC PIXEL VALUES
##
## Run an Naive Bayes analysis using numeric pixel values.
cat("Analysis #1: Pixel data as numbers.\n")
pctcorrect_total1 <- 0
for (i in 1:k_folds) {
# Define the range of indices to be held out for cross-validation
holdout_range1 <- c(floor(fold_size * (i - 1) + 1):floor(fold_size * i))
train_range1 <- setdiff(1:nrow(train1), holdout_range1)
nbmodel1 <- naiveBayes(
formula = formula("label ~ ."),
data = train1,
laplace = 1,
na.action = na.fail,
subset = train_range1)
pred1 <- predict(nbmodel1, newdata = train1[holdout_range1, ], type=c("class"))
testcols1 <- train1[holdout_range1, "label"]
verify1 <- cbind(label = testcols1, pred = pred1)
ncorrect1 <- sum(verify1[, "label"] == verify1[, "pred"])
pctcorrect1 <- ncorrect1/nrow(verify1)
pctcorrect_total1 <- pctcorrect_total1 + pctcorrect1
cat("Test ", i, ": Predicted ", pctcorrect1, "\n", sep="")
}
cat("Overall: ", pctcorrect_total1/k_folds, " percent correctly predicted.\n", sep="")
verify1_df <- data.frame(label = factor(verify1[, "label"]-1), pred = factor(verify1[, "pred"]-1))
bc1 <- barchart_results(as.data.frame(verify1_df), st = "Analysis #1: Pixel values as numerics")
bc1
rm(holdout_range1, train_range1, nbmodel1, pred1)
rm(pctcorrect_total1, pctcorrect1, ncorrect1, testcols1)
##-------------------------------------------------------------------------------------------------
## ANALYSIS #2 - NAIVE BAYES WITH FACTOR PIXEL VALUES
##
## Run an Naive Bayes analysis using factor pixel values.
cat("Analysis #2: Pixel data as factors.\n")
pctcorrect_total2 <- 0
train2 <- train_fac
for (i in 1:k_folds)
{
# Define the range of indices to be held out for cross-validation
holdout_range2 <- c(floor(fold_size * (i - 1) + 1):floor(fold_size * i))
train_range2 <- setdiff(1:nrow(train2), holdout_range2)
nbmodel2 <- naiveBayes(
formula = formula("label ~ ."),
data = train2,
laplace = 1,
na.action = na.fail,
subset = train_range2)
pred2 <- predict(nbmodel2, newdata = train2[holdout_range2, ], type=c("class"))
testcols2 <- train2[holdout_range2, "label"]
verify2 <- cbind(label = testcols2, pred = pred2)
ncorrect2 <- sum(verify2[, "label"] == verify2[, "pred"])
pctcorrect2 <- ncorrect2/nrow(verify2)
pctcorrect_total2 <- pctcorrect_total2 + pctcorrect2
cat("Test ", i, ": Predicted ", round(pctcorrect2 * 100, digits = 1), "%\n", sep="")
}
cat("Overall: ", pctcorrect_total2/k_folds, " percent correctly predicted.\n", sep="")
verify2_df <- data.frame(label = factor(verify2[, "label"]-1), pred = factor(verify2[, "pred"]-1))
bc2 <- barchart_results(as.data.frame(verify2_df), st = "Analysis #2: Pixel values as factors")
bc2
rm(holdout_range2, train_range2, nbmodel2, pred2)
rm(pctcorrect_total2, pctcorrect2, ncorrect2, testcols2)
##-------------------------------------------------------------------------------------------------
## ANALYSIS #3 - NAIVE BAYES WITH BINARY NUMERIC PIXEL VALUES
##
## Run an Naive Bayes analysis using factor pixel values.
cat("Analysis #3: Pixel data as binary numbers.\n")
pctcorrect_total3 <- 0
# train3 <- data.frame(label = train1$label, sign(train1[, -1]))
train3 <- data.frame(label = train1$label, sign(train1[, -1] > 32))
for (i in 1:k_folds)
{
# Define the range of indices to be held out for cross-validation
holdout_range3 <- c(floor(fold_size * (i - 1) + 1):floor(fold_size * i))
train_range3 <- setdiff(1:nrow(train3), holdout_range3)
nbmodel3 <- naiveBayes(
formula = formula("label ~ ."),
data = train3,
laplace = 1,
na.action = na.fail,
subset = train_range3)
pred3 <- predict(nbmodel3, newdata = train3[holdout_range3, ], type=c("class"))
testcols3 <- train3[holdout_range3, "label"]
verify3 <- cbind(label = testcols3, pred = pred3)
ncorrect3 <- sum(verify3[, "label"] == verify3[, "pred"])
pctcorrect3 <- ncorrect3/nrow(verify3)
pctcorrect_total3 <- pctcorrect_total3 + pctcorrect3
cat("Test ", i, ": Predicted ", round(pctcorrect3*100, digits = 1), "%\n", sep="")
}
cat(
"Overall: ",
round((pctcorrect_total3/k_folds) * 100, digits = 1),
" percent correctly predicted.\n", sep="")
verify3_df <- data.frame(label = factor(verify3[, "label"]-1), pred = factor(verify3[, "pred"]-1))
bc3 <- barchart_results(as.data.frame(verify3_df), st = "Analysis #3: Pixel values as binary numbers")
bc3
rm(holdout_range3, train_range3, nbmodel3, pred3)
rm(pctcorrect_total3, pctcorrect3, ncorrect3, testcols3)
##-------------------------------------------------------------------------------------------------
## ANALYSIS #4 - NAIVE BAYES WITH BINARY FACTOR PIXEL VALUES
##
## Run an Naive Bayes analysis using binary factor pixel values.
cat("Analysis #4: Pixel data as binary factors\n")
pctcorrect_total4 <- 0
# Create the binary factor data set.
pixel_bfac <- data.frame(lapply(
X = train3[, -1],
FUN = function(x) factor(x = x, levels = c("0", "1"), labels = c("0", "1"))))
train4 <- data.frame(label = train3$label, pixel_bfac)
for (i in 1:k_folds)
{
# Define the range of indices to be held out for cross-validation
holdout_range4 <- c(floor(fold_size * (i - 1) + 1):floor(fold_size * i))
train_range4 <- setdiff(1:nrow(train4), holdout_range4)
nbmodel4 <- naiveBayes(
formula = formula("label ~ ."),
data = train4,
laplace = 1,
na.action = na.fail,
subset = train_range4)
pred4 <- predict(nbmodel4, newdata = train4[holdout_range4, ], type=c("class"))
testcols4 <- train4[holdout_range4, "label"]
verify4 <- cbind(label = testcols4, pred = pred4)
ncorrect4 <- sum(verify4[, "label"] == verify4[, "pred"])
pctcorrect4 <- ncorrect4/nrow(verify4)
pctcorrect_total4 <- pctcorrect_total4 + pctcorrect4
cat("Test ", i, ": Predicted ", round(pctcorrect4 * 100, digits = 1), "%\n", sep="")
}
cat(
"Overall: ",
round((pctcorrect_total4/k_folds) * 100, digits = 1),
"% percent correctly predicted.\n",
sep="")
verify4_df <- data.frame(label = factor(verify4[, "label"]-1), pred = factor(verify4[, "pred"]-1))
bc4 <- barchart_results(as.data.frame(verify4_df), st="Analysis #4: Pixel values as binary factors")
bc4
rm(holdout_range4, train_range4, nbmodel4, pred4)
rm(pctcorrect_total4, pctcorrect4, ncorrect4, testcols4)
##-------------------------------------------------------------------------------------------------
## ANALYSIS #5 - NAIVE BAYES WITH BINARY FACTOR PIXEL VALUES
##
## Run a decision tree analysis using binary factor pixel values.
cat("Analysis #5: Decision trees using pixel data as binary factors\n")
# Reset the % correct accumulator
pctcorrect_total5 <- 0
# Initialized the training data set
train5 <- train4
# Loop across all k-folds...
for (i in 1:k_folds) {
# Define the range of indices to be held out for cross-validation
holdout_range5 <- c(floor(fold_size * (i - 1) + 1):floor(fold_size * i))
train_range5 <- setdiff(1:nrow(train5), holdout_range5)
dttrain5 <- train5[train_range5, ]
dttest5 <- train5[holdout_range5, ]
dt5 <- rpart(formula = label ~ ., data = dttrain5, method = "class")
bplot5 <- fancyRpartPlot(dt5)
bplot5
pred5 <- predict(dt5, newdata = dttest5, type=c("class"))
testcols5 <- dttest5[ , "label"]
verify5 <- cbind(label = testcols5, pred = pred5)
ncorrect5 <- sum(verify5[, "label"] == verify5[, "pred"])
pctcorrect5 <- ncorrect5/nrow(verify5)
pctcorrect_total5 <- pctcorrect_total5 + pctcorrect5
cat("Test ", i, ": Predicted ", round(pctcorrect5 * 100, digits = 1), "\n", sep="")
}
cat(
"Overall: ",
round((pctcorrect_total5/k_folds) * 100, digits = 1),
" percent correctly predicted.\n",
sep = "")
verify5_df <- data.frame(label = factor(verify5[, "label"]-1), pred = factor(verify5[, "pred"]-1))
bc5 <- barchart_results(
verify5_df,
st = "Analysis #5: Decision tree analysis with pixel values as binary factors")
bc5
rm(holdout_range5, train_range5, pred5)
rm(pctcorrect_total5, pctcorrect5, ncorrect5, testcols5)
##-------------------------------------------------------------------------------------------------
## FINALE - RUN THE WINNING ALGORITHM ACROSS THE PROVIDED TEST DATA
##
## Run an Naive Bayes analysis using binary factor pixel values on the test data.
cat("FINALE: Pixel data as binary factors on supplied test data\n")
# Create the binary factor data set.
train_final <- train4
nbmodel_finale <- naiveBayes(
formula = formula("label ~ ."), data = train_final, laplace = 1, na.action = na.fail)
pred_finale <- predict(nbmodel_finale, newdata = test_binfac, type=c("class"))
finale_df <- data.frame(digit = as.numeric(pred_finale)-1, stringsAsFactors = FALSE)
ghisto_finale <- ggplot(data <- finale_df, mapping = aes(x = digit)) +
geom_histogram(bins = 10, color="white", fill = "goldenrod") +
scale_x_continuous(name = "Digit Predicted", breaks = seq(from = 0, to = 9, by = 1)) +
labs(
title = "Prediction Volumes for the 1000-element Test Data Set",
y = "Prediction Volume")
ghisto_finale
|
ebd5745fd235a2bfda72f038b92dfcba668360e0 | 72d03ec10b4955bcc7daac5f820f63f3e5ed7e75 | /input/gcam-data-system/aglu-processing-code/level1/LA100.0_LDS_preprocessing.R | c353d2f4be4cf4299bd636d1624cbc313c0905bc | [
"ECL-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bgmishra/gcam-core | 54daddc3d037571bf745c4cf0d54c0d7a77f493f | bbfb78aeb0cde4d75f307fc3967526d70157c2f8 | refs/heads/master | 2022-04-17T11:18:25.911460 | 2020-03-17T18:03:21 | 2020-03-17T18:03:21 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,227 | r | LA100.0_LDS_preprocessing.R | # Before we can load headers we need some paths defined. They
# may be provided by a system environment variable or just
# having already been set in the workspace
if( !exists( "AGLUPROC_DIR" ) ){
if( Sys.getenv( "AGLUPROC" ) != "" ){
AGLUPROC_DIR <- Sys.getenv( "AGLUPROC" )
} else {
stop("Could not determine location of aglu data system. Please set the R var AGLUPROC_DIR to the appropriate location")
}
}
# Universal header file - provides logging, file support, etc.
source(paste(AGLUPROC_DIR,"/../_common/headers/GCAM_header.R",sep=""))
source(paste(AGLUPROC_DIR,"/../_common/headers/AGLU_header.R",sep=""))
logstart( "LA100.0_LDS_preprocessing.R" )
adddep(paste(AGLUPROC_DIR,"/../_common/headers/GCAM_header.R",sep=""))
adddep(paste(AGLUPROC_DIR,"/../_common/headers/AGLU_header.R",sep=""))
printlog( "Re-setting column names of LDS output data files for consistency with GCAM data processing system" )
# -----------------------------------------------------------------------------
# 1. Read files
sourcedata( "COMMON_ASSUMPTIONS", "A_common_data", extension = ".R" )
sourcedata( "AGLU_ASSUMPTIONS", "A_aglu_data", extension = ".R" )
LDSfilepath <- readdomainpathmap()["AGLU_LDS_DATA"][[1]]
LDSfiles.list <- list.files( LDSfilepath )
LDSfiles.list <- sub( ".csv", "", LDSfiles.list )
LDSfiles <- list()
for( i in LDSfiles.list ){
index <- which( LDSfiles.list == i )
LDSfiles[[ index ]] <- readdata( "AGLU_LDS_DATA", i)
}
names( LDSfiles ) <- LDSfiles.list
# -----------------------------------------------------------------------------
# Change names
for( i in 1:length( LDSfiles ) ){
names( LDSfiles[[i]] ) <- sub( "ctry_iso", "iso", names( LDSfiles[[i]] ) )
names( LDSfiles[[i]] ) <- sub( "reglr_iso", "GTAP_region", names( LDSfiles[[i]] ) )
names( LDSfiles[[i]] ) <- sub( "glu_code", GLU, names( LDSfiles[[i]] ) )
names( LDSfiles[[i]] ) <- sub( "land_type", "land_code", names( LDSfiles[[i]] ) )
names( LDSfiles[[i]] ) <- sub( "SAGE_crop", "GTAP_crop", names( LDSfiles[[i]] ) )
names( LDSfiles[[i]] ) <- sub( "mirca_crop", "MIRCA_crop", names( LDSfiles[[i]] ) )
names( LDSfiles[[i]] ) <- sub( "use_sector", "GTAP_use", names( LDSfiles[[i]] ) )
#Replace numerical GLU code with concatenated GLU and the 3-digit code
if( GLU %in% names( LDSfiles[[i]] ) ){
LDSfiles[[i]][[GLU]] <- paste( GLU, sprintf( "%03d", LDSfiles[[i]][[GLU]] ), sep = GLU_name_delimiter )
}
#Need to re-set Taiwan to mainland China, as the current version of AgLU (and pre-2015 versions of FAOSTAT) doesn't disaggregate Taiwan
if( "iso" %in% names( LDSfiles[[i]] ) ){
if( names( LDSfiles )[i] != "Pot_veg_carbon_Mg_per_ha" ){
LDSfiles[[i]][["iso"]][ LDSfiles[[i]][["iso"]] == "twn" ] <- "chn"
agg.vectors <- names( LDSfiles[[i]] )[ names( LDSfiles[[i]] ) != "value" ]
LDSfiles[[i]] <- aggregate( LDSfiles[[i]][ "value" ],
by = LDSfiles[[i]][ agg.vectors ], sum )
}
#Drop Taiwan from the carbon contents
if( names( LDSfiles )[i] == "Pot_veg_carbon_Mg_per_ha" ){
LDSfiles[[i]] <- subset( LDSfiles[[i]], iso != "twn" )
}
}
}
#Next, the production and harvested area tables have values <1 clipped, resulting in some country/glu/crops present in one but not the other
# For now these will simply be dropped; in the future, we may want to add a digit of rounding in the lds
LDSfiles[["LDS_ag_HA_ha"]] <- LDSfiles[["LDS_ag_HA_ha"]][
vecpaste( LDSfiles[["LDS_ag_HA_ha"]][ c( "iso", GLU, "GTAP_crop" ) ] ) %in%
vecpaste( LDSfiles[["LDS_ag_prod_t"]][ c( "iso", GLU, "GTAP_crop" ) ] ), ]
LDSfiles[["LDS_ag_prod_t"]] <- LDSfiles[["LDS_ag_prod_t"]][
vecpaste( LDSfiles[["LDS_ag_prod_t"]][ c( "iso", GLU, "GTAP_crop" ) ] ) %in%
vecpaste( LDSfiles[["LDS_ag_HA_ha"]][ c( "iso", GLU, "GTAP_crop" ) ] ), ]
# -----------------------------------------------------------------------------
# 3. Output
#write tables as CSV files
for( i in 1:length( LDSfiles ) ){
objectname <- paste0( "L100.", names( LDSfiles )[i] )
object <- LDSfiles[[i]]
assign( objectname, c )
writedata( object,domain="AGLU_LEVEL1_DATA",fn=objectname )
}
# Every script should finish with this line
logstop()
|
39852fec1b7cc75a2f292266055863926252b654 | 8be8fe5e1a4ef5642640dff5b392f440303fe8d0 | /Workflow_Code/older_code/valid_iterative_taxa.R | 10ed497d7852d7dd64f17b093eb99d6e8865c47f | [
"MIT"
] | permissive | PalEON-Project/ReFAB | 63eb7a645f02a37069a566e771fdb3fba115d167 | 335d098c42dc2232b4b2e4bc93e263a9393daca2 | refs/heads/master | 2022-04-30T18:58:09.983560 | 2022-04-20T15:55:32 | 2022-04-20T15:55:32 | 87,744,726 | 4 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,673 | r | valid_iterative_taxa.R |
######## run on geo with job.array.taxa.sh
arg <- commandArgs(trailingOnly = TRUE)
if (is.na(arg[1])) {
runnum <- NA
} else {
group_rm <- as.numeric(arg[1])
}
library(nimble)
library(splines)
library(maps)
library(methods)
ciEnvelope <- function(x,ylo,yhi,...){
polygon(cbind(c(x, rev(x), x[1]), c(ylo, rev(yhi),
ylo[1])), border = NA,...)
}
load("twothirds_v2.0.Rdata") #for calibration
load('threethirds_v2.0.Rdata') #for validation
source(file.path('Workflow_Code','utils','validation_args.R')) #file with constants that should be constant between validation exercises
#### Setting up taxa removal
Y.keep <- Y
biomass.keep <- biomass
Y.calib <- Y.pred <- Y[,-group_rm]
biomass.calib <- biomass.pred <- biomass
source("Workflow_Code/utils/bs_nimble.R")
Z.test <- matrix(NA,length(biomass.calib),5)
for(i in 1:length(biomass.calib)){
Z.test[i,] <- bs_nimble(u_given = biomass.calib[i], u = u, N0 = rep(0, (length(u)-1)), N1 = rep(0, (length(u))),
N2 = rep(0, (length(u)+1)), N3 = rep(0, (length(u)+2)))
}
Z.knots <- Z.test
source(file.path('Workflow_Code','models','calibration.model.R'))
if(FALSE){
samples.mixed <- calibration_model(Y = Y.calib, biomass = biomass.calib,
Z.knots = Z.knots, u = u, Niters = Niters,
group_rm = group_rm)
}
load(file = paste0("beta.est.group.in", group_rm, ".Rdata"))
burnin <- round(.2 * nrow(samples.mixed))
new.biomass <- 1:bMax
Z.new = matrix(0,nrow=length(new.biomass),ncol=ncol(Z.knots))
for(i in 1:length(new.biomass)){
u_given <- new.biomass[i]
Z.new[i,] = bs_nimble(u_given, u=u, N0 = rep(0, (length(u)-1)),
N1 = rep(0, (length(u))),
N2 = rep(0, (length(u)+1)),
N3 = rep(0, (length(u)+2)))
}
source(file.path('Workflow_Code','utils','getLik.R'))
outLik <- getLik(Z = Z.new, u = u, beta = (samples.mixed[nrow(samples.mixed),]),
bMax = bMax, Y = Y.calib, knots = length(u) + 2)
source(file.path('Workflow_Code','models','validation.R'))
samples.pred <- validation_model(Y = Y.pred, Z.knots = Z.knots,
samples.mixed = samples.mixed, u = u,
Niters = Niters, bMax = bMax, group_rm = group_rm,
outLik = outLik)
if(FALSE){ ### To plot use the following after running on the server
samps.mat <- array(NA, dim = c(5000,232,22))
r.saved <- r.saved.23 <- numeric(22)
load('threethirds_v2.0.Rdata') #for validation
load('one.third.idx.Rdata')
for(i in 1:22){
load(paste0('~/Downloads/iter.samps/samples.pred.group',i,'betaNA.Rdata'))
samps.mat[,,i] <- samples.pred
}
pdf(paste0('iterative.taxa.sens',Sys.Date(),'.pdf'))
par(mfrow=c(2,2))
for(i in order(r.saved)){ #order(r.saved)
bio.median <- apply(samps.mat[,,i],2,FUN = quantile,.5)
plot(biomass,bio.median,
xlim=c(0,bMax), ylim=c(0,bMax), pch=19,
xlab="True Biomass", ylab="Predicted Mean Biomass",
main=colnames(Y)[i],col='black',cex = .5)
points(biomass[one.third.idx], bio.median[one.third.idx],pch=19,col='red',cex = .5)
abline(a=0,b=1)
lm.mod <- lm(bio.median[-one.third.idx] ~ biomass[-one.third.idx] +0)
lm.mod.13 <- lm(bio.median[one.third.idx] ~ biomass[one.third.idx] +0)
abline(lm.mod,lty=2)
abline(lm.mod.13,lty=2,col='red')
r.saved.23[i] <- give_me_R2(preds = bio.median[-one.third.idx],
actual = biomass[-one.third.idx])#signif(summary(lm.mod)$r.squared,digits = 3)
r.saved[i] <- give_me_R2(preds = bio.median[one.third.idx],
actual = biomass[one.third.idx])#signif(summary(lm.mod.13)$r.squared,digits = 3)
r2_23 <- signif(r.saved.23[i],digits = 3)
r2_13 <- signif(r.saved[i],digits = 3)
arrows(x0 = biomass, y0 = apply(samps.mat[,,i],2,FUN = quantile,.05),
x1 = biomass, y1 = apply(samps.mat[,,i],2,FUN = quantile,.975),
code = 0, lwd=.5)
arrows(x0 = biomass[one.third.idx], y0 = apply(samps.mat[,,i],2,FUN = quantile,.05)[one.third.idx],
x1 = biomass[one.third.idx], y1 = apply(samps.mat[,,i],2,FUN = quantile,.975)[one.third.idx],
code = 0, lwd=.5,col='red')
legend('bottomright',c(paste('R2 =',r2_23),paste('R2 =',r2_13)),text.col = c('black','red'))
}
dev.off()
out.table <- data.frame(TwoThirds=r.saved.23,OneThird=r.saved)
rownames(out.table) <- colnames(Y)
out.table <- out.table[order(out.table[,2]),]
xtable(out.table)
}
|
2ce484e0924ca6807a92bc798e337d28871784e0 | f05a2f7175f9422ac9908181c97aaab3c375fd34 | /tests/testthat/test-factorize-df.R | 21ea32c88e808a2f6e61b213a76694a21bdedca4 | [
"GPL-2.0-only",
"MIT",
"CC-BY-4.0"
] | permissive | tntp/tntpr | 19c6b39cf9252f2854a1faf7bd1062b582d8e5ab | fa9d7442cb42c667539213805192a9c845cf2913 | refs/heads/master | 2023-08-08T23:05:28.893304 | 2023-07-09T15:11:15 | 2023-07-09T15:11:15 | 158,586,843 | 4 | 0 | CC-BY-4.0 | 2023-08-15T17:43:50 | 2018-11-21T17:54:23 | R | UTF-8 | R | false | false | 2,081 | r | test-factorize-df.R | # Tests for factorizing columns based on string matching
library(tntpr); library(testthat)
context("factorize_df")
x <- data.frame(a = c("a lot", "a little", "some", "some"),
b = 1:4,
c = rep(as.POSIXct(Sys.Date()), 4),
stringsAsFactors = FALSE)
test_that("works with POSIX (two-class) columns present", {
y <- x
y$a <- factor(y$a, c("a little", "some", "a lot"))
expect_equal(tibble::as_tibble(y), factorize_df(x, c("a little", "some", "a lot")))
})
test_that("warning message if no matches found", {
expect_warning(factorize_df(x, c("bugs", "birds")),
"No columns matched. Check spelling & capitalization of your levels.",
fixed = TRUE)
})
test_that("appropriate message prints if matched but already factor", {
aa <- factorize_df(x, 4:1)
ab <- aa
ab$d <- 1:4
expect_warning(suppressMessages(factorize_df(aa, 4:1)),
"at least one matching column was already a factor, though this call will have reordered it if different levels provided. Could be caused by overlapping sets of factor levels, e.g., \"Yes\", \"Maybe\", \"No\" and \"Yes\", \"No\".",
fixed = TRUE)
expect_warning(suppressMessages(factorize_df(aa, 4:1)), # it says no NEW columns, acknowledging that there was a match but it was already a factor
"No new columns matched. Check spelling & capitalization of your levels.",
fixed = TRUE)
# the unusual case where there's a match on a non-factor and an already-present factor match
expect_warning(factorize_df(ab, 4:1),
"at least one matching column was already a factor, though this call will have reordered it if different levels provided. Could be caused by overlapping sets of factor levels, e.g., \"Yes\", \"Maybe\", \"No\" and \"Yes\", \"No\".",
fixed = TRUE)
expect_message(suppressWarnings(factorize_df(ab, 4:1)),
paste("Transformed these columns: \n", paste("* ", "d", collapse = ", \n")),
fixed = TRUE)
})
|
44c36e75bc6d87a84d63122e2f74f375c2078731 | 9580717f9f09fe026dee8224b35f3f72c9f78675 | /man/tween_microsteps.Rd | 3c49eb54d3a03f1d278cdd79de373cba9e999e32 | [] | no_license | sctyner/netvizinf | dc0fed9791ae7c29255ff133b010ed5f6bc39a17 | d9cd0e249ad6b351b59b9478d238dbaf0a8762ce | refs/heads/master | 2021-05-03T22:30:58.889245 | 2017-10-26T19:52:35 | 2017-10-26T19:52:35 | 71,607,611 | 1 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,536 | rd | tween_microsteps.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tween_microsteps.R
\name{tween_microsteps}
\alias{tween_microsteps}
\title{A function to create the full set of \code{\link[tweenr]{tween}}'d microstep data appropriate for animation.}
\usage{
tween_microsteps(ptv, pte, microsteps_df)
}
\arguments{
\item{ptv}{\code{list} A list of vertices and their locations at each microstep. The result of \code{\link{pretween_vertices}}}
\item{pte}{\code{list} A list of edges and their locations at each microstep. The result of \code{\link{pretween_edges}}}
\item{microsteps_df}{\code{data.frame}}
}
\value{
A data frame with the following columns:
\itemize{
\item \code{from} ego node
\item \code{to} alter node
\item \code{edge.weight} not important
\item \code{addedge} is the edge being added
\item \code{rmvedge} is the edge being removed
\item \code{microstep} the microstep (0 is the starting network)
\item \code{from.x} from node x coordinate
\item \code{from.y} from node y coordinate
\item \code{ms} animation microstep
\item \code{size} node size in the frame
\item \code{color} node color in the frame
\item \code{.frame} frame id for animating
\item \code{to.x} to node x coordinate
\item \code{to.y} to node y coordinate
\item \code{ecolor} edge color in the frame
\item \code{esize} edge size in the frame
}
}
\description{
A function to create the full set of \code{\link[tweenr]{tween}}'d microstep data appropriate for animation.
}
|
c3e4a6400f9ba34414752fddd75e757037c1666e | 286a38a9d52fef14b959763b0b920819c61a42cb | /GetXDataFrame.R | 22a1f68bd65a6d1673aca5eaf74feb71799d84de | [] | no_license | TBKelley/GettingAndCleaningDataPeer | 6b0df6bc74bb17df5bbe11d51d67e3c11cba8483 | 5da1a673e95964e9eb40f790902d8b541587269e | refs/heads/master | 2021-01-13T01:25:50.740562 | 2014-04-26T12:56:49 | 2014-04-26T12:56:49 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,707 | r | GetXDataFrame.R | ## GetXDataFrame.R
##
## Get a filtered X data frame of "UCI HAR Dataset".
##
## folderUNC: Source root folder for "UCI HAR Dataset"
## Example: "./UCI HAR Dataset"
## dataType: Type of data. Example: "test" or "train"
##
## Returns Data Frame with the following columns:
# 1 tBodyAcc-mean()-X
# 2 tBodyAcc-mean()-Y
# 3 tBodyAcc-mean()-Z
# 4 tBodyAcc-std()-X
# 5 tBodyAcc-std()-Y
# 6 tBodyAcc-std()-Z
# 41 tGravityAcc-mean()-X
# 42 tGravityAcc-mean()-Y
# 43 tGravityAcc-mean()-Z
# 44 tGravityAcc-std()-X
# 45 tGravityAcc-std()-Y
# 46 tGravityAcc-std()-Z
# 81 tBodyAccJerk-mean()-X
# 82 tBodyAccJerk-mean()-Y
# 83 tBodyAccJerk-mean()-Z
# 84 tBodyAccJerk-std()-X
# 85 tBodyAccJerk-std()-Y
# 86 tBodyAccJerk-std()-Z
# 121 tBodyGyro-mean()-X
# 122 tBodyGyro-mean()-Y
# 123 tBodyGyro-mean()-Z
# 124 tBodyGyro-std()-X
# 125 tBodyGyro-std()-Y
# 126 tBodyGyro-std()-Z
# 161 tBodyGyroJerk-mean()-X
# 162 tBodyGyroJerk-mean()-Y
# 163 tBodyGyroJerk-mean()-Z
# 164 tBodyGyroJerk-std()-X
# 165 tBodyGyroJerk-std()-Y
# 166 tBodyGyroJerk-std()-Z
# 201 tBodyAccMag-mean()
# 202 tBodyAccMag-std()
# 214 tGravityAccMag-mean()
# 215 tGravityAccMag-std()
# 227 tBodyAccJerkMag-mean()
# 228 tBodyAccJerkMag-std()
# 240 tBodyGyroMag-mean()
# 241 tBodyGyroMag-std()
# 253 tBodyGyroJerkMag-mean()
# 254 tBodyGyroJerkMag-std()
# 266 fBodyAcc-mean()-X
# 267 fBodyAcc-mean()-Y
# 268 fBodyAcc-mean()-Z
# 269 fBodyAcc-std()-X
# 270 fBodyAcc-std()-Y
# 271 fBodyAcc-std()-Z
# 345 fBodyAccJerk-mean()-X
# 346 fBodyAccJerk-mean()-Y
# 347 fBodyAccJerk-mean()-Z
# 348 fBodyAccJerk-std()-X
# 349 fBodyAccJerk-std()-Y
# 350 fBodyAccJerk-std()-Z
# 424 fBodyGyro-mean()-X
# 425 fBodyGyro-mean()-Y
# 426 fBodyGyro-mean()-Z
# 427 fBodyGyro-std()-X
# 428 fBodyGyro-std()-Y
# 429 fBodyGyro-std()-Z
# 503 fBodyAccMag-mean()
# 504 fBodyAccMag-std()
# 516 fBodyBodyAccJerkMag-mean()
# 517 fBodyBodyAccJerkMag-std()
# 529 fBodyBodyGyroMag-mean()
# 530 fBodyBodyGyroMag-std()
# 542 fBodyBodyGyroJerkMag-mean()
# 543 fBodyBodyGyroJerkMag-std()
source("GetFeatureName.R")
source("GetFileUNC.R")
source("GetRequiredColumnIndexList.R")
GetXDataFrame <- function(folderUNC, dataType) {
getFeatureName <- make.GetFeatureName(folderUNC)
requiredColIndex <- GetRequiredColumnIndexList(folderUNC)
requiredColNames <- getFeatureName(requiredColIndex) # Example: c('tBodyAcc-mean()-X', ...'fBodyBodyGyroJerkMag-std()')
filename <- paste("X_", dataType, ".txt", sep="")
fileUNC <- GetFileUNC(paste(folderUNC, dataType, sep="/"), filename)
cat("Read ", "'", fileUNC, "'", "\n", sep="")
df <- read.table(fileUNC, header=FALSE) # 561 Columns
df <- df[requiredColIndex]
names(df) <- requiredColNames
df
} |
b3f87837896708b0923b218e03957d99500053b0 | c520c73d2db2b95ced0c6c75778b18b2b64e45d7 | /man/calculate_epp.Rd | 7a977193e9e45bc1f02f0c26f195608f9a4a4ab8 | [] | no_license | ModelOriented/EloML | 9c8b50b6e15b283d2dd930daf7001bea37f69f3f | 11d1670379b1602b662068f7aa9cce7deba0cdf1 | refs/heads/master | 2022-06-22T03:38:06.371318 | 2022-06-17T16:24:31 | 2022-06-17T16:24:31 | 206,395,947 | 23 | 2 | null | 2019-09-27T11:11:25 | 2019-09-04T19:21:29 | R | UTF-8 | R | false | true | 2,402 | rd | calculate_epp.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/calculate_elo.R
\name{calculate_epp}
\alias{calculate_epp}
\title{Calculate EPP Meta-Scores for All Players}
\usage{
calculate_epp(
results,
decreasing_metric = TRUE,
compare_in_round = TRUE,
keep_columns = FALSE,
keep_model = FALSE,
reference = NULL,
keep_data = TRUE,
estimation = "glmnet"
)
}
\arguments{
\item{results}{Data frame. Results for one Round Data should be in the following format.
First 3 columns should correspond to: Player, Round, Score. See more in 'details' section.}
\item{decreasing_metric}{Logical. If TRUE used Score is considered as decreasing, that means a Player with higher Score value is considered as winner.
If FALSE used Score will be considered as increasing.}
\item{compare_in_round}{Logical. If TRUE compares Players only in the same fold. If FALSE compares Players across folds.}
\item{keep_columns}{Logical. If TRUE original data frame with new 'epp' column will be returned.}
\item{keep_model}{Logical. If TRUE logistic regression model to compute EPP will be returned.}
\item{reference}{Character. Name of the Player that should be a reference level for EPP Meta-scores. It should be a name of one of the Players from
'results' data frame. If NULL, none of the Players will be chosen.}
\item{keep_data}{If all the meta-data should be kept in result.}
\item{estimation}{Method of estimating EPP coefficients, 'glm' or 'glmnet'.}
}
\value{
epp_results
}
\description{
Calculate EPP Meta-Scores for All Players
}
\details{
Format of the data frame passed via results parameter.
First column should correspond to a Player.
Second column corresponds to indexes of Rounds As EPP is based on Elo rating system, power of Player is assessed by comparing its results
with other Players on multiple Rounds. Therefore, each Player should be evaluated on multiple Rounds.
Indexes of Rounds should be in this column. And should match across Players.
Third column contains Score used to evaluate players. It can be both decreasing or increasing metric.
just remember to set the \code{decreasing_metric} parameter accordingly.
The following columns can be of any kind.
Naming convention, such as Player, Rounds, etc. comes from \href{https://arxiv.org/abs/2006.02293}{Gosiewska et al. (2020)}.
}
\examples{
library(EloML)
data(auc_scores)
calculate_epp(auc_scores[1:400,])
}
|
d24b6ae179e26d9bb53d50e60454be44820eeee0 | 4a9029585d7ab42959856fc46b5ef60618d9da49 | /Assignment1/Mandatory1.R | f1a155c7f6f97eded9d8ebe8cebfb3d04824577e | [] | no_license | Eiriksak/STA510 | c974b615165a48ad2b11ba61bb38691c53537f10 | 345f9fae82d611c34c10c99791da99aec87eccc8 | refs/heads/master | 2021-05-16T23:07:30.749377 | 2020-03-27T10:50:46 | 2020-03-27T10:50:46 | 250,508,408 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 15,255 | r | Mandatory1.R | rm(list=ls())
library("ggplot2")
library("gridExtra")
##Author: Eirik Sakariassen
######### 1C
#N = num of cards, k=num of success states among the cards, n=num of cards drawn
simCardDraws <- function(Nsim, N, k, n){
#Generate a deck of cards
suits <- c('Red','Failure') # Red=success, black+yellow=failure
ResVec <- vector(length=Nsim) # Vector to store the simulated draw results
for(i in 1:Nsim){
deck <- rep(suits, times = c(k,N-k)) #creates a deck of k (18) red cards, then the remainding ones becomes failure cards
drawn_cards <- c() #vector of drawn cards
#Now pick n random cards from the deck and append to drawn_cards
for(j in 1:n){
index <- round(runif(1, 1, length(deck))) #random number between 1 and length of deck
drawn_cards <- c(drawn_cards, deck[index]) #append to drawn_cards vector
deck <- deck[-index] #remove the card from the deck
}
ResVec[i] = sum(drawn_cards == 'Red') #add the number of red cards drawn into the result vector
}
return(ResVec)
}
cardSim <- simCardDraws(Nsim=10000, N=36, k=18, n=6)
hist(cardSim)
sum(cardSim >= 2)/length(cardSim) #P(Y6 >= 2), 0.9113 from 1a
mean(cardSim) #expected value, 3 from 1a
######### 1E
simCardGame <- function(Nsim, condition1){
resVec <- vector(length = 11)
for(i in 0:10){ #simulate 10 probabilities for p
p <- i/10
simWinner <- vector(length = Nsim)
for(j in 1:Nsim){
deck <- rep(c('Red','Black', 'Yellow'), times = c(18,18,1)) #creates a deck of 18 red, 18 black and 1 yellow
player1 = c()
player2 = c()
for(k in 1:8) { #pick 8 cards
index <- round(runif(1, 1, length(deck))) #random number between 1 and length of deck
if(k%%2 == 0){ #the players pick a new card every other time
player2 <- c(player2, deck[index])
}else{
if(condition1){ #First three cards are red, the last one random
if(k==7){
player1 <- c(player1, deck[index]) #last random
}else{
player1 <- c(player1, deck[1]) #First value allways red in the deck since there is no shuffle and k<18
deck <- deck[-1]
next
}
}else{
player1 <- c(player1, deck[index])
}
}
deck <- deck[-index]
}
winner = ""
#Coin toss (ensures a winner if rest of the conditions does not appair)
toss <- ifelse(runif(1) < p, "Heads", "Tails")
if(toss == 'Heads'){
winner = "Player1"
}else{
winner = "Player2"
}
#Player with most red cards
if (sum(player1 == 'Red') > sum(player2 == 'Red')){
winner = "Player1"
} else if (sum(player2 == 'Red') > sum(player1 == 'Red')){
winner = "Player2"
}
#Check if anyone has a yellow card
if('Yellow' %in% player1){
winner = "Player1"
} else if('Yellow' %in% player2){
winner = "Player2"
}
simWinner[j] = winner #Store all winners for this simulation of p
}
resVec[i+1] <- (sum(simWinner == 'Player2'))/Nsim #Add the probability that p2 won based on one simulation for p
}
return(resVec)
}
CardGameC1 <- simCardGame(10000, TRUE) #with condition 1
CardGameC2 <- simCardGame(10000, FALSE) #with condition 2
##### Plot 1E #####
pValues <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0)
mydata1 <-data.frame(pValues, CardGameC1)
mydata2 <-data.frame(pValues, CardGameC2)
p1 <-ggplot(mydata1, aes(pValues, CardGameC1)) +
labs(x = "p values", y="Probability that Player 2 wins", title="Condition 1") + geom_bar(stat = "identity")
p2 <-ggplot(mydata2, aes(pValues, CardGameC2)) +
labs(x = "p values", y="Probability that Player 2 wins", title="Condition 2") + geom_bar(stat = "identity")
grid.arrange(p1, p2, ncol = 2)
##### end plot #####
######### 2C
simTimeToHospital <- function(Nsim){
resVec <- vector(length = Nsim)
for(i in 1:Nsim){
#ACCIDENT JUST HAPPENED
peopleInAccident <- sample(c(1:4), size = 1, prob=c(0.4,0.3,0.2,0.1), replace = TRUE)
timeToLastPerson <- sum(rexp(peopleInAccident,1/15))
resVec[i] <- timeToLastPerson
}
return(resVec)
}
T <- simTimeToHospital(10000)
sum(T > 30)/length(T) #P(T>30)
median(T)
max(T)
######### 2E
simBusyAmbulance <- function(Nsim, stoptime, lambda){
resVec <- vector(length=Nsim)
for(i in 1:Nsim){
#Simulate a poisson process with intensity lambda over a time period
#The inter arrival times can be simulated from an exponential distribution with parameter lambda
#This part is directly taken from stochastic_processes_examples.R
expectednumber <- stoptime*lambda # Expected number of event until stoptime
sim <- 3*expectednumber # Simulate more than the expected number to be certain to exceed stoptime
timesBetween <- rexp(sim,lambda) # Simulate the interarrival times T1,T2,..
arrivalTimes <- cumsum(timesBetween) # Calculate arrival times
arrivalTimes <- arrivalTimes[arrivalTimes<stoptime] # Discard the times larger than stoptime
if(length(arrivalTimes) < 2){ #go to next simulation if it was only one accident this time period
resVec[i] <- 0
next
}
#Now simulate a queue system for the ambulance based on the arrival times
isBusy <- FALSE
for(accident in 1:(length(arrivalTimes)-1)){ #Last arrival has no accident after that may crash
peopleInAccident <- sample(c(1:4), size = 1, prob=c(0.4,0.3,0.2,0.1), replace = TRUE)
timeToLastPerson <- sum(rexp(peopleInAccident,1/15))/60 #represent accident times as hours
if(arrivalTimes[accident+1]-arrivalTimes[accident] < timeToLastPerson){ #Check if ambulance is done before next arrival
isBusy <- TRUE
break
}
}
if(isBusy){
resVec[i] <- 1
}else{resVec[i] <- 0}
}
return(sum(resVec)/Nsim)
}
T24 <- simBusyAmbulance(10000,24,0.2)
T24 #Probability that the ambulance is being out on a mission at the time when an accident occurs within 24h
TWEEK <- simBusyAmbulance(10000,168,0.2)
TWEEK
TMONTH <- simBusyAmbulance(10000,720,0.2)
TMONTH
######### 3A
simRenyiRandomGraph <- function(n, p, Nsim){
degreeDis <- rep(0,n) #Add distribution after each simulation
for(s in 1:Nsim){
degreeVec <- rep(0,n) #store the degree of each vertex
#Represent the graph as a matrix
adjacencyMatrix <- matrix(1, nrow=n, ncol=n) #Create a nxn adjacency matrix
diag(adjacencyMatrix) <- 0 #Set all nodes to be connected to each other, except connected to itself (0 at the diagonal)
#Since this is an undirected graph, we dont need to look at more than the upper half of the diagonal in the matrix
for(i in 2:n){ #n columns (skip the first since thats 0 anyway)
for(j in 1:i-1){ #stop at the upper half of the diagonal
#Now evaluate each edge with a coin toss
toss <- ifelse(runif(1) < p, "Head", "Tail")
if(toss =="Tail"){
adjacencyMatrix[j,i] <- 0 #remove the edge
}else{
#Increment both the i and j nodes degree (since its undirected)
degreeVec[i] <- degreeVec[i] +1
degreeVec[j] <- degreeVec[j] +1
}
}
}
#Create a degree distribution for this simulation
simDegreeDis <- rep(0,n)
for(i in 1:n){
simDegreeDis[degreeVec[i]] <- simDegreeDis[degreeVec[i]] +1
}
degreeDis <- degreeDis + simDegreeDis/n #Add to the total distribution
}
return(list("distribution" = degreeDis/n, "mean" = mean(degreeVec), "max" = max(degreeVec), "var" = var(degreeVec)))
}
rg1 = simRenyiRandomGraph(100,0.5,100)
rg2 = simRenyiRandomGraph(100,0.1,100)
rg3 = simRenyiRandomGraph(100,0.01,100)
##### Plot 3A #####
mydata1 <-data.frame(x=c(1:100), probability = rg1$distribution)
mydata2 <-data.frame(x=c(1:100), probability = rg2$distribution)
mydata3 <-data.frame(x=c(1:100), probability = rg3$distribution)
title1 <- sprintf("p=0.5, mean=%2.1f, var=%2.1f, max=%2.1f", rg1$mean, rg1$var, rg1$max)
title2 <- sprintf("p=0.1, mean=%2.1f, var=%2.1f, max=%2.1f", rg2$mean, rg2$var, rg2$max)
title3 <- sprintf("p=0.01, mean=%2.1f, var=%2.1f, max=%2.1f", rg3$mean, rg3$var, rg3$max)
p1 <-ggplot(mydata1, aes(x,probability)) + labs(title=title1) + geom_bar(stat = "identity")
p2 <-ggplot(mydata2, aes(x,probability)) + labs(title=title2) + geom_bar(stat = "identity")
p3 <-ggplot(mydata3, aes(x,probability)) + labs(title=title3) + geom_bar(stat = "identity")
grid.arrange(p1, p2, p3, ncol = 1)
##### end plot #####
######### 3B
#the adjacencyMatrix is commented out due to the compute time. Could be used as a representation of the graph if needed
simPreferentialAttachment <- function(n, p, Nsim){
degreeDis <- rep(0,n) #Add distribution after each simulation
for(s in 1:Nsim){
adjacencyMatrix <- matrix(c(0,1,0,0), nrow=2, ncol=2) #Start with 2 vertices, where vertex2 is connected to vertex1
V <- seq(2) #Collection of vertices
degreeVec <- c(1,0) #store the degree of each vertex
for(i in 3:n){ #down the rows
toss <- ifelse(runif(1) < p, "Head", "Tail")
#Existing rows in the matrix only needs a new zero column to be inserted
#adjacencyMatrix <- cbind(adjacencyMatrix, 0)
#The new row (representing newly inserted vertex) need to fill in the entire row with i columns
#adjacencyMatrix <- rbind(adjacencyMatrix, rep(0,i))
if(toss == "Head"){
#Connect to an existing vertex drawn uniformly at random
vertex <- sample(V, 1, replace = TRUE)
#adjacencyMatrix[i,vertex] <- 1 #At the newly inserted row, add which column (vertex) it is connected to
degreeVec[vertex] <- degreeVec[vertex] + 1 #New edge at the drawn vertex
} else{
#Connect to an existing vertex (the number of edges with end-point in an existing vertex determines its probability)
probVec <- degreeVec/sum(degreeVec) #calculates the probabilty for each vertex
vertex <- sample(V, size = 1, prob=probVec, replace = TRUE) #pick a vertex based on each probability
#adjacencyMatrix[i,vertex] <- 1
degreeVec[vertex] <- degreeVec[vertex] + 1 #New edge at the drawn vertex
}
V <- seq(i) #new vertex in the collection of vertices
degreeVec <- c(degreeVec,0) #new vertex added to the degree vector (0 value since no one is connected atm)
}
simDegreeDis <- rep(0,n)
for(l in 1:n){
simDegreeDis[degreeVec[l]+1] <- simDegreeDis[degreeVec[l]+1] + 1
}
degreeDis <- degreeDis + simDegreeDis/n #Add to the total distribution
}
return(list("distribution" = degreeDis/n, "degrees" = degreeVec, "mean" = mean(degreeVec), "max" = max(degreeVec), "var" = var(degreeVec)))
}
pam1 <- simPreferentialAttachment(10000, 0.5, 1)
pam2 <- simPreferentialAttachment(10000,0.1,1)
pam3 <- simPreferentialAttachment(10000,0.01,1)
##### Plot 3B part 1##### (if just 1 of 6 plots shows up, click on the zoom button or run plot again)
mydata1 <-data.frame(age=c(1:10000), degree = pam1$degrees)
mydata2 <-data.frame(age=c(1:10000), degree = pam2$degrees)
mydata3 <-data.frame(age=c(1:10000), degree = pam3$degrees)
p1 <- ggplot(mydata1,aes(x=age,y=degree)) + geom_point(alpha = 1) + labs(title="p=0.5")
logp1 <- ggplot(mydata1,aes(x=log(age),y=log(degree))) +
labs(title="Log-log plot with regression") + geom_point(alpha = 1) +
geom_smooth(method = "lm", se = FALSE)
p2 <- ggplot(mydata2,aes(x=age,y=degree)) + geom_point(alpha = 1) + labs(title="p=0.1")
logp2 <- ggplot(mydata2,aes(x=log(age),y=log(degree))) +
labs(title="Log-log plot with regression") + geom_point(alpha = 1) +
geom_smooth(method = "lm", se = FALSE)
p3 <- ggplot(mydata3,aes(x=age,y=degree)) + geom_point(alpha = 1) + labs(title="p=0.01")
logp3 <- ggplot(mydata3,aes(x=log(age),y=log(degree))) +
labs(title="Log-log plot with regression") + geom_point(alpha = 1) +
geom_smooth(method = "lm", se = FALSE)
grid.arrange(p1, logp1, p2, logp2, p3, logp3, ncol = 2)
##### end plot part 1#####
#3B part 2
#simulate 100 times with N=100
pam4 <- simPreferentialAttachment(100,0.5,100)
pam5 <- simPreferentialAttachment(100,0.1,100)
pam6 <- simPreferentialAttachment(100,0.01,100)
##### Plot 3B part 2 #####
mydata4 <-data.frame(x=c(1:100), probability = pam4$distribution)
mydata5 <-data.frame(x=c(1:100), probability = pam5$distribution)
mydata6 <-data.frame(x=c(1:100), probability = pam6$distribution)
title4 <- sprintf("p=0.5, mean=%2.1f, var=%2.1f, max=%2.1f", pam4$mean, pam4$var, pam4$max)
title5 <- sprintf("p=0.1, mean=%2.1f, var=%2.1f, max=%2.1f", pam5$mean, pam5$var, pam5$max)
title6 <- sprintf("p=0.01, mean=%2.1f, var=%2.1f, max=%2.1f", pam6$mean, pam6$var, pam6$max)
p4 <-ggplot(mydata4, aes(x,probability)) + labs(title=title4) + geom_bar(stat = "identity")
p5 <-ggplot(mydata5, aes(x,probability)) + labs(title=title5) + geom_bar(stat = "identity")
p6 <-ggplot(mydata6, aes(x,probability)) + labs(title=title6) + geom_bar(stat = "identity")
grid.arrange(p4, p5, p6, ncol = 1)
##### end plot 3B part 2 #####
######### 4B
#Implemented the discrete inverse transfer algorithm from 4a
simDiscInverseTransf = function(Nsim, n, s) {
pmfVec <- vector(length=n) #Store n values calculated from the pmf
#Generate the constant divider
divider <- 0
for(l in 1:n){
divider <- divider + 1/l^s
}
#Calcuate the k values from pmf
for(v in 1:n){
pmfVec[v] <- (1/v^s)/divider
}
U <- runif(Nsim)
resVec <- rep(0,Nsim)
for (i in 1:Nsim) {
if(U[i] <= pmfVec[1]){
resVec[i] = 1
}
#Check if the condition applies for a constant k
for(k in 2:length(pmfVec)) {
if(sum(pmfVec[1:(k-1)]) < U[i] && U[i] <= sum(pmfVec[1:k]) ) {
resVec[i] <- k
}
}
}
return(list("result" = resVec, "theoretical" = pmfVec))
}
ditf <- simDiscInverseTransf(10000,10,3)
##### Plot 4B #####
theory <- data.frame(x=c(1:10), probability = ditf$theoretical)
res <- as.data.frame(table(ditf$result))
colnames(res) <- c("x", "probability")
p1 <- ggplot(theory, aes(x,probability)) + labs(title="Theory") + geom_bar(stat = "identity", fill="steelblue")
p2 <- ggplot(res, aes(x,probability/10000)) + labs(y="probability", title="Simulation") + geom_bar(stat = "identity", fill="red")
grid.arrange(p1,p2, ncol = 1)
##### Plot 4B #####
######### 4C
#Simulate K by inverse transfer method
#For a geometric distribution, P(X=k) = p(1-p)^k-1, k=1,2,..
simK <- function(Nsim){
pmfVec <- vector(length=100)
for(v in 1:100){
W <- rexp(1, 1/2)
p <- 1-exp(-W)
pmfVec[v] <- p*(1-p)^(v-1)
}
U <- runif(Nsim)
resVec <- rep(0,Nsim)
for (i in 1:Nsim) {
#Check if the condition applies for a constant k
if(U[i] <= pmfVec[1]){
resVec[i] = 1
}
for(k in 2:length(pmfVec)) {
if(sum(pmfVec[1:(k-1)]) < U[i] && U[i] <= sum(pmfVec[1:k]) ) {
resVec[i] <- k
}
}
}
return(list("result" = resVec, "theoretical" = pmfVec))
}
sk <- simK(10000)
hist(sk$result)
#The plot of the simulated rv K proves that the
#preferential attachment model from Problem 3 converges K as N -> inf. (and a low p value)
##Compare simulation with real generated if needed
#W <- rexp(10000, 1/2)
#Z = 1-exp(-W)
#K = rgeom(10000,Z)
#hist(K)
|
ea367c907cbc7d50333cad5bb76f0b8eb1a87e9f | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/growthcurver/examples/SummarizeGrowth.Rd.R | 28771c19190b007969a17294f99ae102ee8ae0eb | [] | no_license | surayaaramli/typeRrh | d257ac8905c49123f4ccd4e377ee3dfc84d1636c | 66e6996f31961bc8b9aafe1a6a6098327b66bf71 | refs/heads/master | 2023-05-05T04:05:31.617869 | 2019-04-25T22:10:06 | 2019-04-25T22:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,226 | r | SummarizeGrowth.Rd.R | library(growthcurver)
### Name: SummarizeGrowth
### Title: Summarize Growth Curves
### Aliases: SummarizeGrowth
### ** Examples
# We can check that the parameters that are found are the same
# as we use to generate fake experimental data. To do so, let's first
# generate the "experimental" data using the logistic equation,
# e.g., absorbance readings from a single well in a plate reader over time.
k_in <- 0.5 # the initial carrying capacity
n0_in <- 1e-5 # the initial absorbance reading
r_in <- 1.2 # the initial growth rate
N <- 50 # the number of "measurements" collected during the growth
# curve experiment
data_t <- 0:N * 24 / N # the times the measurements were made (in hours)
data_n <- NAtT(k = k_in, n0 = n0_in, r = r_in, t = data_t) # the measurements
# Now summarize the "experimental" growth data that we just generated
gc <- SummarizeGrowth(data_t, data_n)
# Get the possible metrics for fitness proxies
gc$vals$r # growth rate is a common choice for fitness
gc$vals$t_gen # doubling time, or generation time, is also common
gc$vals$k
gc$vals$n0
gc$vals$auc_l
gc$vals$auc_e
gc$vals$t_mid
# Compare the data with the fit visually by plotting it
plot(gc)
|
96f2d6ab1043ffb0a64aeeddc96cc31db21a0bac | 617a2b428dbee689943fbeb0d7058592666dc33b | /stockQuoter.R | 6ed7415058fdf4ac02e5bef0dd8c6f121299dfa6 | [] | no_license | mksaraf/finance-stockStrategy | b4c9aacbc562e3de01e530dc5500d11dbeddc722 | 6cb09e8a08bf62256eb5e0d2de144fb70fc0c840 | refs/heads/master | 2021-09-27T14:26:47.496263 | 2018-11-09T04:03:16 | 2018-11-09T04:03:16 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,218 | r | stockQuoter.R |
################# Finance : Stock Quoter STOCK Updates for Indian market ##################################
############## INput: Takes stock symbols from the database ################
############## Process: Gets Key Stats & STK data from Yahoo URL / Query ################
############## Process: Store into database/USSTOCKS/INStocks ################
library(quantmod)
library(RODBC)
library(RQuantLib)
library(data.table)
processNumber<-function(x){
x=gsub(",","",x)
x=gsub("%","/1",x) # Div by 1 is just to make it values compatible with Java program
x=gsub("N/A","0",x)
x=gsub("K","*1000",x)
x=gsub("M","*1000000",x)
x=gsub("B","*1000000000",x)
x=gsub("T","*1000000000000",x)
x=eval(parse(text=x))
return(x)
}
setwd(paste0("C:/Users/",Sys.getenv("username"),"/Dropbox/Projects/RCode/finance-stockStrategy/"))
ch<-odbcDriverConnect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=../../FirmFinancials/USStocks.accdb")
#### ################ ### Update INSTOCKS table #######
stk.tab <- data.table(sqlFetch(ch, "INStocks",stringsAsFactors = F)) #Fetch Query results
setkey(stk.tab,symbol)
symbolList = rbindlist(lapply(stk.tab$symbol,function(x) tryCatch(data.table(getSymbols(x,from=Sys.Date()-2,env = NULL),x )[,6:7],error=function(e) data.table(NA,x)) ), fill = F)
stocks.in = symbolList[symbolList[,max(.I),keyby=x][,V1],]
stocks.in$LastUpdated = Sys.Date()
setnames(stocks.in,1:2,c('ClosePrice','symbol'))
sqlUpdate(ch,dat=stocks.in, tablename = 'INStocks',index = c('symbol'))
#### ################ ### Update INPortfolioTable #######
pf = data.table(sqlQuery(channel = ch, "Select INStocks.symbol,Number,BuyPrice,BuyDate,INStocks.ClosePrice from INPortfolioTable,INStocks where INStocks.symbol=INPortfolioTable.symbol",stringsAsFactors=FALSE))
pf$Profit = (pf$ClosePrice-pf$BuyPrice)*pf$Number
pf$AbsoluteGrowth = (pf$ClosePrice/pf$BuyPrice -1)
pf$AnnualizedGrowth = pf$AbsoluteGrowth/(as.numeric(Sys.Date()-as.Date(pf$BuyDate))/365)
pf$CostBasis = (pf$BuyPrice)*pf$Number
pf$LastUpdated = Sys.Date()
sqlUpdate(ch,dat=pf[,-c('ClosePrice')],tablename="INPortfolioTable",index=c("symbol"))
close(ch) |
c03ec9c0bbf7b19eae078e0391deb11f88fac30e | 9a4a0951042394c3bf29ac1ec4a8867891812568 | /data preparation/prep data for event study.R | 7652108d61e922e32908ed2d962528592b590bf5 | [] | no_license | dkori/east_lib_systems_git | 2d12aa3d6f00903edf5e5467215dc9ec5791fd66 | 6a82c5c5e5bf07d677199f7ba0f9507d41d0b6d2 | refs/heads/master | 2021-01-04T22:25:13.766397 | 2020-05-11T19:03:18 | 2020-05-11T19:03:18 | 240,785,146 | 0 | 2 | null | null | null | null | UTF-8 | R | false | false | 2,998 | r | prep data for event study.R | rm(list=ls())
library(dplyr)
library(sf)
library(tidyr)
library(tidycensus)
library(leaflet)
#read in allegheny county blocks
load("quantitative analysis/block groups.Rdata")
blocks<-alle_co_block_groups%>%
st_transform(crs="+init=epsg:4326")
# read in neighborhood data
hoods<-st_read("data preparation/geocode addresses/Neighborhoods_/Neighborhoods_.shx")%>%
select(hood)
#read in parcel boundaries
parcels<-st_read("quantitative analysis/Allegheny_County_Parcel_Boundaries/Allegheny_County_Parcel_Boundaries.shx")%>%
st_transform(crs="+init=epsg:4326")
# load geocoded voucher data
load("cleaned and geocoded data 01-April.Rdata")
# load the dataframe of moves (for calculating disadvantages)
load("quantitative analysis/east end moves.Rdata")
# load bnp data
load("quantitative analysis/combined apartments commercial bnps.Rdata")
#read in zoning data
#read in zoning data
zoning<-read_sf("quantitative analysis/zoning/zoning.geojson")%>%
select(full_zoning_type)
# create a dataframe of parcels corresponding to bnps/apartments (used to exclude treatment matches)
bnp_parcels<-parcels%>%
st_join(apartments_commercial_bnps,st_intersects,left=FALSE)%>%
#some parcels overlap (subparcels on parcels), so we want to use the parcel with the largest area
group_by(`Development.Projects`,`Date-Completed`,Type)%>%
slice(which.max(SHAPE_Area))%>%
ungroup()%>%
#get rid of duplicate projects while preserving type,
group_by(`Development.Projects`,`Date-Completed`)%>%
summarise(Type=max(Type))%>%
ungroup()%>%
#get rid of Google Offices since its located on the same parcel / geoid as bakery square
filter(!grepl("Google",`Development.Projects`))
# add census blocks to bnps (this is separate from parcels), used to find treatment matches
bnps<-apartments_commercial_bnps%>%
st_join(blocks,st_within)%>%
#join in neighborhoods
st_join(hoods,st_within)%>%
#limit only to bnps for which we have a parcel match
filter(`Development.Projects`%in%bnp_parcels$`Development.Projects`)%>%
#get rid of duplicates while preserving type
group_by(`Development.Projects`,`Date-Completed`,GEOID,hood)%>%
summarise(Type=max(Type))%>%
ungroup()
#change type for Rippey street to "mixed income"
bnps[bnps$Development.Projects=="Rippey Apartment Complex",]$Type<-"Mixed-income"
# add census blocks to voucher stay data
voucher_stays<-cleaned_and_geocoded%>%
st_join(blocks,st_within)%>%
#also add zoning data
st_join(zoning,st_within)
# add census blocks to voucher moves
voucher_moves<-moves%>%
st_as_sf()%>%
st_join(blocks,st_within)%>%
#also add zoning data
st_join(zoning,st_within)
#save all the datasets we just created
save(bnps,bnp_parcels,voucher_stays,voucher_moves,
file="quantitative analysis/files for event study.Rdata")
# test1<-bnp_parcels%>%
# filter(grepl('Bakery Square|Google',`Development.Projects`))
#
# leaflet()%>%
# addProviderTiles(providers$CartoDB.Positron)%>%
# addPolylines(data=st_as_sf(test1)) |
f56673cc1db1e936e70ec3e820f66ba1fc6b4f4d | ebe176edc75218f81d56589fff819c5a1337179d | /Exploratory-Data-Analysis/ExData_Plotting1/main.R | 39553040953cd7a3747e10ce725b11060c9bc585 | [] | no_license | tcriscuolo/Coursera | 365ccea58ae810ab502da804abd264c41fa9966d | 559ba95cf1286aed32256c18b9cb249aa4d69cab | refs/heads/master | 2021-01-10T02:53:04.086237 | 2015-06-19T18:42:07 | 2015-06-19T18:42:07 | 36,746,163 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 653 | r | main.R | #Pre process the data
# It is assumed that the household power consumption file
# is ins in the same working directory
# The raw data set can be found at this link
# https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip
data <- read.table(file = "household_power_consumption.txt", sep = ";",
na.strings = c("NA", "?"), header = TRUE);
# Subset the dataset
data <- data[data$Date %in% c("1/2/2007","2/2/2007") ,]
# Create a data and time variable
date <- paste(data$Date, data$Time);
data$DateTime <- strptime(date, "%d/%m/%Y %H:%M:%S")
dim(data);
write.csv(data, file = "data.csv", row.names = F)
|
ccd2675589221a99526eda7c45fe1287dd624a10 | 95676ebfb27d6706d6bd9c23f04dfb43bd62bac2 | /BaseballHistoryPlot_script.R | f55c897b3d9f5ea678dc42ff8d4e191065d2ef6f | [] | no_license | jnotis99/baseball-history-plot | 3364498c0372dee9154f5e5e3fc816ad592bf496 | a5a185bfcfc0bb4c2c971a35eed56055027e1006 | refs/heads/master | 2021-04-03T05:20:59.882845 | 2019-11-07T21:45:48 | 2019-11-07T21:45:48 | 124,954,226 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,781 | r | BaseballHistoryPlot_script.R | ## Extra-Base Hit and Strikeout frequency throughout Professional Baseball
##
## Name: Joseph Notis
## Date: February 17, 2018
# Initial settings --------------------------------------------------------
library(tidyverse)
library(rvest)
library(ggrepel)
# Read and wrangle data ---------------------------------------------------
web_table <- function(num_tbl, stats) {
df <- temp[[num_tbl]] %>%
filter(Year != "Year") %>%
select(stats) %>%
mutate_if(is.character, as.numeric, stats)
return(df)
}
middle_year <- function(start, end) {
mid_year <- round(median(c(start, end)))
return(mid_year)
}
Eras <- data.frame(
Year = c(middle_year(1871, 1892) + 1, # The +1 adjusts to prevent the text from intersecting with the line in the plot
middle_year(1893, 1919),
middle_year(1920, 1946),
middle_year(1947, 1968),
middle_year(1969, 1992),
middle_year(1993, 2012),
2016),
era_name = c("Pioneer Era",
"Dead Ball Era",
"Live Ball Era",
"Golden Era",
"Artificial Turf\nEra",
"Steroid Era",
"Moneyball\nEra")
)
sig_events = data.frame(
Year = c(1910, 1920, 1941, 1945, 1969),
event_name = c("First cork-based core\n in baseballs",
"Spitball outlawed",
"WWII\nstarts",
"WWII\nends",
"Pitcher's mound lowered\nto 10 inches"))
url <- "https://www.baseball-reference.com/leagues/MLB/bat.shtml#all_teams_standard_batting_totals"
temp <- read_html(url) %>%
html_nodes("table") %>%
html_table()
totals <- web_table(2, c("Year", "H", "2B", "3B", "HR")) %>%
group_by(Year) %>%
mutate(XBH = (`2B` + `3B` + HR)) %>%
ungroup()
averages <- web_table(1, c("Year", "G", "H", "HR", "SO")) %>%
mutate(XBH = totals$XBH / G,
pct_K = SO / 27,
pct_XBH = XBH / H) %>%
gather("Stat", "Ratio", 7:8) %>%
mutate(Stat = ifelse(Stat == "pct_XBH",
"Percentage of Hits that were Extra-Base Hits per Game",
"Percentage of Outs that were Strikeouts per Game")) %>%
left_join(Eras, by = "Year") %>%
left_join(sig_events, by = "Year") %>%
mutate(sig_year = !is.na(event_name))
# Data visualization ------------------------------------------------------
ggplot(averages, aes(Year, Ratio)) +
annotate("rect", xmin = 1893, xmax = 1919, ymin = -Inf, ymax = Inf, alpha = 0.3, fill = "darkgray") +
annotate("rect", xmin = 1947, xmax = 1968, ymin = -Inf, ymax = Inf, alpha = 0.3, fill = "darkgray") +
annotate("rect", xmin = 1993, xmax = 2012, ymin = -Inf, ymax = Inf, alpha = 0.3, fill = "darkgray") +
geom_label_repel(aes(label = event_name),
direction = "y",
nudge_y = c(0.07, -0.05),
min.segment.length = 0.001,
size = 4,
na.rm = TRUE) +
geom_line(size = 1.25) +
geom_point(aes(size = sig_year)) +
geom_text(aes(Year, 0.025, label = era_name), na.rm = TRUE, size = 4) +
facet_wrap(~ Stat, nrow = 2) +
scale_x_continuous(breaks = c(1871, 1893, 1919, 1947, 1968, 1993, 2012, 2017)) +
scale_y_continuous(limits = c(0, 0.4),
labels = scales::percent) +
labs(title = "Extra-Base Hit and Strikeout frequency throughout Professional Baseball",
subtitle = paste("Source: Major League Baseball Batting Year-by-Year Averages and Totals, Baseball Reference"),
y = "") +
theme_minimal() +
guides(size = FALSE) +
theme(strip.text = element_text(size = 10),
axis.text.x = element_text(size = 7)) +
scale_size_manual(values = c(0.25, 2.5))
ggsave("figures/MLB_History_Plot.pdf", width = 13, height = 7.5)
|
c5bc874ba8c973f042a05c85b5b2655efa503ef3 | 4e09dc73001ca609406fef2b7dd9441b8ee1690e | /Plot4.R | 80298c5ffe46df6a40bece714e4a952186919aa3 | [] | no_license | Yun-Hui/ExData_Plotting1 | 5ffa47042edc4e171b314aff41c6dff9a2de837e | a08fa0c364e78881924bc571ae9f2f9659145d64 | refs/heads/master | 2021-01-01T16:57:36.383509 | 2017-07-21T15:43:06 | 2017-07-21T15:43:06 | 97,959,801 | 0 | 0 | null | 2017-07-21T15:02:40 | 2017-07-21T15:02:40 | null | UTF-8 | R | false | false | 1,640 | r | Plot4.R |
d<-read.csv(file="household_power_consumption.txt",sep=';',stringsAsFactors=FALSE, dec=".")
d$Date<-as.Date(d$Date, format = "%d/%m/%Y")
fd<-subset(d,Date=="2007-02-01"|Date=="2007-02-02")
fd$datetime <-paste(fd$Date, fd$Time)
fd$datetime<-strptime(fd$datetime, "%Y-%m-%d %H:%M:%S")
fd$Global_active_power<-as.numeric(fd$Global_active_power)
fd$Sub_metering_1<-as.numeric(fd$Sub_metering_1)
fd$Sub_metering_2<-as.numeric(fd$Sub_metering_2)
fd$Sub_metering_3<-as.numeric(fd$Sub_metering_3)
fd$Voltage<-as.numeric(fd$Voltage)
fd$Global_reactive_power<-as.numeric(fd$Global_reactive_power)
##### Plot 4
png(filename = "Plot4.png",
width = 480, height = 480)
par(mfrow=c(2,2))
## top left
plot(fd$datetime,(fd$Global_active_power)
,type = "l"
,ylab="Global Active Power(kilowatts)"
,xlab=" ")
## top right
plot(fd$datetime,fd$Voltage
,type="l"
,ylab="Voltage"
,xlab="datetime")
## bottom left
plot(fd$datetime,fd$Sub_metering_1,type = "l",ylim=c(0,40),ylab="Energy sub meltering",xlab=" ")
par(new=T)
plot(fd$datetime,fd$Sub_metering_2,type = "l",col="red",ylim=c(0,40),ylab=" ",xlab=" ")
par(new=T)
plot(fd$datetime,fd$Sub_metering_3,type = "l",col="blue",ylim=c(0,40),,ylab=" ",xlab=" ")
legend("topright",legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3")
,lty=c(1,1)
,cex = 0.7
,lwd=c(2.5,2.5,2.5)
,col=c("black","blue","red")
,bty = "n" )
## bottom right
plot(fd$datetime,(fd$Global_reactive_power)
,type="l"
,ylab="Global_reactive_power"
,xlab="datetime")
dev.off()
|
dc805948b58372fb7b42a8e4c7711d7538719128 | 0a8e985c6a53f05b771451502e20627b39ef8115 | /cleandata/air_quality_clean.R | 4ee37110e0aaaa602d2c75fef1a42527967b2759 | [] | no_license | osiau/GIS713DataChallenge | e7637a7cbefc185a0f8c72dc50bb6dd573aaa869 | 8e305bfc04237c45dbed32e4823f38d42dbc074f | refs/heads/master | 2023-01-30T12:23:34.349407 | 2020-10-07T01:49:56 | 2020-10-07T01:49:56 | 322,170,942 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,548 | r | air_quality_clean.R |
# THIS SCRIPT gives you clean air quality data (not clean air quality though, unfortunately)
# The final clean data objects are: air_qual2019 and air_qual2020
# No calculation has been done on the air quality fields
library(data.table)
wd <- getwd()
# read
air_qual2019 <- read.csv(file.path(wd,"Datasources/air_quaity_annual_aqi_by_county_2019.csv"),stringsAsFactors=TRUE, header=TRUE)
air_qual2020 <- read.csv(file.path(wd,"Datasources/air_quality_annual_aqi_by_county_2020.csv"),stringsAsFactors=TRUE, header=TRUE)
data_states <- read.csv(file.path(wd,"Datasources/all_names_FIPS.csv"),stringsAsFactors=TRUE)
data_states <- as.data.table(data_states)
data_states <- data_states[,.(stateFIPS = as.factor(formatC(stateFIPS,width=2,flag="0")), countyFIPS=as.factor(formatC(countyFIPS,width=3,flag="0")), geoID=as.factor(formatC(geoID,width=5,flag="0")),county,state)]
# convert to data.table
air_qual2019 <- as.data.table(air_qual2019)
air_qual2020 <- as.data.table(air_qual2020)
# lowercase names
names(air_qual2019) <- tolower(names(air_qual2019))
names(air_qual2020) <- tolower(names(air_qual2020))
summary(data_states)
# adding codes to air quality
air_qual2019$state <- tolower(air_qual2019$state)
air_qual2019$county <- tolower(air_qual2019$county)
air_qual2019 <- merge(air_qual2019,data_states,by=c("state","county"))
air_qual2020$state <- tolower(air_qual2020$state)
air_qual2020$county <- tolower(air_qual2020$county)
air_qual2020 <- merge(air_qual2020,data_states,by=c("state","county"))
|
7d584b773bdf3237e463a6d80e813023b56bc1e3 | d92e24b978d924c3631ac9e34ad16d215e4484a4 | /CrudTest/app_new.R | 158654d2a67d21616ae8169abd84bc63c525f849 | [
"MIT"
] | permissive | Sumidu/dashboardtests | a98ab790ab8606662de41bde4a5e011ea2199301 | f6c23da50f1f297546ebdcc78c192ca94dde9200 | refs/heads/master | 2020-04-30T11:50:07.538680 | 2019-03-25T07:11:22 | 2019-03-25T07:11:22 | 176,812,099 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 781 | r | app_new.R | #
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(shinydashboard)
library(rhandsontable)
library(htmlwidgets)
library(dplyr)
library(DBI)
library(pool)
library(tidyverse)
source("modules/project_view.R")
source("view_sidebar.R")
source("view_body.R")
source("read_personal.R")
con <- dbConnect(RSQLite::SQLite(), "mydata.sqlite")
ui <- dashboardPage(
header = dashboardHeader(title = "Crud Test"),
sidebar = getSidebar(),
body = getBody()
)
server <- function(input, output, session) {
callModule(projectview,"overview")
}
# Run the application
shinyApp(ui = ui, server = server)
|
d9b2aa56edf09ca9eae0f64687d8f34cf482d3ef | 8372f94c022cd1b6b36c787d0a8336a19ff8279f | /plot2.R | 4fbb6944b19a74a856bf6050f0c8424468691eca | [] | no_license | Dweepobotee/ExData_Plotting1 | 44ce8329b540070d17165abb88d0bd71f87a0935 | a77f8f55ff918320b99297f0884cac791581259c | refs/heads/master | 2021-05-15T07:46:29.349340 | 2017-12-04T16:21:31 | 2017-12-04T16:21:31 | 109,470,035 | 0 | 0 | null | 2017-11-04T05:37:51 | 2017-11-04T05:37:50 | null | UTF-8 | R | false | false | 606 | r | plot2.R | ## Reading the data
hpc<-read.table("household_power_consumption.txt", header=TRUE, sep=';', na.strings="?",stringsAsFactors = F, dec = ".")
hpc$Date<-as.Date(hpc$Date, format="%d/%m/%Y")
data1<-subset(hpc, subset=(Date>="2007-02-01" & Date<="2007-02-02"))
rm(hpc)
## Creating the datetime variable
datetime<-paste(data1$Date, data1$Time)
data1$datetime<-as.POSIXct(datetime)
## Creating the plot
plot(data1$datetime, data1$Global_active_power, type="l", xlab="", ylab="Global Active Power(kilowatts)")
## Saving the plot
dev.copy(png, file="plot2.png", height=480, width=480)
dev.off()
|
a1e4af506c7bde96c5aa38c7fd06b4ded56d7353 | bf4dea5b896b89e14bac8ccfde707e67352208b6 | /src/ui/input_panels.R | fa926b7b78579c22cbf6fcf0f709658c1d4d0d9a | [
"MIT"
] | permissive | mrc-ide/shiny90 | 6afa140da681cf72f505c158bbf55db2ecaecdf4 | 4b8abb38cfc03e40bcaacc1987690b90c7f8fa36 | refs/heads/master | 2023-05-29T17:02:56.132104 | 2023-05-09T08:50:43 | 2023-05-09T08:50:43 | 146,604,625 | 2 | 0 | MIT | 2023-05-05T08:19:14 | 2018-08-29T13:32:42 | R | UTF-8 | R | false | false | 10,867 | r | input_panels.R | panelSurvey <- function() {
shiny::div("",
shiny::tags$p("Please provide survey data on the proportion of people ever tested by sex and age group, and HIV serostatus (if available).
Where available please provide the following:"),
shiny::tags$ul(
shiny::HTML("<li><strong>Country or region:</strong> Must exactly match country or region in top left panel.</li>"),
shiny::HTML("<li><strong>Survey Id:</strong> Provide a unique identifier for your survey (each survey must have a unique name).</li>"),
shiny::HTML("<li><strong>Year:</strong> Year in which survey was conducted; year of survey fieldwork
midpoint if survey spanned multiple years.</li>"),
shiny::HTML("<li><strong>Age Group:</strong> 15-24, 25-34, 35-49, 50+, 15-49 or 15+.</li>"),
shiny::HTML("<li><strong>Sex</strong> \"male\", \"female\" or \"both\".</li>"),
shiny::HTML("<li><strong>HIV Status:</strong> \"positive\", \"negative\" or \"all\".</li>"),
shiny::HTML("<li><strong>Estimate:</strong> Estimate for proportion ever tested for HIV; as a percentage (e.g. 87.6 rather than proportion 0.876).</li>"),
shiny::HTML("<li><strong>Standard Error:</strong> Standard Error of the estimate (as a percentage). Should take into account survey design effects.</li>"),
shiny::HTML("<li><strong>Lower Confidence Interval:</strong> Lower limit of the 95% confidence interval of the survey estimate (as a percentage).</li>"),
shiny::HTML("<li><strong>Upper Confidence Interval:</strong> Upper limit of the 95% confidence interval of the survey estimate (as a percentage).</li>"),
shiny::HTML("<li><strong>Counts:</strong> Unweighted counts of the number of survey respondents included in the stratification group.</li>")
),
shiny::tags$p("You can copy and paste from Excel or upload a new CSV file."),
shiny::tags$p("All columns are required. Where values are unknown, please just leave blank.
The app will not accept an uploaded CSV with the wrong headers. It may be
useful to download the headers as a template:"),
shiny::downloadButton("downloadSurveyTemplate", "Download CSV template", class = "mb-4"),
infoAlert("usePercentInfo", "Estimates, Standard Error and Lower and Upper Confidence Intervals should
all be given as percentages (for example, enter percentage 87.56 rather than proportion 0.8756)."),
shiny::h3("Upload new data"),
errorAlert(id = "wrongSurveyHeadersError",
condition = "output.wrongSurveyHeaders",
message = "Error: Invalid headers! Survey data must match the given column headers. This file has been ignored."),
errorAlert(id = "wrongSurveyCountryError",
condition = "output.wrongSurveyCountry",
message = "Error: You cannot upload survey data for a different country. This file has been ignored."),
shiny::fileInput("surveyData", "Choose CSV File", accept = c("text/csv","text/comma-separated-values,text/plain",".csv")),
shiny::h3("Or edit data in place"),
shiny::div("Hint: Select rows and use ctrl-c to copy to clipboard. Use ctrl-v to paste rows from excel.", class = "text-muted mb-1"),
rhandsontable::rHandsontableOutput("hot_survey")
)
}
panelProgram <- function() {
shiny::div("", class="mb-3",
shiny::tags$p("Please provide programmatic data sourced from national testing programs. For each year please
provide either sex aggregated data (1 row with sex = \"both\") or sex disaggregated data (2 rows with sex=\"male\" and sex=\"female\" respectively).
Where values are unknown, please just leave blank.
Where available please provide
the following:"),
shiny::tags$ul(
shiny::HTML("<li><strong>Country or region:</strong> Must exactly match country or region in top left panel.</li>"),
shiny::HTML("<li><strong>Year:</strong> Calendar year in which the HIV tests were performed.</li>"),
shiny::HTML("<li><strong>Total Tests:</strong> This is the annual number of tests performed at the national level among the population aged 15+ years of age.
This number should be equal to the total number of tests administered as part of HIV Testing and Counseling (HTC) and
during antenatal care (ANC), and for which the clients received the results.</li>"),
shiny::HTML("<li><strong>Total Positive Tests:</strong> Out of the total annual number of tests, how many were found to be HIV positive.
This number should be equal to the number of positive tests found during HTC (in non-pregnant population) and during ANC among
pregnant women.</li>"),
shiny::HTML("<li><strong>Total HTC Tests:</strong> Total annual number of tests performed in the population aged 15+ years outside of
ANC services,
and for which clients received the results.</li>"),
shiny::HTML("<li><strong>Total Positive HTC Tests</strong>: Annual number of tests that were found to be positive for HIV outside of ANC services.</li>"),
shiny::HTML("<li><strong>Total ANC Tests:</strong> Annual number of pregnant women tested for HIV (and that received their results) as part of ANC services.</li>"),
shiny::HTML("<li><strong>Total Positive ANC Tests:</strong> Annual number of pregnant women found to be HIV positive during ANC services.</li>"),
shiny::HTML("<li><strong>Sex:</strong> Male, female or both.</li>")
),
shiny::p("*A person should only be counted as testing once even if up to three different assays are performed to confirm an HIV-positive diagnosis according to the national testing algorithm.
A person who is tested twice during the year should be counted as contributing two tests."),
shiny::tags$p("You can copy and paste data from Excel into the table below or upload a CSV file."),
shiny::p("All columns are required. Where values are unknown, please just leave blank. The app will
not accept an uploaded CSV with the wrong headers. It may be useful to download the headers as a template:"),
downloadButton("downloadProgramTemplate", "Download CSV template"),
shiny::h3("Upload new data"),
errorAlert(id = "wrongProgramHeadersError", condition="output.wrongProgramHeaders",
message = "Error: Invalid headers! Program data must match the given column headers. This file has been ignored."),
errorAlert(condition="output.wrongProgramCountry", id="wrongProgramCountryError",
message="Error: You cannot upload program data for a different country. This file has been ignored."),
shiny::fileInput("programData", "Choose CSV File", accept = c("text/csv","text/comma-separated-values,text/plain",".csv")),
shiny::h3("Or edit data in place"),
shiny::div("Hint: Select rows and use ctrl-c to copy to clipboard. Use ctrl-v to paste rows from excel.", class = "text-muted mb-1"),
rhandsontable::rHandsontableOutput("hot_program")
)
}
panelReviewInput <- function() {
shiny::div("",
shiny::div("Here's a visualisation of the data you have uploaded so far.
Please review it, and go back and edit your data if anything doesn't look right.",
class = "mb-3"
),
shiny::div("", class="suggest-save mb-3",
shiny::span("Please save your work. This downloads a file containing your input data and results.
If you get disconnected from the server, or if you want to return to the app later
and review your results, you can re-upload this file and resume where you left off.")
),
shiny::div("", class="save-button",
downloadButtonWithCustomClass("digestDownload3", "Save your work",
font_awesome_icon = "download")
),
shiny::conditionalPanel(
condition = "output.invalidProgramData",
shiny::div("The programmatic data for your country is invalid. Please check the guidance and correct it.",
class = "mt-5 alert alert-danger", id="invalid-error")
),
shiny::conditionalPanel(
condition = "output.invalidSurveyData",
shiny::div("The survey data for your country is invalid. Please check the guidance and correct it.",
class = "mt-5 alert alert-danger", id="invalid-error")
),
shiny::conditionalPanel(
condition = "output.incompleteProgramData",
shiny::div("The programmatic data for your country is incomplete. Please fill in missing values if you have them.",
class = "mt-5 alert alert-warning", id="incomplete-warning")
),
shiny::div("", class = "row",
shiny::conditionalPanel(
condition = "output.anyProgramDataTot",
shiny::div("", class = "col-md-6 col-sm-12", shinycssloaders::withSpinner(plotOutput(outputId = "reviewTotalTests")))
),
shiny::conditionalPanel(
condition = "output.anyProgramDataTotPos",
shiny::div("", class = "col-md-6 col-sm-12", shinycssloaders::withSpinner(plotOutput(outputId = "reviewTotalPositive")))
)
),
shiny::div("", class = "row",
shiny::conditionalPanel(
condition = "output.anyProgramDataAnc",
shiny::div("", class = "col-md-6 col-sm-12", shinycssloaders::withSpinner(plotOutput(outputId = "reviewTotalANC")))
),
shiny::conditionalPanel(
condition = "output.anyProgramDataAncPos",
shiny::div("", class = "col-md-6 col-sm-12", shinycssloaders::withSpinner(plotOutput(outputId = "reviewTotalANCPositive")))
)
),
shiny::div("", class = "row",
shiny::div("", class = "col-md-6 col-sm-12", shinycssloaders::withSpinner(plotOutput(outputId = "reviewPrevalence"))),
shiny::div("", class = "col-md-6 col-sm-12", shinycssloaders::withSpinner(plotOutput(outputId = "reviewIncidence")))
),
shiny::div("", class = "row",
shiny::div("", class = "col-md-6 col-sm-12", shinycssloaders::withSpinner(plotOutput(outputId = "reviewTotalPop"))),
shiny::div("", class = "col-md-6 col-sm-12", shinycssloaders::withSpinner(plotOutput(outputId = "reviewPLHIV")))
)
)
# TODO: More plots when Jeff knows what's needed
}
|
cdea428803aed2862c576d63fd10326c96367b14 | de3f5864b44f6ba76807af0b1c9712e46cde590f | /summary_susie.R | dd30982819de54e95e7384b4567ed29ab01275e1 | [] | no_license | chr1swallace/coloc-susie-paper | 83c5ad461e56ad865b4d0c42f7fc61c04129138c | 3c1280508b4dafac75e69607970e753243f3b235 | refs/heads/main | 2023-06-27T01:04:18.748780 | 2021-08-03T09:34:39 | 2021-08-03T09:34:39 | 339,751,246 | 2 | 0 | null | null | null | null | UTF-8 | R | false | false | 23,982 | r | summary_susie.R | #!/home/cew54/localc/bin/Rscript
setwd("~/Projects/coloc-susie")
source("dirs.rb")
library(randomFunctions)
library(magrittr)
## args=getArgs(defaults=list(chr=2, begin=43082452, end=44086664), numeric=c("chr","begin","end"))
source("~/E/sim_colours.R")
## example with high LD between CVs (0.0.99)
## f="data/sim/coloc/_223c973ddcaff_255f719b075c4.RData"
library(pbapply)
dirs=list.files(SIMCOLOC,pattern="approx_",full=TRUE)
d=dirs[1]
for(d in dirs) {
files=list.files(d,full=TRUE) %>% grep("summary",.,value=TRUE,invert=TRUE)
message(basename(d),"\tfiles found: ",length(files))
}
library(ggplot2)
library(ggrastr)
library(data.table)
proc_file=function(f,d) {
(load(f))
result[,scenario:=basename(d)][,index:=paste(f,1:.N,sep="_")]
}
d=dirs[1]
DATA=vector("list",length(dirs))
names(DATA)=basename(dirs)
for(d in dirs) {
files=list.files(d,full=TRUE) %>% grep("summary",.,value=TRUE,invert=TRUE)
## if(length(files)>200)
## files=files[1:200]
f=files[1]
message(basename(d),"\tfiles found: ",length(files))
if(!length(files))
next
if(length(files)>1000)
files=sample(files,1000)
DATA[[ basename(d) ]] = lapply(files,proc_file,d=d) %>% rbindlist()
## scores[is.nan(spec.B),spec.B:=0]
## scores[is.nan(spec.A),spec.A:=0]
}
NPER_THR=1000
results=rbindlist(DATA)
with(results, table(scenario))
results[,nsnp:=as.numeric(sub("approx_","",scenario))]
head(results)
results[,base_nsets.out:=base_nsets-base_nsets.in]
results[,nsets.out:=nsets-nsets.in]
results[,diff_nsets.in:=nsets.in-base_nsets.in]
results[,diff_nsets.out:=nsets.out-base_nsets.out]
results[,pip.cv1:=sub("/.*","",cv.pip) %>% as.numeric()]
results[ncv==2,pip.cv2:=sub(".*/","",cv.pip) %>% as.numeric()]
results[,base_pip.cv1:=sub("/.*","",base_cv.pip) %>% as.numeric()]
results[ncv==2,base_pip.cv2:=sub(".*/","",base_cv.pip) %>% as.numeric()]
results[,z.cv1:=sub("/.*","",cv.z) %>% as.numeric()]
results[nsnp==1,z.cv2:=sub(".*/","",cv.z) %>% as.numeric()]
results[,.(n=.N,prop.same=mean(same_top)),by=c("ncv","nsnp","zthr")]
results[nsnp < 1000, nsnp:=1000 * nsnp]
results[,ncvscen:=ifelse(ncv==1, "single CV", "two CV")]
results[,snpscen:=paste(nsnp," SNPs")]
library(cowplot)
theme_set(theme_cowplot(font_size=10))
results[,sets_same:=nsets.in==base_nsets.in & nsets.out==nsets.out]
with(results, table(snpscen,ncvscen,zthr))
ggplot(results, aes(x=pipcr,fill=factor(zthr),col=factor(zthr))) +
geom_histogram(position="dodge",binwidth=0.05) +
scale_fill_seaborn("|Z| threshold for trimming") +
scale_colour_seaborn("|Z| threshold for trimming") +
background_grid(major="y") +
labs(x="Correlation between PIP before and after trimming",y="Count") +
theme(legend.position="bottom") +
## scale_y_log10() +
## scale_colour_seaborn("|Z| threshold for trimming") +
facet_grid(snpscen ~ ncvscen)
ggsave("~/Projects/coloc-susie/figure-pipcr.png",height=4,width=6)
## alternative time
mtime=results[,.(y=median(base_time+time_diff),ymax=quantile(base_time+time_diff,.75),ymin=quantile(base_time+time_diff,.25)),
by=c("zthr","nsnp","ncvscen")]
mtime=rbind(mtime, results[zthr==0.5,.(y=median(base_time), ymax=quantile(base_time,.75),ymin=quantile(base_time,.25),zthr=0),
by=c("nsnp","ncvscen")])
ggplot(mtime, aes(x=nsnp,y=y,ymin=ymin,ymax=ymax,col=factor(zthr))) +
geom_pointrange() +
geom_path(aes(group=factor(zthr))) +
facet_wrap(~ncvscen) +
scale_x_continuous(breaks=c(1000,2000,3000)) +
labs(x="Number of SNPs in region",y="Time (seconds)") +
scale_colour_seaborn("|Z| threshold for trimming") +
theme(legend.position="bottom") +
background_grid(major="y")
ggsave("~/Projects/coloc-susie/figure-time.png",height=4,width=6)
################################################################################
## all abandonned below here
m=rbind(results[,.(base_pip=base_pip.cv1,pip=pip.cv1,zthr,pipcr,snpscen,
ncvscen=ifelse(ncvscen=="single CV", ncvscen, paste(ncvscen, "(CV 1)")))],
results[ncvscen!="single CV",.(base_pip=base_pip.cv2,pip=pip.cv2,zthr,pipcr,snpscen,
ncvscen=ifelse(ncvscen=="single CV", ncvscen, paste(ncvscen, "(CV 2)")))])
with(m, table(snpscen,ncvscen,zthr))
ggplot(m, aes(x=base_pip,y=pip)) +
geom_abline() +
geom_point(alpha=0.1) +
facet_grid(factor(zthr) ~ ncvscen + snpscen)
## ggplot(m, aes(x=base_pip,y=pip)) +
## geom_abline() +
## geom_hex() +
## facet_grid(factor(zthr) ~ ncvscen + snpscen)
## ggplot(results, aes(x=base_pip.cv1,y=pip.cv1)) + #,col=factor(nsets.in==base_nsets.in & nsets.out==nsets.out)
## geom_abline(intercept=0,slope=1) +
## geom_point(alpha=0.1) +
## facet_grid(factor(zthr) ~ ncvscen + snpscen)
## ggplot(results, aes(x=base_pip.cv2,y=pip.cv2)) + #,col=factor(nsets.in==base_nsets.in & nsets.out==nsets.out)
## geom_abline(intercept=0,slope=1) +
## geom_point(alpha=0.1) +
## facet_grid(factor(zthr) ~ ncvscen + snpscen)
## ggplot(results, aes(x=max_pos_diff.noncv,y=min_neg_diff.noncv)) +#,col=factor(nsets.in==base_nsets.in & nsets.out==nsets.out))) +
## geom_abline() +
## geom_point(alpha=0.1) +
## facet_grid(factor(zthr) + factor(sets_same) ~ ncvscen + snpscen)
## results[,.(mse1=mean((pip.cv1-base_pip.cv1)^2),
## mse2=mean((pip.cv2-base_pip.cv2)^2)), by=c("zthr","ncvscen","snpscen")]
## ggplot(results,aes(x=base_tot+tot_diff)) + geom_histogram() + facet_wrap(~zthr)
## ggplot(results,aes(x=base_tot,y=tot_diff)) + geom_hex() + geom_smooth() +
## facet_wrap(~zthr)
## fill barchart
## library(cowplot)
## library(seaborn)
## m=melt(results, measure.vars=c("diff_nsets.in","diff_nsets.out"))
## head(m)
## ggplot(m, aes(x=value,fill=as.factor(zthr))) +
## geom_bar(position="dodge") +
## scale_fill_seaborn("|Z| threshold for trimming") +
## scale_colour_seaborn("|Z| threshold for trimming") +
## background_grid(major="y") +
## facet_grid(ncvscen + variable ~ snpscen)
## ggplot(m, aes(x=value,fill=variable)) +
## geom_bar(position="dodge") +
## scale_fill_seaborn("|Z| threshold for trimming") +
## scale_colour_seaborn("|Z| threshold for trimming") +
## background_grid(major="y") +
## facet_grid(ncvscen + factor(zthr) ~ snpscen)
## ggplot(results, aes(x=pip.cv1-base_pip.cv1,fill=factor(zthr))) +
## geom_histogram(position="dodge",aes(y=..density..)) +
## scale_fill_seaborn("|Z| threshold for trimming") +
## scale_colour_seaborn("|Z| threshold for trimming") +
## background_grid(major="y") +
## facet_grid(ncvscen + factor(diff_nsets.in==0) ~ snpscen)
## bivariate plot
library(cowplot)
library(ggExtra)
library(viridis)
p=ggplot(results[zthr>0], aes(x=pcv_diff,y=pnocv_diff)) + #,col=pnocv_diff)) +
## geom_hex(binwidth=c(0.01/21,2/11),colour="grey") +
## geom_bin2d(binwidth=c(0.018/17,4/19),colour="grey") +
## geom_hline(yintercept=0) + geom_vline(xintercept=0,width=0.1) +
geom_jitter(alpha=0.01) +
## geom_point(colour="transparent") +
## geom_density2d(alpha=0.2) +
background_grid() +
geom_rug(aes(x=pcv_diff,y=pcv_diff),alpha=0.01,data=results) +
scale_colour_viridis() +
scale_fill_viridis() +
facet_grid(ncvscen + zthr ~ snpscen)
p
## https://www.r-bloggers.com/2014/05/finding-the-midpoint-when-creating-intervals/
midpoints <- function(x){
lower <- as.numeric(gsub(",.*","",gsub("\\(|\\[|\\)|\\]","", x)))
upper <- as.numeric(gsub(".*,","",gsub("\\(|\\[|\\)|\\]","", x)))
lower+(upper-lower)/2
}
min(results$pnocv_diff)
max(results$pnocv_diff)
min(results$pcv_diff)
max(results$pcv_diff)
## results[,xbin:=cut(pnocv_diff,breaks=seq(-0.009,0.009,length.out=40),include.lowest=TRUE)]
results[,xbin:=cut(pnocv_diff,breaks=seq(-20,20,length.out=80),include.lowest=TRUE)]
results[,ybin:=cut(pcv_diff,breaks=seq(-2,2,length.out=20),include.lowest=TRUE)]
m=results[zthr > 0,.(n=.N),by=c("xbin","ybin","ncvscen","zthr","snpscen")]
m[,pc:=100*n/sum(n),by=c("ncvscen","zthr","snpscen")]
m[,x:=midpoints(xbin)]
m[,y:=midpoints(ybin)]
msub=m[ncvscen=="two CV" & snpscen=="1000 SNPs"]
ggplot(msub[zthr>0]) + #,col=pnocv_diff)) +
## geom_hex(binwidth=c(0.01/21,2/11),colour="grey") +
geom_tile(aes(x=x,y=y,fill=pc),colour="grey") +
geom_text(aes(x=x,y=y,label=round(pc),colour=100-pc),data=msub[zthr>0]) +
## geom_hline(yintercept=0) + geom_vline(xintercept=0,width=0.1) +
## geom_jitter(alpha=0.01) +
## geom_point(colour="transparent") +
## geom_density2d(alpha=0.2) +
background_grid() +
## geom_rug(aes(x=pnull_diff,y=pcv_diff),alpha=0.02,data=results[zthr>0]) +
scale_fill_viridis("percent") +
scale_colour_viridis("percent",guide=FALSE) +
facet_grid(ncvscen + zthr ~ snpscen) +
theme(legend.position="bottom")
for(isnp in c(1000,2000,3000)) {
plots=lapply(c("single CV","two CV"), function(incv) {
lapply(c(0.5,1,1.5), function(izthr) {
msub=m[ncvscen==incv & snpscen==paste0(isnp," SNPs")]
show_legend = izthr==0.5
show_xlab = izthr==1.5
show_ylab = incv=="single CV"
p=ggplot(msub[zthr==izthr]) + #,col=pnocv_diff)) +
geom_tile(aes(x=x,y=y,fill=pc),colour="grey") +
geom_text(aes(x=x,y=y,label=round(pc,1),colour=100-pc)) +
geom_point(aes(x=pnocv_diff,y=pcv_diff),colour="transparent",
data=results[ncvscen=="two CV" & snpscen=="1000 SNPs" & zthr==izthr]) +
scale_fill_viridis("percent") +
scale_colour_viridis("percent",guide=FALSE) +
labs(x=if(show_xlab) { "Change in total PP at non-causal variants" } else { "" },
y=if(show_ylab) { "Change in total PP at causal variants" } else { "" }) +
ggtitle(paste0(incv,", |Z| threshold = ",izthr)) +
theme_cowplot(font_size=10) +
background_grid() +
theme(legend.position="none",#if(show_legend) {c(1,1)} else { "none" },
legend.justification=c("left","bottom"),
legend.direction="horizontal",
plot.title=element_text(face="bold"))
ggMarginal(p,size=10)
})
}) %>% do.call("c",.)
pgrid=plot_grid(plotlist=plots,ncol=2,align="hv",axis="xy",byrow=FALSE)
## save_plot(paste0("pipgrid-",isnp,".png"),plot=pgrid,base_height=10,base_width=8)
ggsave(paste0("figure-pipgrid-",isnp,".png"),plot=pgrid,height=10,width=8,units="in")
}
## univariate plots
m=melt(results,c("nsnp","ncv","zthr"),list(c("pip.cv1","pip.cv2"),c("z.cv1","z.cv2"),c("base_pip.cv1","base_pip.cv2")))
setnames(m,c("variable","value1","value2","value3"),c("cv","pip","z","base_pip"))
with(m,table(ncv,cv))
m=m[!is.na(pip) & as.numeric(cv) <= as.numeric(ncv)]
m[,pip_diff:=pip-base_pip]
head(m)
m[,cvscen:=ifelse(ncv==1, "single CV", paste("two CV, variant",cv))]
m[,ncvscen:=ifelse(ncv==1, "single CV", "two CV")]
results[,ncvscen:=ifelse(ncv==1, "single CV", "two CV")]
m[,snpscen:=paste(nsnp," SNPs")]
results[,snpscen:=paste(nsnp," SNPs")]
## ggplot(m,aes(x=base_pip,y=pip,col=factor(zthr),size=abs(z))) +
## geom_point() +
## geom_smooth() +
## facet_grid(nsnp ~ ncv + cv, labeller=label_both)
results[,ptot_diff:=pnocv_diff+pcv_diff+pnull_diff]
## ggplot(results,aes(x=base_pnull,y=base_pnull+pnull_diff,col=factor(zthr))) +
## geom_point() +
## geom_smooth() +
## facet_grid(nsnp ~ ncv, labeller=label_both)
library(cowplot); theme_set(theme_cowplot(font_size=10))
library(seaborn)
library(ggridges)
plots=list(
pnull=ggplot(results, aes(y=factor(zthr),x=pnull_diff,fill=factor(zthr),col=factor(zthr))) +
geom_vline(xintercept=0,linetype="dashed") +
## geom_density_ridges(stat = "density", aes(height = stat(density)), col="grey") +
labs(x="Pr(null) in trimmed - Pr(null) in full data")
,time= ggplot(results, aes(y=factor(zthr),x=time_diff+base_time,fill=factor(zthr),col=factor(zthr))) +
geom_vline(xintercept=0,linetype="dashed") +
## geom_density_ridges(stat = "density", aes(height = stat(density)), col="grey") +
labs(x="Time to run SuSiE")
,max_pos_diff=ggplot(results, aes(y=factor(zthr),x=max_pos_diff.noncv,fill=factor(zthr),col=factor(zthr))) +
geom_vline(xintercept=0,linetype="dashed") +
## geom_density_ridges(stat = "density", aes(height = stat(density)), col="grey") +
labs(x="Max PIP difference excluding CV")
,min_neg_diff=ggplot(results, aes(y=factor(zthr),x=min_neg_diff.noncv,fill=factor(zthr),col=factor(zthr))) +
geom_vline(xintercept=0,linetype="dashed") +
## geom_density_ridges(stat = "density", aes(height = stat(density)), col="grey") +
labs(x="Min PIP difference excluding CV")
,totdiff=ggplot(results, aes(y=factor(zthr),x=ptot_diff,fill=factor(zthr),col=factor(zthr))) +
geom_vline(xintercept=0,linetype="dashed") +
## geom_density_ridges(stat = "density", aes(height = stat(density)), col="grey") +
labs(x="Bias in PIP excluding CV")
,nocvdiff=ggplot(results, aes(y=factor(zthr),x=pnocv_diff,fill=factor(zthr),col=factor(zthr))) +
geom_vline(xintercept=0,linetype="dashed") +
## geom_density_ridges(stat = "density", aes(height = stat(density)), col="grey") +
labs(x="Bias in PIP excluding CV")
,cvdiff=ggplot(results, aes(y=factor(zthr),x=pcv_diff,fill=factor(zthr),col=factor(zthr))) +
geom_vline(xintercept=0,linetype="dashed") +
## geom_density_ridges(stat = "density", aes(height = stat(density)), col="grey") +
labs(x="Bias in PIP excluding CV")
,nulldiff=ggplot(results, aes(y=factor(zthr),x=pnull_diff,fill=factor(zthr),col=factor(zthr))) +
geom_vline(xintercept=0,linetype="dashed") +
## geom_density_ridges(stat = "density", aes(height = stat(density)), col="grey") +
labs(x="Bias in PIP excluding CV")
,pipcr=ggplot(results, aes(y=factor(zthr),x=pipcr,fill=factor(zthr),col=factor(zthr))) +
geom_vline(xintercept=1,linetype="dashed") +
## geom_density_ridges(stat = "density", aes(height = stat(density)), col="grey") +
labs(x="Correlation between PIP")
,pip=ggplot(m, aes(y=factor(zthr),x=pip_diff,fill=factor(zthr),col=factor(zthr))) +
geom_vline(xintercept=0,linetype="dashed") +
labs(x="Difference in PIP at causal variants"))
plotsplus = lapply(plots,function(p)
p + geom_density_ridges(stat = "binline", scale=0.95,bins=21, draw_baseline = FALSE) +
scale_fill_seaborn("|Z| threshold for trimming") +
scale_colour_seaborn("|Z| threshold for trimming") +
background_grid(major="y") +
ylab("|Z| threshold") +
theme(legend.position="bottom") +
facet_grid(ncvscen ~ snpscen,space="free"))
msum=m[,.(mid=paste0(100*round(mean(abs(pip_diff)<0.1),2),"%")),
by=c("cvscen","snpscen","zthr")]
plotsplus$pip =
plotsplus$pip +
geom_text(aes(label=mid,y=zthr*2+1.5),x=0.5,data=msum) +
facet_grid(cvscen ~ snpscen, space="free") +
scale_x_continuous(breaks=c(-1,0,1))
## stand alone
## plotsplus$time
plotsplus$pip
ggsave("~/Projects/coloc-susie/figure-pipdiff.png",plot=plotsplus$pip,height=6,width=6)
## other diagnostics
plotlist=plotsplus[c("pnull","pipcr")]
plotlist[1] %<>% lapply(., function(p) p + theme(legend.position="none"))
plot_grid(plotlist=plotlist[],ncol=1)
ggsave("~/Projects/coloc-susie/figure-otherdiagnostics.png",height=8,width=6)
plotlist=plotsplus[c("max_pos_diff","min_neg_diff","bias")]
plotlist=plotsplus[c("totdiff","cvdiff","nocvdiff","nulldiff")]
plot_grid(plotlist=plotlist[],ncol=1)
library(MASS)
library(ggplot2)
library(viridis)
## theme_set(theme_bw(base_size = 16))
# Get density of points in 2 dimensions.
# @param x A numeric vector.
# @param y A numeric vector.
# @param n Create a square n by n grid to compute density.
# @return The density within each square.
get_density <- function(x, y, ...) {
dens <- MASS::kde2d(x, y, ...)
ix <- findInterval(x, dens$x)
iy <- findInterval(y, dens$y)
ii <- cbind(ix, iy)
return(dens$z[ii])
}
results[zthr>0,dens:=get_density(x=pnull_diff, y=pcv_diff, n=100), by=c("ncvscen","zthr","snpscen")]
## results[zthr>0,dens:=dens/max(dens), by=c("ncvscen","zthr","snpscen")]
ggplot(results[zthr>0][order(dens)], aes(x=pnull_diff,y=pcv_diff,col=dens)) +
## geom_hex() +
## geom_hline(yintercept=0) + geom_vline(xintercept=0,width=0.1) +
geom_point(alpha=1,size=5) +
## geom_density2d(alpha=0.2) +
background_grid() +
scale_colour_viridis() +
facet_grid(ncvscen + zthr ~ snpscen, space="free")
## alternative time
## ggplot(results, aes(x=factor(nsnp),y=base_time + time_diff,col=factor(zthr))) +
## geom_boxplot() +
## facet_wrap(~ncv,labeller=label_both) +
## background_grid(major="y")
library(ggridges)
ggplot(results, aes(y=factor(zthr),x=max_abs_diff,fill=factor(zthr),col=factor(zthr))) +
geom_vline(xintercept=0,linetype="dashed") +
## geom_density_ridges(stat = "density", aes(height = stat(density)), col="grey") +
geom_density_ridges(stat = "binline", scale=0.95,bins=20, draw_baseline = FALSE,
## point_size = 0.4, point_alpha = 1,
## position = position_raincloud(adjust_vlines = TRUE)) +
) +
scale_fill_seaborn("|Z| threshold for trimming") +
scale_colour_seaborn("|Z| threshold for trimming") +
background_grid(major="y") +
labs(x="Maximum absolute difference in ppi",y="|Z|") +
background_grid(major="y") +
facet_grid(nsnp ~ ncv, labeller=label_both,space="free",scales="free_x")
library(ggridges)
ggplot(results, aes(x=factor(nsnp*1000),y=max_abs_diff,group=factor(nsnp))) +
geom_boxplot() +
facet_grid(ncv ~ zthr, labeller=label_both)
ggplot(results, aes(x=base_pnull,y=pnull_diff+base_pnull)) +
geom_abline(),
geom_point(alpha=0.1) + geom_density2d() +
facet_grid(ncv + nsnp ~ zthr, labeller=label_both)
ggplot(results, aes(x=base_time,y=time_diff+base_time)) +
geom_abline() +
geom_point(alpha=0.1) + geom_density2d() +
facet_grid(ncv + nsnp ~ zthr, labeller=label_both)
m=melt(results, measure.vars=list(pnull=c("pnull.trim","pnull.notrim"),
time=c("time.trim.elapsed","time.notrim.elapsed")))
m[,trim:=c("trim","notrim")[variable]]
head(m)
tail(m)
library(viridis)
library(ggplot2)
library(ggpubr)
library(cowplot); theme_set(theme_cowplot(font_size=10,line_size=0.3))
library(seaborn)
ggplot(m, aes(x=factor(nsnps),y=time,col=trim)) +
geom_boxplot() +
labs(x="Number of SNPs in region",y="Elapsed time (seconds)")
ggplot(results, aes(x=pnull.notrim,y=pnull.trim,col=factor(ncv))) +
geom_point() +
geom_smooth() +
facet_wrap(~factor(nsnps)) +
labs(x="P(null), full data",y="P(null), trimmed data")
ggplot(results, aes(x=as.factor(ncv),y=cor,col=factor(nsnps))) +
geom_boxplot() +
scale_colour_seaborn("Number of SNPs in region") +
labs(x="Number of causal SNPs in region",y="Correlation between PPI") +
theme(legend.position="bottom")
ggplot(results, aes(x=as.factor(ncv),y=MSE,col=factor(nsnps))) +
geom_boxplot(outlier.size=0.5) +
scale_colour_seaborn("Number of SNPs in region") +
labs(x="Number of causal SNPs in region",y="Mean sq error between PPI") +
theme(legend.position="bottom")
ggplot(results, aes(x=as.factor(ncv),y=nsnps*MSE,col=factor(nsnps))) +
geom_boxplot(outlier.size=0.5) +
scale_colour_seaborn("Number of SNPs in region") +
labs(x="Number of causal SNPs in region",y="Sum of sq error between PPI") +
theme(legend.position="bottom")
ggsave("~/susie_approx.png",width=6,height=6)
## ## plot average posterior by n
## kk <- results[!is.na(H0) & n<=4, .(H0=sum(H0),H1=sum(H1),H2=sum(H2),H3=sum(H3),H4=sum(H4)),
## by=c("scenario","method","n","rsq")]
## m <- melt(kk,c("scenario","method","n","rsq"))
## m[,method:=factor(method,levels=c("single","cond","mask","susie"))]
## p.r <- ggplot(m,aes(x=n,y=value/(NPER*n),fill=variable)) + geom_col() +
## facet_grid(method ~ scenario + rsq,space="free_x",scales="free_x") + theme_pubr() +
## scale_fill_viridis_d("hypoth.") +
## ylab("Avg. posterior") +
## xlab("Tested variants") +
## theme(legend.position="right",
## panel.border=element_rect(linetype="solid",fill=NA)
## ##, strip.text.y = element_blank()
## )
## p.rr
kk <- results[!is.na(H0), .(H0=sum(H0),H1=sum(H1),H2=sum(H2),H3=sum(H3),H4=sum(H4)),
by=c("scenario","method","tested.cv","rsq")]
m <- melt(kk,c("scenario","method","tested.cv","rsq"))
m[,method:=factor(method,levels=c("single","cond","mask","susie"))]
p.r <- ggplot(m,aes(x=tested.cv,y=value/NPER,fill=variable)) + geom_col() +
facet_grid(method ~ scenario + rsq,space="free_x",scales="free_x") + theme_pubr() +
scale_fill_viridis_d("hypoth.") +
ylab("Avg. posterior") +
xlab("Tested variants") +
background_grid(major="y") +
theme(legend.position="right",
panel.border=element_rect(linetype="solid",fill=NA)
##, strip.text.y = element_blank()
)
## p.r
bottomline <- ggplot(m[rsq=="[0,0.5]"],aes(x=tested.cv,y=value/NPER,fill=variable)) + geom_col() +
facet_grid(method ~ scenario,space="free_x",scales="free_x") + theme_pubr() +
scale_fill_viridis_d("hypoth.") +
ylab("Avg. posterior") + ylim(0,1) +
xlab("Tested variant pairs") +
background_grid(major="y") +
theme(legend.position="right",
panel.border=element_rect(linetype="solid",fill=NA)
, strip.text.x = element_blank()
)
## bottomline
## plot number of tests per result
kk=results[,.(n=.N),by=c("index","scenario","method")]
table(kk$n)
kk[n>4,n:=5]
bottom_n=ggplot(kk, aes(x=n)) +
geom_histogram(binwidth=1,fill="grey40",colour="grey80") +
scale_x_continuous(breaks=c(1,2,3,4,5),labels=c("1","2","3","4","5+")) +
facet_grid(method ~ scenario) + theme_pubr() +
background_grid(major="y") +
theme(legend.position="right",
panel.border=element_rect(linetype="solid",fill=NA)
, strip.text.x = element_blank()
)
################################################################################
## four plots
RELATIONS=list(sim_0_0=data.table(from=c("trait 1","trait 2"),to=c("A","B")),
"sim_1_-1"=data.table(from=c("trait 1","trait 2"),to=c("A","A")),
sim_1_0=data.table(from=c("trait 1","trait 2","trait 2"),to=c("A","B","A")),
sim_1_1=data.table(from=c("trait 1","trait 2","trait 1","trait 2"),
to=c("A","A","B","B")))
library(cowplot)
theme_set(theme_cowplot(font_size=28))
library(seaborn)
simCols <- seaborn:::SEABORN_PALETTES$pastel[c(6,8,1)] # 8 is grey
library(igraph)
nodes=data.table(name=c("A","B","trait 1","trait 2"),
x=c(-1,1,-1,1),
y=c(-1,-1,1,1),
col=simCols[c(1,1,3,3)], #cols[c(2,10,10,10,10,2,4)],
class=c("variant","variant","trait","trait"),
stringsAsFactors=FALSE)
plotter=function(tag) {
relations=RELATIONS[[tag]]
rdf=merge(relations,nodes[,.(name,x,y)],by.x="from",by.y="name")
rdf <- merge(rdf,nodes[,.(name,x,y,col)],by.x="to",by.y="name",suffixes=c(".from",".to"))
rdf[,col:=simCols[2]][,row:="row"][,column:="column"]
cscale <- structure(unique(c(nodes$col,rdf$col)),names=unique(c(nodes$col,rdf$col)))
ggplot(nodes, aes(x=x,y=y)) +
geom_segment(aes(x=x.from,y=y.from,xend=x.to,yend=y.to,col=col),data=rdf,size=1) +
geom_point(aes(colour=col,size=class),pch=20) +
geom_text(aes(label=name)) +
## xlim(0,3) + ylim(1.9,3.5) +
scale_colour_manual(values=cscale) +
scale_size_manual(values=c(trait=22,variant=12)) +
xlim(-1.6,1.6) + ylim(-1.2,1.5) +
facet_grid(row ~ column) +
## ggtitle(patterns$match[i]) +
theme(legend.position="none",axis.line=element_blank(),
axis.title=element_blank(),
panel.border=element_rect(linetype="solid",fill=NA),
strip.text.x = element_blank(),
strip.text.y = element_blank(),
axis.ticks=element_blank(), axis.text=element_blank())
}
topplots=lapply(names(RELATIONS),plotter)
w=1.5
topline=plot_grid(plotlist=list(NULL,topplots[[1]],NULL,topplots[[2]],NULL,topplots[[3]],NULL,topplots[[4]],NULL),
nrow=1,rel_widths=c(1,w,1,w,1,w,2,w,2.5))
## plot_grid(topline,bottomline,bottom_n,ncol=1,rel_heights=c(.2,.8,.5))
both=plot_grid(topline,bottomline,rel_heights=c(.2,.8),ncol=1)
## both
ggsave("~/coloc_susie.png",both,height=7,width=14)
|
dc5d3730534719c8eccc57bac666869cf345d1cc | a114996ecfdd212ea60e54238a24b3bf51112b13 | /Problems/Problem58.R | c2c54d9849e55146475aef47632d0cf19a9becff | [] | no_license | Adam-Hoelscher/ProjectEuler.R | 35610697d5bc4c61e9adfaec6d923a424df20486 | e060484365cafcfcd400c3cecacc189293dfc682 | refs/heads/master | 2021-01-23T01:29:54.585429 | 2017-09-11T18:28:46 | 2017-09-11T18:28:46 | 102,432,553 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 906 | r | Problem58.R | Problem58 <- function(){
pos <- 1L
width <- 2L
prime <- 0L
total <- 1L
repeat {
for (i in 1L:3L){
pos <- (pos + width)
if (Functions$IsPrime(pos)) prime <- prime + 1L
}
#we know this one isn't prime; it's a perfect square
pos <- (pos + width)
total <- total + 4L
if (prime * 10 < total) return (width + 1L)
width <- (width + 2L)
}
}
# Problem58 <- function(){
#
# string <- c(3L, 5L, 7L, 9L)
# step <- 2L
# testPs <- Functions$IsPrime(string)
# # check <- sum(testPs)/length(testPs)
#
# while ( (10*sum(testPs)) > length(testPs) ) {
# step <- (step + 2L)
# new <- max(string) + step * (1L:4L)
# string <- c(string, new)
# testPs <- c(testPs, Functions$IsPrime(new))
# # check <- sum(testPs)/length(testPs)
# }
#
# return(step + 1L)
# }
# debug(Problem58)
# print(system.time(print(Problem58())))
|
be2c37ab66561014bbcfbe992d1db7780a344630 | 89605002f363e92e2144dcecc4a46d5e407ccbda | /6/demo/server.R | 573754f0f1930858128603368b358471eb9d10af | [] | no_license | da-okazaki/jenkins | 9b2bca4d83372e126171bc5937df6d00e8ab5bcd | e96b5e9694354e0e1ecd51c96ffa0193702bc8ac | refs/heads/master | 2020-05-17T12:43:02.756276 | 2019-04-27T02:17:48 | 2019-04-27T02:17:48 | 183,717,583 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 5,665 | r | server.R | shinyServer(
function(input, output, session) {
output$contents <- renderTable({
# input$file will be NULL initially. After the user selects
# and uploads a file, it will be a data frame with 'name',
# 'size', 'type', and 'datapath' columns. The 'datapath'
# column will contain the local filenames where the data can
# be found.
inFile <- input$file
if (is.null(inFile))
return(NULL)
if(1){
inFile <- input$file
if (is.null(inFile))
return(NULL)
#data <- read.csv(inFile$datapath, header=input$header, sep=input$sep,
# quote=input$quote)
data <- read.csv(inFile$datapath, header=TRUE)
x<-data$Day
y<-data$Number
x<-data$Day
y<-data$Number
print(x)
max_x<-length(x)
max_y<-length(y)
RSS_array<-c(1:max_x)
RSS_array<-RSS_array-RSS_array
parameter_array<-c(1:max_x)
parameter_array<-parameter_array-parameter_array
filename<-"data/sample"
data<-cbind(x,y)
plot(data,xlim=c(0,x[max_x]*2), ylim=c(0, y[max_y]*2))
Sys.sleep(1)
x_axis<-seq(0,x[max_x]*2)
for(i in 4:max_x){
tmpfilename<-paste("data/",i)
tmpfilename<-paste(tmpfilename,".txt")
tmppictname<-paste(filename,i)
tmppictname<-paste(tmppictname,".png")
tmpx<-x[0:i]
tmpy<-y[0:i]
print(i)
ansans<-try(ansans<-nls(tmpy~SSlogis(tmpx,A,B,C),trace=TRUE,control=nls.control(warnOnly=TRUE)))
cat("Ans\n")
if(class(ansans)!="try-error"){
print(ansans)
print("end")
parameter<-ansans$m$getPars()
parameter_array[i]=parameter[1]
print(parameter)
result<-summary(ansans)
predict.c <- predict(ansans,list(tmpx = x_axis))
#Save Graph start
#png(tmppictname)
#plot(data,xlim=c(0,x[max_x]), ylim=c(0, y[max_y]), xlab="Day", ylab="# of Issues" )
#lines(x_axis,predict.c)
#abline(v=x[i])
#abline(h=parameter_array[i])
#dev.off()
#Save Graph end
RSS_predict <- predict(ansans,list(tmpx = x))
RSS<-sum((y-RSS_predict)^2)
RSS_array[i]<-RSS
#Save plot data as csv
predicted_data <- data.frame(x_axis,predict.c)
write.csv(predicted_data,file=tmpfilename)
}
}
#Save Graph start
plot.new()
png("data/Plot.png")
plot(data,xlim=c(0,x[max_x]), ylim=c(0, y[max_y]*1.5), xlab="Day", ylab="# of Issues" )
lines(x_axis,predict.c)
dev.off()
#Save Graph end
#The Data for Behavier of RSS
RSS_summary<-data.frame(x,RSS_array)
frame()
plot.new()
png("data/RSS.png")
plot(RSS_summary, type="l" , xlab="Day", ylab="# of Issues" )
abline(h=y[max_y])
dev.off()
write.csv(RSS_summary, file="data/RSS.csv")
#The Data for Behavier of Predicted number of Issues
param_summary<-data.frame(x,parameter_array)
frame()
plot.new()
png("data/Predicted_Issues.png")
plot(param_summary, type="l", xlab="Day", ylim=c(0, y[max_y]*1.5), ylab="# of Predicted Issues" )
abline(h=y[max_y])
dev.off()
write.csv(param_summary, file="data/Predicted_Issues.csv")
print(ansans)
print("end")
}
read.csv(inFile$datapath, header=TRUE)
})
output$plot1 <- renderPlot({
inFile <- input$file
if (is.null(inFile))
return(NULL)
data <- read.csv(inFile$datapath, header=TRUE)
plot(data)
x<-data$Day
y<-data$Number
file_number <- input$animation
#persentage to integer
max_x <- length(x)
number <- as.integer(file_number/100 * max_x)
read_file_name <- paste("data/", number)
read_file_name <- paste(read_file_name,".txt")
if(file.exists(read_file_name)){
Predicted_data <- read.csv(read_file_name, header=TRUE)
tmpPX <- Predicted_data$x_axis
tmpPY <- Predicted_data$predict.c
data <- data.frame(tmpPX,tmpPY)
lines(data,type="l")
abline(v=x[number])
abline(h=tmpPY[length(tmpPY)])
} else {
while(!file.exists(read_file_name)){
number <- number + 1
read_file_name <- paste("data/", number)
read_file_name <- paste(read_file_name,".txt")
}
print(read_file_name)
Predicted_data <- read.csv(read_file_name, header=TRUE)
tmpPX <- Predicted_data$x_axis
tmpPY <- Predicted_data$predict.c
data <- data.frame(tmpPX,tmpPY)
lines(data,type="l")
abline(v=x[number])
abline(h=tmpPY[length(tmpPY)])
}
})
output$plot2 <- renderPlot({
inFile <- input$file
if (is.null(inFile))
return(NULL)
data <- read.csv(inFile$datapath, header=TRUE)
if(file.exists("data/Predicted_Issues.csv")){
print("exits")
Predicted_data <- read.csv("data/Predicted_Issues.csv", header=TRUE)
tmpPX <- Predicted_data$x
tmpPY <- Predicted_data$parameter_array
print(tmpPX)
print(tmpPY)
data <- data.frame(tmpPX,tmpPY)
}
plot(data, type = "l")
})
}) |
e18b79a8764afc74e9ff47cfea255bd802da94f2 | 2465aa63e2f856b93d11cb75db5ebadfc738127f | /man/gcs_dir.Rd | 06cacacb01c5a9ef1bad2c5a2885048494fcc099 | [] | no_license | nturaga/GCSConnection | 078b6554afafbce5d1ff6ade437c39632ee24c0a | 91abb4d6d3e126174d32a54ef1983a53a866ba75 | refs/heads/master | 2022-11-09T09:38:59.255586 | 2020-06-19T14:49:24 | 2020-06-19T14:49:24 | 271,274,526 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,379 | rd | gcs_dir.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/cloud-functions.R
\name{gcs_dir}
\alias{gcs_dir}
\title{List bucket/folder/object}
\usage{
gcs_dir(path, delimiter = TRUE, user_pay = gcs_get_user_pay())
}
\arguments{
\item{path}{character(1), the path to the bucket/folder/file.}
\item{delimiter}{Logical(1), whether to use `/` as a path
delimiter. If not, the path will be treated as the path to a
file even when it ends with `/`}
\item{user_pay}{logical(1). Whether users should be responsible
for the cost associated with accessing the data. If the value
is `TRUE`, the charge will be sent to the billing project. See
`?gcs_get_billing_project()` for more details.}
}
\value{
`FolderClass` object or a `FileClass` object
}
\description{
list objects in a bucket/folder or get the description of a file.
You can change the current direction via `[[` or `$` operator. `..`
can be used to go to the parent folder. For reducing the number of
request sent to the network, it is recommended to add a trailing
slash if the path is a folder.
}
\examples{
## List files in a bucket
## Equivalent: gcs_dir(path = "gs://genomics-public-data/")
gcs_dir(path = "genomics-public-data/")
## List files in a folder
gcs_dir(path = "genomics-public-data/clinvar/")
## List the information of a file
gcs_dir(path = "genomics-public-data/clinvar/README.txt")
}
|
c11baceef6b793adf5dcbd59ea0c939c6a7c9b58 | 13c7670d460f72d4c3cd55b1f351ac2ef6eea8b6 | /Limpeza_Inspecao_Workspace.R | 5e09e2916f77125688fb63663c973f7990858203 | [] | no_license | metodosexatos/ccr | d5a0c9415e7a867db9665a3254521a8caf1d5a99 | 98277a8317d224d53ea29f6191ecc5f2e93b26b8 | refs/heads/master | 2020-05-02T16:53:28.429059 | 2019-03-31T14:24:13 | 2019-03-31T14:24:13 | 178,081,835 | 0 | 0 | null | null | null | null | ISO-8859-1 | R | false | false | 1,586 | r | Limpeza_Inspecao_Workspace.R | #########################
##### Métodos Exatos ####
# www.metodosexatos.com #
#########################
# Autor: André Santos | andre@metodosexatos.com.br
# 04/03/2019
# citation()
# To cite R in publications use:
# R Core Team (5018). R: A language and environment for statistical
# computing. R Foundation for Statistical Computing, Vienna,
# Austria. URL https://www.R-project.org/.
#####################################################################
# Limpeza e inspeção do ambiente R
#- Comandos para inspecionar o ambiente R:
ls() # listar os objetos atuais no ambiente do R
getwd() # ver o diretório atual
# selecionar o diretório de trabalho:
setwd("C:/Users/andre/OneDrive/Documentos/PROJETOS/Metodos Exatos/Cursos/Curso6_Bioestatistica_com_R_Trilha/6.02_Curso_Computacao_com_R/Scripts_R_Curso_Computacao_com_R")
list.files(getwd())
#- Comandos limpar o ambiente de trabalho
# Crtl + l # limpa o Console do R
rm(var1, var2) # remover os objetos selecionados
rm(list = ls()) # remove todos os objetos
# Tipos de ajuda no R
help(mean) # Ajuda sobre uma função específica
?mean # Ajuda sobre uma função específica
example(mean) # Demonstra como utilizar a função
demo(graphics) # Demonstração de gráficos no R
demo() # Retorna uma lista de demonstrações disponíveis
apropos("mea") # Retorna uma lista de opções com a palavra
help.search("mean") # Pesquisa manuais do R no sistema
help.start() # Fornece referencias de materiais na web
|
44c4b7cbdbde6802f4a19fc321a201326ef5f97c | 016bbbbfbda258147cfa675b69f3c4a4a64f0c67 | /R/mb_delta_estimation.R | 9277f6e4b9c56437bfec0b6105ac2e75d3c40106 | [] | no_license | laandrad/SCEDbayes | a04b457003f3ae7eef700a052b59c15a1ca8d3f6 | ab3577f31a40bd685db7bf6bf783534992df0e46 | refs/heads/master | 2021-01-17T18:34:56.861894 | 2017-04-23T00:29:43 | 2017-04-23T00:29:43 | 71,513,188 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,969 | r | mb_delta_estimation.R | ## calculate standardized effect sizes for intercept only model
mb.compute.delta <- function(y, P, s, bayes.coeff, model) {
phases = mb.create.phases(P, s)
nPoints = length(y)
P1 = unlist(phases[1])
T1 = unlist(phases[2])
T2 = unlist(phases[3])
N = nrow(bayes.coeff)
nPoints = length(P)
x = P[-1] - P[-nPoints]
nPhase = which(!x==0)
lPhase = c(0,nPhase, nPoints)
lPhase = lPhase[-1] - lPhase[-length(lPhase)]
lPhase = (lPhase-1) / 2
if(model == 'trend'){
## calculate the within-subject stdev from residuals = observed - predicted value at time t
stdev = sapply(1:N, function(j) {
yhat = sapply(2:nPoints, function(t)
beta0[j]*(1-rho[j]) + beta2[j]*(T1[t] - rho[j]*T1[t-1]) +
beta1[j]*(P1[t]-rho[j]*P1[t-1]) + beta3[j]*(T2[t]*P1[t] - rho[j]*T2[t-1]*P1[t-1]) +
rho[j] * y[t-1])
yhat = c( beta0[j] + beta2[j] * T1[1] +
beta1[j] * P1[1] + beta3[j] * T2[1]*P1[1] ,
yhat)
res = (y - yhat)^2
return(sqrt(sum(res)/nPoints))
})
## calculate effect sizes
delta = sapply(1:N, function(j) beta1[j] - beta3[j]*lPhase[1] ) ## AB
## standardize effect sizes
delta = sapply(1:N, function(j) delta[j] / stdev[j]) ## AB
return(delta)
} else{
## calculate the within-subject stdev from residuals = observed - predicted value at time t
stdev = sapply(1:N, function(j) {
yhat = sapply(2:nPoints, function(t) beta0[j]*(1-rho[j]) +
beta1[j] * (P1[t]-rho[j]*P1[t-1]) )
yhat = c( beta0[j] + beta1[j] * P1[1] , yhat )
res = (y - yhat)^2
return(sqrt(sum(res)/nPoints))
})
## calculate standardized effect sizes
delta = sapply(1:N, function(j) beta1[j] / stdev[j]) ## AB
return(delta)
}
}
|
79f03d9cb68491596317fbe0619d88ad9b131c22 | 7a95abd73d1ab9826e7f2bd7762f31c98bd0274f | /mcga/inst/testfiles/ByteCodeMutation/libFuzzer_ByteCodeMutation/ByteCodeMutation_valgrind_files/1612886722-test.R | 76799bd236d69b7c9cde4a333d8598c6b03efa63 | [] | no_license | akhikolla/updatedatatype-list3 | 536d4e126d14ffb84bb655b8551ed5bc9b16d2c5 | d1505cabc5bea8badb599bf1ed44efad5306636c | refs/heads/master | 2023-03-25T09:44:15.112369 | 2021-03-20T15:57:10 | 2021-03-20T15:57:10 | 349,770,001 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 714 | r | 1612886722-test.R | testlist <- list(bytes1 = c(-8388608L, 16702978L, -8388608L, 8388608L, -16646144L, 16720383L, -1L, -65314L, 16703L, -55007L, 8388608L, 0L, 0L, -1414823936L, 65195L, -14614101L, -1414856448L, 3857920L, -14614529L, 32768L, 65279L, 553713664L, 50298880L, 65246L, 50298880L, 32768L, 65535L, -1L, -1L, -128L, 53L, 989888512L, 65282L, 255L, -1L, -1L, -1753219072L, 16711425L, -570416894L, -8388608L, 16187392L, -1414823936L, NA, 32768L, 65279L, 553713886L, 9046528L, 16777024L, 3071L, -16711681L, -130816L, -570416896L, -1L, -14548993L, 570368256L, 16244352L, 33423359L, -33488674L, 2195456L, 65024L, -14614101L), pmutation = 1.70900593416875e-304)
result <- do.call(mcga:::ByteCodeMutation,testlist)
str(result) |
f194f326817a93048296be9a8ea4795fffd5461f | 570fe25860ba1fc28be96a9f6eeb0a07e0f27aff | /R/CheckPoisson.R | 3c70983547966f4c769cf0d34e28a919608e8139 | [] | no_license | apwheele/Blog_Code | 08ebd53623b46f2177e72f63fece2abccd1bd9b7 | 28811b33810632e39943d91c1fe7e449d419cc7e | refs/heads/master | 2023-08-15T18:21:40.942099 | 2023-07-22T13:59:03 | 2023-07-22T13:59:03 | 229,156,788 | 9 | 9 | null | null | null | null | UTF-8 | R | false | false | 1,161 | r | CheckPoisson.R | ################################################################
#This returns a dataframe with the columns
##Int -- cells with 0, 1, 2, etc.
##Freq -- total sample size in that count
##Prop -- proportion of the sample with that integer value
##PoisD -- the proportion expected via the Poisson distribution
##Resid -- residual between Prop and PoisD
##mu -- mean of the sample
##v -- variance of the sample [another check, should be close for Poisson
CheckPoisson <- function(counts){
maxC <- max(counts)
freqN <- as.data.frame(table(factor(counts,levels=0:maxC)))
mu <- mean(counts)
freqN$Prop <- (freqN$Freq/sum(freqN$Freq))*100
freqN$PoisD <- dpois(0:maxC,mu)*100
freqN$Resid <- (freqN$Prop - freqN$PoisD)
freqN$mu <- mu
freqN$v <- var(counts)
freqN$Var1 <- as.numeric(as.character(freqN$Var1))
names(freqN)[1] <- 'Int'
return(freqN)
}
################################################################
#Example use
lambda <- 0.2
x <- rpois(10000,lambda)
CheckPoisson(x)
#82% zeroes is not zero inflated -- expected according to Poisson!
######################
#ToDo, this for negative binomial fit
###################### |
d9e093ca692c15703557d1d75a1acdf4d23f7147 | d7a4eea625f8419f1dd2d523f954114c83c6ea69 | /Kuis1.R | 1feec1cadd24496837518bc4074911f3ac07c7c4 | [] | no_license | ulis-f/Kuis1 | 0a8bda12d46d3a1534a8a1832db633921b0a2148 | fa8aa2b117c0865646cd60ffce33b1240384fa25 | refs/heads/main | 2023-04-15T16:14:03.346840 | 2021-04-25T12:01:38 | 2021-04-25T12:01:38 | 361,416,103 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 46 | r | Kuis1.R | #Quiz 1 - Statistika Multivariant dengan R
|
5186ec7b4c3ee52b435d759a164fafd896428617 | 506cacd76e2e01ec709203bd2143ffbbf1a4e43e | /4_ExploratoryDataAnalysis/ProgrammingAssignment/PA2/plot5.R | b8109e362d17e5db34c7f5052de90bb1a482c482 | [] | no_license | proutray/datasciencecoursera | e897ffb2b0c405ca19a0e7e2e0ddd49e542448ea | 29c7883ca328637cfefbc0c7d69c4773a131c539 | refs/heads/master | 2021-01-06T20:46:36.356594 | 2016-02-18T19:57:29 | 2016-02-18T19:57:29 | 21,712,511 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 593 | r | plot5.R | library(dplyr)
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
motor <- as.character(SCC$SCC[grepl("Motor",SCC$Short.Name)])
data <- filter(NEI, SCC %in% motor, fips == "24510")
plot5data <- aggregate(data[4], by=list(data$year), FUN=sum, na.rm=TRUE)
yrange = range(0,12)
plot(plot5data, type = "h", col = "orange", ylim = yrange, main = "Motor vehicle related emission in Baltimore city", xlab = "Year", ylab = "Emission (in tons)" , xaxt = "n", lwd = 10)
axis(1,plot5data$Group.1)
dev.copy(png, "plot5.png", width=480, height=480, units="px")
dev.off() |
3ee1da0d8b969464afcb6b8f7ee9e6d3a9ba2f6f | 9cbfb976df111cdb998ead2bb9aa7a05e6c81c9b | /first.R | c912c95ac19a077fefcf754540f31754b086c7af | [] | no_license | VedSengupta/MACHINE-LEARNING-PYTHON-R | bd18c7e38f712e85c899e5588687f056e44da94d | 90c34b73cdf1015eea0935cc67298ad22143cf8a | refs/heads/master | 2020-03-09T00:47:04.441299 | 2018-10-18T05:56:53 | 2018-10-18T05:56:53 | 128,497,243 | 0 | 0 | null | 2018-09-29T10:27:16 | 2018-04-07T04:48:23 | R | UTF-8 | R | false | false | 196 | r | first.R | vec1 <-c(1,2,3,4,5,6)
vec2 <-c(1L,2L,3L,4L,5L,6L)
vec3 <-c("ved","sudip","sourav")
vec4 <-c(1+2i,2+3i)
vecc5 <-c(TRUE,FALSE)
class(vec1)
class(vec2)
class(vec3)
class(vec4)
class(vecc5)
|
fa7bcacb21037003f5bf70456a36068b35539d19 | d9cc435d84d2b2f9d2b7ac974864db0420337e41 | /man/indocx.Rd | e7d1e8154d453e5c9a96f53ef9de5fdf749f03eb | [] | no_license | guokai8/eoffice | 162e98cef8722d69dd84a9e5735eb081e8ef94de | 4a9064451b3af51ca3bd97f91c782050bfe479ac | refs/heads/master | 2021-11-28T21:18:41.874439 | 2021-11-09T21:15:47 | 2021-11-09T21:15:47 | 184,794,096 | 23 | 7 | null | 2019-08-29T15:42:58 | 2019-05-03T17:22:21 | R | UTF-8 | R | false | true | 514 | rd | indocx.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/inoffice.R
\name{indocx}
\alias{indocx}
\title{read table from docx}
\usage{
indocx(filename, header = FALSE)
}
\arguments{
\item{filename}{input filename}
\item{header}{use first row as column name}
}
\description{
read table from docx
}
\examples{
totable(t.test(wt ~ am, mtcars), filename = file.path(tempdir(), "mtcars.docx"))
tabs <- indocx(filename = file.path(tempdir(), "mtcars.docx"), header = TRUE)
tabs
}
\author{
Kai Guo
}
|
0dba8c6584437295a312be10f7278d35523a405e | a6596161ef3214df1bc054bb3f9fa03ab93a7221 | /ui1.R | 81c273b77f31fdc1c7e66c46f62bde967559c1c9 | [
"MIT"
] | permissive | Ben-NIU/HazTrak-Inventory | 5f3430a52767abadabe09d8830024093f54b4f5f | f87b6a783af06a1ab02358fb9786c4aa87621c08 | refs/heads/master | 2021-01-22T17:15:04.257231 | 2017-01-27T04:58:05 | 2017-01-27T04:58:05 | 68,497,325 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 5,765 | r | ui1.R |
shinyUI(fluidPage(
titlePanel(
fluidRow(column(8, div(p(strong("HazTrak Inventory Chemical List")),style="font-family:'bradley hand';color:purple; font-size:30pt"),
h4(em(strong("from", span("Gross Lab", style="font-family:'gabriola';color:blue; font-size:15pt"))))),
column(4, img(src="wustl_name.png", width=210, height=70, align="right"))
)),
sidebarLayout(
sidebarPanel(
fileInput("ipt0",label=div(em("Click to upload csv!"), style="font-family:'marker felt';color:darkblue; font-size:12pt")),
textInput("ipt1", label=div(em("Inventory #"), style="font-family:'marker felt';color:darkgreen; font-size:12pt"), placeholder = "input inventory # to add"),
textInput("name", label=div(em("Chemical Name"), style="font-family:'marker felt';color:darkgreen; font-size:12pt"), placeholder = "input chemical name here"),
actionButton("GO", label=div(em("Add item!"), style="font-family:'marker felt';color:darkgreen; font-size:12pt")),
br(),
br(),
radioButtons("state", label=div(em("Specify the state of chemical"), style="font-family:'marker felt';color:darkgreen; font-size:12pt"), choices = c("Solid","Liquid","Gas"), selected = "Liquid"),
fluidRow(
column(5,numericInput("amount", label=div(em("Specify the Amount"), style="font-family:'marker felt';color:darkgreen; font-size:12pt"),value=1,width="100%")),
column(5,textInput("unit", label=div(em("Specify the Unit"), style="font-family:'marker felt';color:darkgreen; font-size:12pt"), placeholder = "e.g., ug", width = "100%"))),
textInput("ipt2", label=div(em("Remove items from inventory"), style="font-family:'marker felt';color:darkred; font-size:12pt"), placeholder = "input inventory # then click delete"),
actionButton("Delete",label=div(em("Delete item!"), style="font-family:'marker felt';color:darkred; font-size:12pt")),
hr(),
downloadButton("Output", label=span(em("Download Full Inventory!"), style="font-family:'marker felt';color:#996600; font-size:12pt"))
),
mainPanel(
tabsetPanel(type="tabs",
tabPanel(div(strong("Full List"), style="font-family:'bradley hand';color:purple; font-size:13pt"),
br(),
DT::dataTableOutput("LIST")
),
tabPanel(div(strong("Confirmed Chemicals"),style="font-family:'bradley hand';color:purple; font-size:13pt"),
br(),
fluidRow(
column(4,actionButton("cf", label=div(em("Update List!"), style="font-family:'marker felt';color:red; font-size:12pt"))),
column(6,downloadButton("output.cf", label=span(em("Download Confirmed Chemicals!"), style="font-family:'marker felt';color:#996600; font-size:12pt")))),
br(),
DT::dataTableOutput("confirmed")
),
tabPanel(div(strong("Unconfirmed Chemicals"),style="font-family:'bradley hand';color:purple; font-size:13pt"),
br(),
fluidRow(
column(4,actionButton("uncf", label=div(em("Update List!"), style="font-family:'marker felt';color:red; font-size:12pt"))),
column(6,downloadButton("output.uncf", label=span(em("Download Unconfirmed Chemicals!"), style="font-family:'marker felt';color:#996600; font-size:12pt")))),
hr(),
DT::dataTableOutput("unconfirmed")
),
tabPanel(div(strong("Guide"),style="font-family:'bradley hand';color:purple; font-size:13pt"),
helpText(p(strong("Sidebar Panel & Full List Tab")),
p('1. Upload the .csv inventory file by clicking "Choose File" button. Under the "Full List" tab, a table corresponding to the inventory list should appear AUTOMATICALLY.'),
p('2. To add item to the inventory list, input the "item # / id" to the 1st blank of sidebar, select the "State of chemical" (Solid, Liquid or Gas) and then click "Add item!" button. '),
p('3. For any new items added to the list, one of the following two would happen: (i) If the current inventory list does NOT contain the "item id / #" you added, this "item id / #" would be inserted to the FIRST ROW of the current list; (ii) If the current inventory list already contains the "item id / #", it will refresh the existing item by specifying its state (solid, liquid or gas) and put the corresponding row to the TOP OF LIST.'),
p('4. If, by any chance, you wanna remove an item from the inventory list (e.g., you added something to it but later on realized that you mis-spelt the id / #), simply input the "item id / #" to the 2nd blank of sidebar and hit "Delete item!" button.'),
p(strong("Confirmed & Unconfirmed Chemicals Tab")),
p('1. Unlike in the Full list Tab where contents are shown interactively, the contents in these two tabs will NOT present / update until you hit the red "Update List!" button'),
p('2. Under Confirmed Chemicals Tab, only those chemicals inputted by user are shown. (i.e., the lab DOES have those chemicals.)'),
p('3. Under Unconfirmed Chemicals Tab, only those chemicals that are on the Inventory List BUT NOT FOUND IN THE LAB are shown. '),
p(strong("Download files")),
p('(i). Once done with Add / Delete, you can download the full inventory list (containing both confirmed & unconfirmed chemicals) by clicking the "Download Full Inventory" button.'),
p('(ii). Under the "Confirmed Chemicals" Tab, you can download those confirmed chemicals ONLY by clicking the "Download Confirmed Chemicals!" button.'),
p('(iii). Under the "Unconfirmed Chemicals" Tab, download the unconfirmed chemicals by clicking the "Download Unconfirmed Chemicals!" button.')
)
)
)
)
))
) |
eccebea06101750a1bf513367d382e4b2d21692f | 9c4634e062e5bafa303effc781ef2b693825aa6a | /France.R | 6178d4982aee57b1801a222ae8f5f6d3744d92b2 | [] | no_license | Chavagnac/dissertation-soil-c | 74f52960d87a6b1b083b7296d53becf51cc38326 | 3c8ababd265ccadb1d1eae5fe43a6093c40f23fd | refs/heads/master | 2022-11-22T04:43:42.976461 | 2020-07-23T20:50:46 | 2020-07-23T20:50:46 | 267,895,010 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 59,183 | r | France.R |
install.packages("rio")
install.packages("rgdal")
install.packages("sp")
install.packages("ncdf")
install.packages("chron")
install.packages("ncdf4")
install.packages("rasterVis")
install.packages("gpclib")
library(rio)
library(rgdal)
library(raster)
library(ncdf4)
library(sp)
library(ggplot2)
library(tmap)
library(RColorBrewer)
library(shapefiles)
library(tidyverse)
library(chron)
library(tibble)
library(lattice)
library(lubridate)
library(dplyr)
# Let's do the same as with morocco but now with Sweden
readdir <- ("~/Desktop/Diss-data/SpamYield")
file.names <- dir(readdir, pattern =".tif")
Crop_yield_stack <- raster::stack()
for(i in 1:length(file.names)){
readpath <- paste(readdir, file.names[i], sep="/") # aggregate strings to create filepath
x <- raster(readpath) # read raster
Crop_yield_stack <- addLayer(Crop_yield_stack, x)
rm(x)
print(file.names[i])
}
rm(readdir, file.names, readpath, i)
readdir <- ("~/Desktop/Diss-data/SpamArea")
file.names <- dir(readdir, pattern =".tif")
Crop_area_stack <- raster::stack()
for(i in 1:length(file.names)){
readpath <- paste(readdir, file.names[i], sep="/") # aggregate strings to create filepath
x <- raster(readpath) # read raster
Crop_area_stack <- addLayer(Crop_area_stack, x)
rm(x)
print(file.names[i])
}
Shp_sw <- shapefile("~/Desktop/Diss-data/Sweden/Sweden.shp")
shp_sw <- as.data.frame(Shp_sw@polygons[[1]]@Polygons[[1]]@coords)
Crop_area_stack <- Crop_area_stack %>%
crop(Shp_sw) %>%
mask(Shp_sw)
Crop_yield_stack <- Crop_yield_stack %>%
crop(Shp_sw) %>%
mask(Shp_sw)
plot(Crop_area_stack[[1]])
plot(Shp_sw, add = T)
hist(Crop_area_stack[[1]])
isnt_zero <- function(x){
y <- x == 0 | is.na(x)
z <- F %in% y == T
return(z)
}
Dat_area <- Crop_area_stack %>%
as.data.frame()
Dat_yield <- Crop_yield_stack%>%
as.data.frame()
nonzero <- Dat_area %>%
select_if(isnt_zero) %>%
colnames()
non_zero <- Dat_yield %>%
select_if(isnt_zero) %>%
colnames()
Crop_area_stack <- Crop_area_stack[[which(Crop_area_stack %>% names() %in% nonzero)]]
Crop_yield_stack <- Crop_yield_stack[[which(Crop_yield_stack %>% names() %in% non_zero)]]
#,str_replace(non_zero "phys_area", "yield"))]]
plot(Crop_area_stack[[1:11]])
plot(Crop_yield_stack[[1:11]])
Sweden_fao <- read.csv("~/Desktop/Sweden_fao.csv")
saveRDS(Sweden_fao, "~/Desktop/Diss-data/Sweden/sweden_FAO.rds")
Dat_fs <- read_rds("~/Desktop/Diss-data/Sweden/sweden_FAO.rds")
crop_names <- tibble(orig = names(Crop_area_stack))
crop_names1 <- tibble(orig = names(Crop_yield_stack))
crop_names <- crop_names %>%
mutate(trans = c("barley", "beans", "cereals", "NA","pulses", "potato",
"rapeseed","sugarbeet", "NA","NA", "wheat"))
crop_names1 <- crop_names1 %>%
mutate(trans1 = c("barley", "beans", "cereals", "NA","pulses", "potato",
"rapeseed","sugarbeet", "NA","NA", "wheat"))
crop_names <- crop_names %>%
drop_na()
keep <- crop_names$orig
crop_names1 <- crop_names1 %>%
drop_na()
keep1 <- crop_names1$orig
# filter stacks
Crop_area_stack <- Crop_area_stack[[which(Crop_area_stack %>% names() %in% keep)]]
Crop_yield_stack <- Crop_yield_stack[[which(Crop_yield_stack %>% names() %in% keep1)]]
#str_replace(keep, "phys_area", "yield"))]]
# rename
names(Crop_area_stack) <- crop_names$trans
names(Crop_yield_stack) <- crop_names1$trans1
Crop_area_stack <- readAll(Crop_area_stack)
Crop_yield_stack <- readAll(Crop_yield_stack)
# write out data
write_rds(Crop_area_stack, "~/Desktop/Diss-data/Sweden/sweden-crop-area-ha-2010.rds")
write_rds(Crop_yield_stack, "~/Desktop/Diss-data/Sweden/sweden-crop-yield-tonnes-per-ha-2010.rds")
# Now we visualise. First barley
Brk_croparea <- read_rds("~/Desktop/Diss-data/Sweden/sweden-crop-area-ha-2010.rds")
Brk_cropyield <- read_rds("~/Desktop/Diss-data/Sweden/sweden-crop-yield-tonnes-per-ha-2010.rds")
Ras_cropyield <- Brk_cropyield[[which(names(Brk_cropyield) == "barley")]]
Ras_croparea <- Brk_croparea[[which(names(Brk_croparea) == "barley")]]
rm(temp_cropname)
plot(Ras_croparea)
barley_area <- Brk_croparea[[which(names(Brk_croparea) == "barley")]]
wheat_area <- Brk_croparea[[which(names(Brk_croparea) == "wheat")]]
plot(barley_area)
plot(Shp_sw, add=T)
plot(wheat_area, padj=-1.5, cex.axis=0.7, xlab="Longitude (degree)", ylab="Latitude (degree)", cex.lab=0.75)
axis(1,padj=-1.5, cex.axis=0.7, tck=-0.01, )
plot(Shp_sw, add=T)
barley_area_df <- as.data.frame(Brk_croparea[[which(names(Brk_croparea) == "barley")]], xy = TRUE)
str(barley_area_df)
bean_area_df <- as.data.frame(Brk_croparea[[which(names(Brk_croparea) == "beans")]], xy = TRUE)
str(barley_area_df)
cereal_area_df <- as.data.frame(Brk_croparea[[which(names(Brk_croparea) == "cereals")]], xy = TRUE)
str(barley_area_df)
pulses_area_df <- as.data.frame(Brk_croparea[[which(names(Brk_croparea) == "pulses")]], xy = TRUE)
str(barley_area_df)
pot_area_df <- as.data.frame(Brk_croparea[[which(names(Brk_croparea) == "potato")]], xy = TRUE)
str(barley_area_df)
rape_area_df <- as.data.frame(Brk_croparea[[which(names(Brk_croparea) == "rapeseed")]], xy = TRUE)
str(barley_area_df)
sugb_area_df <- as.data.frame(Brk_croparea[[which(names(Brk_croparea) == "sugarbeet")]], xy = TRUE)
str(barley_area_df)
wheat_area_df <- as.data.frame(Brk_croparea[[which(names(Brk_croparea) == "wheat")]], xy = TRUE)
str(wheat_area_df)
ggplot(data = barley_area_df) +
geom_raster(aes(x = x, y = y, fill = barley)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Barley Harvested \nArea (ha)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = bean_area_df) +
geom_raster(aes(x = x, y = y, fill = beans)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Beans Harvested \nArea (ha)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = cereal_area_df) +
geom_raster(aes(x = x, y = y, fill = cereals)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Cereals Harvested \nArea (ha)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = pulses_area_df) +
geom_raster(aes(x = x, y = y, fill = pulses)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Pulses Harvested \nArea (ha)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = rape_area_df) +
geom_raster(aes(x = x, y = y, fill = rapeseed)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Rapeseed Harvested \nArea (ha)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = pot_area_df) +
geom_raster(aes(x = x, y = y, fill = potato)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Potatoes \nHarvested Area (ha)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = sugb_area_df) +
geom_raster(aes(x = x, y = y, fill = sugarbeet)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Sugarbeet \nHarvested Area (ha)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = wheat_area_df) +
geom_raster(aes(x = x, y = y, fill = wheat)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Wheat \nHarvested Area (ha)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
# Now for yield
barley_y_df <- as.data.frame(Brk_cropyield[[which(names(Brk_cropyield) == "barley")]], xy = TRUE)
barley_y_df$barley <-barley_y_df$barley/1000
wheat_y_df <- as.data.frame(Brk_cropyield[[which(names(Brk_cropyield) == "wheat")]], xy = TRUE)
wheat_y_df$wheat <- wheat_y_df$wheat/1000
bean_y_df <- as.data.frame(Brk_cropyield[[which(names(Brk_cropyield) == "beans")]], xy = TRUE)
bean_y_df$beans <- bean_y_df$beans/1000
cereal_y_df <- as.data.frame(Brk_cropyield[[which(names(Brk_cropyield) == "cereals")]], xy = TRUE)
cereal_y_df$cereals <- cereal_y_df$cereals/1000
pulse_y_df <- as.data.frame(Brk_cropyield[[which(names(Brk_cropyield) == "pulses")]], xy = TRUE)
pulse_y_df$pulses <- pulse_y_df$pulses/1000
rape_y_df <- as.data.frame(Brk_cropyield[[which(names(Brk_cropyield) == "rapeseed")]], xy = TRUE)
rape_y_df$rapeseed<-rape_y_df$rapeseed/1000
pot_y_df <- as.data.frame(Brk_cropyield[[which(names(Brk_cropyield) == "potato")]], xy = TRUE)
pot_y_df$potato<-pot_y_df$potato/1000
sugb_y_df <- as.data.frame(Brk_cropyield[[which(names(Brk_cropyield) == "sugarbeet")]], xy = TRUE)
sugb_y_df$sugarbeet<-sugb_y_df$sugarbeet/1000
ggplot(data = barley_y_df) +
geom_raster(aes(x = x, y = y, fill = barley)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Barley Yield \n(t ha-1)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = wheat_y_df) +
geom_raster(aes(x = x, y = y, fill = wheat)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Wheat Yield \n(t ha-1)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = bean_y_df) +
geom_raster(aes(x = x, y = y, fill = beans)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Bean Yield \n(t ha-1)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = cereal_y_df) +
geom_raster(aes(x = x, y = y, fill = cereals)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Cereal Yield \n(t ha-1)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = pulse_y_df) +
geom_raster(aes(x = x, y = y, fill = pulses)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Pulse Yield \n(t ha-1)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = rape_y_df) +
geom_raster(aes(x = x, y = y, fill = rapeseed)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Rapeseed \nYield (t ha-1)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = sugb_y_df) +
geom_raster(aes(x = x, y = y, fill = sugarbeet)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Sugar Beet \nYield (t ha-1)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
ggplot(data = pot_y_df) +
geom_raster(aes(x = x, y = y, fill = potato)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x=V1, y=V2),
fill=NA,color="black", size=1)+
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Potato Yield \n(t ha-1)") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
# Now let's make an estimate of crop yields for the next 10 years according to Alasdair's equation
# First wheat
sw_fao <- read.csv("~/Desktop/Sweden_fao.csv")
saveRDS(sw_fao, "~/Desktop/Diss-data/Sweden/sweden_FAO.rds")
Dat_faostat_sw <- read_rds("~/Desktop/Diss-data/Sweden/sweden_FAO.rds")
sample_n(Dat_faostat_sw, 10, replace = F)
Ras_clim <- read_rds("~/Desktop/Global Weather/Model 1/Sweden-climate-data-helper-raster.rds")
Brk_croparea <- read_rds("~/Desktop/Diss-data/Sweden/sweden-crop-area-ha-2010.rds")
Brk_cropyield <- read_rds("~/Desktop/Diss-data/Sweden/sweden-crop-yield-tonnes-per-ha-2010.rds")
crop_type <- "wheat" # name of crop of interest
frac_renew <- 1 / 1 # fraction of crop renewed every year (for e.g. crop renewed every three years, frac_renew = 1 / 3)
frac_remove <- 0.265 # fraction of crop residues removed
manure_type <- "dairy-cattle" # type of animal used to produce manure
manure_nrate <- 32 # application rate of manure in kg N per hectare
till_type <- "reduced" # type of tillage, either full, reduced or zero
sim_start_year <- 1961 # year simulation to start (min = 1961)
sim_end_year <- 2097 ## year simulation to end (max = 2097)
lat_lon <- tibble(x = 17.5, y = 60) # default chosen here is a high-yielding arable land near Marrackech
temp_cropname <- crop_type %>% str_replace_all("-", "\\.") # necessary adjustment as raster doesn't like hyphens
# extract relevant crop raster from crop bricks
Ras_cropyield <- Brk_cropyield[[which(names(Brk_cropyield) == temp_cropname)]]
Ras_croparea <- Brk_croparea[[which(names(Brk_croparea) == temp_cropname)]]
rm(temp_cropname)
# extract from rasters based on points
yield_tha <- raster::extract(Ras_cropyield, lat_lon)
area_ha <- raster::extract(Ras_croparea, lat_lon)
sand_pc <- raster::extract(Ras_sand, lat_lon)
clim_coord_no <- raster::extract(Ras_clim, lat_lon)
Dat_crop_ts <- Dat_faostat_sw %>%
filter(crop == crop_type,
year >= sim_start_year) %>%
mutate(yield_rel = (yield_tha / yield_tha[year == 2010]),
area_rel = (area_harvested / area_harvested[year == 2010])) %>%
dplyr::select(crop, year, yield_rel, area_rel)
# convert to yields for extracted area
Dat_crop_ts <- Dat_crop_ts %>%
mutate(yield_tha = yield_rel * yield_tha,
area_ha = area_rel * area_ha)
# plot
Dat_crop_ts %>%
ggplot(aes(x = year, y = yield_tha)) +
geom_line()
# 10 year mean and sd for crop yield
yield_mean <- Dat_crop_ts %>% tail(10) %>% pull(yield_tha) %>% mean()
yield_sd <- Dat_crop_ts %>% tail(10) %>% pull(yield_tha) %>% sd()
area_mean <- Dat_crop_ts %>% tail(10) %>% pull(area_ha) %>% mean()
area_sd <- Dat_crop_ts %>% tail(10) %>% pull(area_ha) %>% sd()
# randomly generated barley yield to 2070 based on 10-year performance
set.seed(260592)
Dat_preds <- tibble(year = 2019:sim_end_year,
yield_tha = rnorm(n = length(2019:sim_end_year), mean = yield_mean, sd = yield_sd),
area_ha = rnorm(n = length(2019:sim_end_year), mean = area_mean, sd = area_sd))
# bind simulation with historical data
Dat_crop_ts <- bind_rows("historical" = Dat_crop_ts,
"simulated" = Dat_preds,
.id = "origin")
# plot to check
sw_wheat_yield <- Dat_crop_ts %>%
ggplot(aes(x = year, y = yield_tha, colour = origin)) +
geom_line()
sw_wheat_area <- data.frame(Dat_crop_ts$origin,Dat_crop_ts$year, Dat_crop_ts$area_ha)
######################################################################
# write out crop and manure data files (MODIFY FILE NAMES AS NEEDED) #
######################################################################
# write out crop data
Dat_crop_ts %>%
mutate(crop_type = crop_type,
frac_renew = frac_renew,
frac_remove = frac_remove,
till_type = till_type,
sand_frac = sand_pc / 100) %>%
dplyr::select(origin, year, crop_type, yield_tha, frac_renew, frac_remove, sand_frac, till_type) %>%
write_csv("~/Desktop/Diss-data/Sweden/sweden-wheat-crop-data.csv")
# write out manure data
tibble(year = sim_start_year:sim_end_year,
man_type = manure_type,
man_nrate = manure_nrate) %>%
write_csv("~/Desktop/Diss-data/Sweden/sweden-example-manure-data.csv")
## Now barley
Dat_faostat_sw <- read_rds("~/Desktop/Diss-data/Sweden/sweden_FAO.rds")
sample_n(Dat_faostat_sw, 10, replace = F)
Brk_croparea <- read_rds("~/Desktop/Diss-data/Sweden/sweden-crop-area-ha-2010.rds")
Brk_cropyield <- read_rds("~/Desktop/Diss-data/Sweden/sweden-crop-yield-tonnes-per-ha-2010.rds")
crop_type <- "barley" # name of crop of interest
frac_renew <- 1 / 1 # fraction of crop renewed every year (for e.g. crop renewed every three years, frac_renew = 1 / 3)
frac_remove <- 0.505 # fraction of crop residues removed
manure_type <- "dairy-cattle" # type of animal used to produce manure
manure_nrate <- 32 # application rate of manure in kg N per hectare
till_type <- "reduced" # type of tillage, either full, reduced or zero
sim_start_year <- 1961 # year simulation to start (min = 1961)
sim_end_year <- 2097 ## year simulation to end (max = 2097)
lat_lon <- tibble(x = 17.5, y = 60) # default chosen here is a high-yielding arable land near Marrackech
temp_cropname <- crop_type %>% str_replace_all("-", "\\.") # necessary adjustment as raster doesn't like hyphens
# extract relevant crop raster from crop bricks
Ras_cropyield <- Brk_cropyield[[which(names(Brk_cropyield) == temp_cropname)]]
Ras_croparea <- Brk_croparea[[which(names(Brk_croparea) == temp_cropname)]]
rm(temp_cropname)
# extract from rasters based on points
yield_tha <- raster::extract(Ras_cropyield, lat_lon)
area_ha <- raster::extract(Ras_croparea, lat_lon)
sand_pc <- raster::extract(Ras_sand, lat_lon)
clim_coord_no <- raster::extract(Ras_clim, lat_lon)
Dat_crop_ts <- Dat_faostat_sw %>%
filter(crop == crop_type,
year >= sim_start_year) %>%
mutate(yield_rel = (yield_tha / yield_tha[year == 2010]),
area_rel = (area_harvested / area_harvested[year == 2010])) %>%
dplyr::select(crop, year, yield_rel, area_rel)
# convert to yields for extracted area
Dat_crop_ts <- Dat_crop_ts %>%
mutate(yield_tha = yield_rel * yield_tha,
area_ha = area_rel * area_ha)
# plot
Dat_crop_ts %>%
ggplot(aes(x = year, y = yield_tha)) +
geom_line()
# 10 year mean and sd for crop yield
yield_mean <- Dat_crop_ts %>% tail(10) %>% pull(yield_tha) %>% mean()
yield_sd <- Dat_crop_ts %>% tail(10) %>% pull(yield_tha) %>% sd()
area_mean <- Dat_crop_ts %>% tail(10) %>% pull(area_ha) %>% mean()
area_sd <- Dat_crop_ts %>% tail(10) %>% pull(area_ha) %>% sd()
# randomly generated barley yield to 2070 based on 10-year performance
set.seed(260592)
Dat_preds <- tibble(year = 2019:sim_end_year,
yield_tha = rnorm(n = length(2019:sim_end_year), mean = yield_mean, sd = yield_sd),
area_ha = rnorm(n = length(2019:sim_end_year), mean = area_mean, sd = area_sd))
# bind simulation with historical data
Dat_crop_ts <- bind_rows("historical" = Dat_crop_ts,
"simulated" = Dat_preds,
.id = "origin")
# plot to check
sw_barley_yield <- Dat_crop_ts %>%
ggplot(aes(x = year, y = yield_tha, colour = origin)) +
geom_line()
sw_barley_area <- data.frame(Dat_crop_ts$origin,Dat_crop_ts$year, Dat_crop_ts$area_ha)
######################################################################
# write out crop and manure data files (MODIFY FILE NAMES AS NEEDED) #
######################################################################
# write out crop data
Dat_crop_ts %>%
mutate(crop_type = crop_type,
frac_renew = frac_renew,
frac_remove = frac_remove,
till_type = till_type,
sand_frac = sand_pc / 100) %>%
dplyr::select(origin, year, crop_type, yield_tha, frac_renew, frac_remove, sand_frac, till_type) %>%
write_csv("~/Desktop/Diss-data/Sweden/sweden-barley-crop-data.csv")
## Now beans
# no data after year 2000
## now potato
Dat_faostat_sw <- read_rds("~/Desktop/Diss-data/Sweden/sweden_FAO.rds")
sample_n(Dat_faostat_sw, 10, replace = F)
Brk_croparea <- read_rds("~/Desktop/Diss-data/Sweden/sweden-crop-area-ha-2010.rds")
Brk_cropyield <- read_rds("~/Desktop/Diss-data/Sweden/sweden-crop-yield-tonnes-per-ha-2010.rds")
crop_type <- "potato" # name of crop of interest
frac_renew <- 1 / 1 # fraction of crop renewed every year (for e.g. crop renewed every three years, frac_renew = 1 / 3)
frac_remove <- 0 # fraction of crop residues removed
manure_type <- "dairy-cattle" # type of animal used to produce manure
manure_nrate <- 32 # application rate of manure in kg N per hectare
till_type <- "reduced" # type of tillage, either full, reduced or zero
sim_start_year <- 1961 # year simulation to start (min = 1961)
sim_end_year <- 2097 ## year simulation to end (max = 2097)
lat_lon <- tibble(x = 17.5, y = 60) # default chosen here is a high-yielding arable land near Marrackech
temp_cropname <- crop_type %>% str_replace_all("-", "\\.") # necessary adjustment as raster doesn't like hyphens
# extract relevant crop raster from crop bricks
Ras_cropyield <- Brk_cropyield[[which(names(Brk_cropyield) == temp_cropname)]]
Ras_croparea <- Brk_croparea[[which(names(Brk_croparea) == temp_cropname)]]
rm(temp_cropname)
# extract from rasters based on points
yield_tha <- raster::extract(Ras_cropyield, lat_lon)
area_ha <- raster::extract(Ras_croparea, lat_lon)
sand_pc <- raster::extract(Ras_sand, lat_lon)
clim_coord_no <- raster::extract(Ras_clim, lat_lon)
Dat_crop_ts <- Dat_faostat_sw %>%
filter(crop == crop_type,
year >= sim_start_year) %>%
mutate(yield_rel = (yield_tha / yield_tha[year == 2010]),
area_rel = (area_harvested / area_harvested[year == 2010])) %>%
dplyr::select(crop, year, yield_rel, area_rel)
# convert to yields for extracted area
Dat_crop_ts <- Dat_crop_ts %>%
mutate(yield_tha = yield_rel * yield_tha,
area_ha = area_rel * area_ha)
# plot
Dat_crop_ts %>%
ggplot(aes(x = year, y = yield_tha)) +
geom_line()
# 10 year mean and sd for crop yield
yield_mean <- Dat_crop_ts %>% tail(10) %>% pull(yield_tha) %>% mean()
yield_sd <- Dat_crop_ts %>% tail(10) %>% pull(yield_tha) %>% sd()
area_mean <- Dat_crop_ts %>% tail(10) %>% pull(area_ha) %>% mean()
area_sd <- Dat_crop_ts %>% tail(10) %>% pull(area_ha) %>% sd()
# randomly generated barley yield to 2070 based on 10-year performance
set.seed(260592)
Dat_preds <- tibble(year = 2019:sim_end_year,
yield_tha = rnorm(n = length(2019:sim_end_year), mean = yield_mean, sd = yield_sd),
area_ha = rnorm(n = length(2019:sim_end_year), mean = area_mean, sd = area_sd))
# bind simulation with historical data
Dat_crop_ts <- bind_rows("historical" = Dat_crop_ts,
"simulated" = Dat_preds,
.id = "origin")
# plot to check
sw_pot_yield <- Dat_crop_ts %>%
ggplot(aes(x = year, y = yield_tha, colour = origin)) +
geom_line()
sw_pot_area <-data.frame(Dat_crop_ts$origin,Dat_crop_ts$year, Dat_crop_ts$area_ha)
######################################################################
# write out crop and manure data files (MODIFY FILE NAMES AS NEEDED) #
######################################################################
# write out crop data
Dat_crop_ts %>%
mutate(crop_type = crop_type,
frac_renew = frac_renew,
frac_remove = frac_remove,
till_type = till_type,
sand_frac = sand_pc / 100) %>%
dplyr::select(origin, year, crop_type, yield_tha, frac_renew, frac_remove, sand_frac, till_type) %>%
write_csv("~/Desktop/Diss-data/Sweden/sweden-potato-crop-data.csv")
## Now rapeseed
Dat_faostat_sw <- read_rds("~/Desktop/Diss-data/Sweden/sweden_FAO.rds")
sample_n(Dat_faostat_sw, 10, replace = F)
Brk_croparea <- read_rds("~/Desktop/Diss-data/Sweden/sweden-crop-area-ha-2010.rds")
Brk_cropyield <- read_rds("~/Desktop/Diss-data/Sweden/sweden-crop-yield-tonnes-per-ha-2010.rds")
crop_type <- "rapeseed" # name of crop of interest
frac_renew <- 1 / 1 # fraction of crop renewed every year (for e.g. crop renewed every three years, frac_renew = 1 / 3)
frac_remove <- 0.3 # fraction of crop residues removed
manure_type <- "dairy-cattle" # type of animal used to produce manure
manure_nrate <- 32 # application rate of manure in kg N per hectare
till_type <- "reduced" # type of tillage, either full, reduced or zero
sim_start_year <- 1961 # year simulation to start (min = 1961)
sim_end_year <- 2097 ## year simulation to end (max = 2097)
lat_lon <- tibble(x = 17.5, y =60) # default chosen here is a high-yielding arable land near Marrackech
temp_cropname <- crop_type %>% str_replace_all("-", "\\.") # necessary adjustment as raster doesn't like hyphens
# extract relevant crop raster from crop bricks
Ras_cropyield <- Brk_cropyield[[which(names(Brk_cropyield) == temp_cropname)]]
Ras_croparea <- Brk_croparea[[which(names(Brk_croparea) == temp_cropname)]]
rm(temp_cropname)
# extract from rasters based on points
yield_tha <- raster::extract(Ras_cropyield, lat_lon)
area_ha <- raster::extract(Ras_croparea, lat_lon)
sand_pc <- raster::extract(Ras_sand, lat_lon)
clim_coord_no <- raster::extract(Ras_clim, lat_lon)
Dat_crop_ts <- Dat_faostat_sw %>%
filter(crop == crop_type,
year >= sim_start_year) %>%
mutate(yield_rel = (yield_tha / yield_tha[year == 2010]),
area_rel = (area_harvested / area_harvested[year == 2010])) %>%
dplyr::select(crop, year, yield_rel, area_rel)
# convert to yields for extracted area
Dat_crop_ts <- Dat_crop_ts %>%
mutate(yield_tha = yield_rel * yield_tha,
area_ha = area_rel * area_ha)
# plot
Dat_crop_ts %>%
ggplot(aes(x = year, y = yield_tha)) +
geom_line()
# 10 year mean and sd for crop yield
yield_mean <- Dat_crop_ts %>% tail(10) %>% pull(yield_tha) %>% mean()
yield_sd <- Dat_crop_ts %>% tail(10) %>% pull(yield_tha) %>% sd()
area_mean <- Dat_crop_ts %>% tail(10) %>% pull(area_ha) %>% mean()
area_sd <- Dat_crop_ts %>% tail(10) %>% pull(area_ha) %>% sd()
# randomly generated barley yield to 2070 based on 10-year performance
set.seed(260592)
Dat_preds <- tibble(year = 2019:sim_end_year,
yield_tha = rnorm(n = length(2019:sim_end_year), mean = yield_mean, sd = yield_sd),
area_ha = rnorm(n = length(2019:sim_end_year), mean = area_mean, sd = area_sd))
# bind simulation with historical data
Dat_crop_ts <- bind_rows("historical" = Dat_crop_ts,
"simulated" = Dat_preds,
.id = "origin")
# plot to check
sw_rape_yield <- Dat_crop_ts %>%
ggplot(aes(x = year, y = yield_tha, colour = origin)) +
geom_line()
sw_rape_area <- data.frame(Dat_crop_ts$origin,Dat_crop_ts$year, Dat_crop_ts$area_ha)
######################################################################
# write out crop and manure data files (MODIFY FILE NAMES AS NEEDED) #
######################################################################
# write out crop data
Dat_crop_ts %>%
mutate(crop_type = crop_type,
frac_renew = frac_renew,
frac_remove = frac_remove,
till_type = till_type,
sand_frac = sand_pc / 100) %>%
dplyr::select(origin, year, crop_type, yield_tha, frac_renew, frac_remove, sand_frac, till_type) %>%
write_csv("~/Desktop/Diss-data/Sweden/sweden-rape-crop-data.csv")
## Now sugarbeet
# removed because none are produced at this area
sw_wheat_yield
sw_barley_yield
sw_pot_yield
sw_rape_yield
plot(sw_wheat_area)
plot(sw_barley_area)
plot(sw_pot_area)
plot(sw_rape_area)
ggplot()+
geom_line(data=sw_rape_area, mapping=aes(x=Dat_crop_ts.year, y=Dat_crop_ts.area_ha, color="Rapeseed"))
color <- c("Maize"="black", "Barley"="blue","Wheat"="red", "Potato"="green", "Millet"='orange', "Rapeseed"='orange')
area_estimate <- ggplot()+
geom_line(data=sw_wheat_area, mapping= aes(x=Dat_crop_ts.year, y=Dat_crop_ts.area_ha, color='Wheat'))+
geom_line(data=sw_barley_area, mapping= aes(x=Dat_crop_ts.year, y=Dat_crop_ts.area_ha, color='Barley'))+
geom_line(data=sw_pot_area, mapping= aes(x=Dat_crop_ts.year, y=Dat_crop_ts.area_ha, color='Potato'))+
geom_line(data=sw_rape_area, mapping=aes(x=Dat_crop_ts.year, y=Dat_crop_ts.area_ha, color="Rapeseed"))+
labs(x="Year", y="Area (ha)", color = "Crops") +
theme(panel.background = element_rect(fill = "white"))+
theme(axis.line = element_line(color = "black"))+
scale_color_manual(values = color)
area_estimate
plot_rape_y <- read_csv("~/Desktop/Diss-data/Sweden/sweden-rape-crop-data.csv")
plot_rape_y$yield_tha <- plot_rape_y$yield_tha/1000
plot_barley_y <- read_csv("~/Desktop/Diss-data/Sweden/sweden-barley-crop-data.csv")
plot_barley_y$yield_tha<- plot_barley_y$yield_tha/1000
plot_wheat_y <- read_csv("~/Desktop/Diss-data/Sweden/sweden-wheat-crop-data.csv")
plot_wheat_y$yield_tha<-plot_wheat_y$yield_tha/1000
plot_pot_y <- read_csv("~/Desktop/Diss-data/Sweden/sweden-potato-crop-data.csv")
plot_pot_y$yield_tha<-plot_pot_y$yield_tha/1000
yield_estimate <- ggplot()+
geom_line(data=plot_rape_y, mapping= aes(x=year, y=yield_tha, color='Rapeseed'))+
geom_line(data=plot_barley_y, mapping= aes(x=year, y=yield_tha, color='Barley'))+
geom_line(data=plot_wheat_y, mapping= aes(x=year, y=yield_tha, color='Wheat'))+
geom_line(data=plot_pot_y, mapping= aes(x=year, y=yield_tha, color='Potato'))+
labs(x="Year", y="Yield (t ha-1)", color = "Crops") +
scale_color_manual(values = color)+
theme(panel.background = element_rect(fill = "white", colour = "white"))+
theme(axis.line = element_line(color = "black"))
yield_estimate
# Now for sand NEED TO DO
library(tidyverse)
library(raster)
Ras_sand <- raster("~/Desktop/Diss-data/Sweden/Sweden_soil.tif")
Ras_sand <- Ras_sand %>%
crop(Shp_sw) %>%
mask(Shp_sw)
plot(Ras_sand)
names(Ras_sand) <- "soil_sand_pc"
Ras_sand <- readAll(Ras_sand) # throws an error cos it's already read it in — keep anyway jic
write_rds(Ras_sand, "~/Desktop/Diss-data/Sweden/sweden-soil-sand-percentage.rds")
see_sand <- rasterToPoints(Ras_sand)
sw_sand <- as.data.frame(see_sand)
ggplot(data = sw_sand) +
geom_raster(aes(x = x, y = y, fill= soil_sand_pc)) +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral")),
na.value="white")+
geom_polygon(data=shp_sw, aes(x= V1, y=V2),
fill=NA,color="black", size=1)+
scale_alpha(range = c(0.1, 0.65), guide = "none")+
labs(x="Longitude (degree)", y="Latitude (degree)", fill="Soil Sand \nComposition (%)") +
geom_hline(yintercept=60, linetype="dashed")+
geom_vline(xintercept=17.5, linetype="dashed")+
theme(panel.background = element_rect(fill = "white", colour = "white"))+
theme(axis.line = element_line(color = "black"))+
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10), legend.key.height=unit(1, "cm"))
# Lets to temp, precip and PEt here
library(raster)
library(tidyverse)
library(ncdf4)
library(lubridate)
nc_open("~/Desktop/Global Weather/Model 1/tempmean_rcp85_land-gcm_global_60km_01_mon_189912-209911.nc")
nc_open("~/Desktop/Global Weather/Model 1/precipitation_rcp85_land-gcm_global_60km_01_mon_189912-209911.nc")
Stk_temp <- brick("~/Desktop/Global Weather/Model 1/tempmean_rcp85_land-gcm_global_60km_01_mon_189912-209911.nc")
Stk_precip <- brick("~/Desktop/Global Weather/Model 1/precipitation_rcp85_land-gcm_global_60km_01_mon_189912-209911.nc")
# read in shapefile and mask brick
Shp_Fr <- shapefile("~/Desktop/Diss-data/Sweden/Sweden.shp")
Stk_temp <- Stk_temp %>% crop(Shp_Fr)
Stk_precip <- Stk_precip %>% crop(Shp_Fr)
plot(Stk_temp[[1:12]])
plot(Stk_precip[[1:12]])
# make names unique
sum(names(Stk_temp) != names(Stk_precip)) # names/dates match exactly
names(Stk_temp) <- names(Stk_temp) %>% str_replace("^X", "temp")
names(Stk_precip) <- names(Stk_precip) %>% str_replace("^X", "precip")
# convert all to dataframe
Dat_clim <- stack(Stk_temp, Stk_precip) %>% as.data.frame(xy = T) %>% as_tibble()
# gather and spread by variable type
Dat_clim <- Dat_clim %>%
gather(-x, -y, key = "key", value = "value") %>%
mutate(date = key %>%
str_replace_all("[:lower:]", "") %>%
str_replace_all("\\.", "-") %>%
ymd_hms(),
metric = key %>%
str_extract("^[:lower:]+(?=\\d)")) %>%
select(-key) %>%
spread(key = metric, value = value) %>%
rename(temp_centigrade = temp,
precip_mm = precip)
nrow(Dat_clim %>% drop_na()) # no NAs to speak of
# convert precipitation to monthly total
Dat_clim <- Dat_clim %>%
mutate(precip_mm = precip_mm * days_in_month(date))
# calculate month and year and nest
Dat_clim <- Dat_clim %>%
mutate(date = as_date(date),
month = month(date),
year = year(date)) %>%
group_by(x, y) %>%
nest() %>%
ungroup()
# compress and interpolate where necessary
# this UKCP data is bloody awkward to get in monthly format
temp <- tibble(date = seq(from = ymd("1902-01-16"), to = ymd("2096-12-17"), by = as.difftime(months(1))) %>% ymd(),
month = month(date),
year = year(date)) %>%
select(-date)
Dat_clim <- Dat_clim %>%
mutate(data_reg = data %>%
map(function(df){
df %>%
group_by(month, year) %>%
summarise(temp_centigrade = mean(temp_centigrade),
precip_mm = mean(precip_mm))
}),
data_reg = data_reg %>%
map(function(df){
df %>%
right_join(temp, by = c("month", "year"))
}),
data_reg = data_reg %>%
map(function(df){
df %>%
mutate(temp_centigrade = temp_centigrade %>% forecast::na.interp() %>% as.numeric(),
precip_mm = precip_mm %>% forecast::na.interp() %>% as.numeric())
})
)
# calculate pet using thornthwaite method
# https://upcommons.upc.edu/bitstream/handle/2117/89152/Appendix_10.pdf?sequence=3&isAllowed=y
# daylength calculations using insol
#install.packages("insol")
#install.packages("forecast")
library(insol)
library(forecast)
lats <- Dat_clim %>%
pull(y) %>%
unique()
jdays <- tibble(date = seq(from = ymd("2019-01-01"), to = ymd("2019-12-31"), by = as.difftime(days(1)))) %>%
mutate(month = month(date),
jday = yday(date),
mday = days_in_month(date)) %>%
group_by(month) %>%
summarise(mday = mean(mday),
jday = mean(jday))
daylength <- tibble(y = rep(lats, 12),
month = rep(1:12, each = length(lats))) %>%
left_join(jdays, by = "month") %>%
mutate(lon = 0,
time_zone = 0,
daylength = pmap_dbl(list(y, lon, jday, time_zone), function(a, b, c, d){
return(daylength(a, b, c, d)[3])
}))
# function required to combat annoying R 'feature' (returns NaN for negative numbers raised to non-integer powers...)
rtp <- function(x, power){
sign(x) * abs(x) ^ (power)
}
Dat_clim <- Dat_clim %>%
mutate(data_reg = map2(y, data_reg, function(lat, df){
df %>%
mutate(y = lat) %>%
group_by(year) %>%
mutate(I = sum(rtp(temp_centigrade / 5, 1.514)),
alpha = 675*10^-9 * rtp(I, 3) - 771*10^-7 * rtp(I, 2) + 1792*10^-5 * I + 0.49239,
pet_mm = rtp(16 * ((10 * temp_centigrade) / I), alpha)) %>%
ungroup() %>%
left_join(daylength %>% select(y, month, daylength, mday), by = c("y", "month")) %>%
mutate(pet_mm = pet_mm * daylength / 12 * mday / 30,
pet_mm = ifelse(pet_mm < 1, 1, pet_mm)) %>% # prevents errors with negative PET/div by zero
select(-y, -I, -alpha, -mday, -daylength) %>%
mutate(precip_mm = ifelse(precip_mm < 0, 0, precip_mm)) # # another quick and dirty fix for potential errors - occasional negative precipitation values
}))
# number cells (x-y pairs) to allow raster-based extraction of data
Dat_clim <- Dat_clim %>%
mutate(cell_no = 1:nrow(Dat_clim)) %>%
select(x, y, cell_no, data_full = data_reg)
# filter data to > 1961 (no data for crops from before this)
Dat_clim <- Dat_clim %>%
mutate(data_full = data_full %>%
map(function(df){
df %>%
filter(year >= 1961)
}))
# write out full climate data
write_rds(Dat_clim, "~/Desktop/Global Weather/Model 1/France-full-climate-data-1902-2097.rds")
# how about a helper raster to allow spatial point querying of data?
# number lat/lon values and transform to raster, keep numbers in climate df
Ras_help <- Dat_clim %>%
select(x, y, z = cell_no) %>%
rasterFromXYZ()
# write out
write_rds(Ras_help, "~/Desktop/Global Weather/Model 1/Sweden-climate-data-helper-raster.rds")
Dat_clim <- read_rds("~/Desktop/Global Weather/Model 1/FINAL-sweden-full-climate-data-1902-2097.rds")
Ras_clim <- read_rds("~/Desktop/Global Weather/Model 1/Sweden-climate-data-helper-raster.rds")
sample_n(Dat_clim, 10, replace = F)
Dat_clim$data_full[[1]] %>% head(10)
plot(Ras_clim)
plot(Shp_Fr, add = T)
########### THIS IS WHERE YOU FIGURE OUT LOCATION!##############
lat_lon <- tibble(x = 17.5, y = 60)
clim_coord_no <- raster::extract(Ras_clim, lat_lon)
clim_coord <- as.data.frame(clim_coord_no)
sim_start_year <- 1961 # year simulation to start (min = 1961)
sim_end_year <- 2097 ## year simulation to end (max = 2097)
mean_sim_end <- 0
# climate uncertainty (fractional std. dev. default i.e. no uncertainty = 0)
sd_sim_end <- 0.3
# number of Monte Carlo repetitions
# (more than 100 at your own risk — depending on your processor it may be too much for it to handle)
MC_n <- 100
Dat_clim <- Dat_clim %>%
filter(cell_no == clim_coord_no) %>%
dplyr::select(-cell_no) %>%
slice(rep(1, MC_n)) %>%
add_column(sample = 1:MC_n, .before = "data_full") %>%
mutate(data_full = pmap(list(mean_sim_end, sd_sim_end, sim_start_year, sim_end_year, data_full), function(mean, sd, start, end, df){
df <- df %>% filter(year >= start,
year <= end)
det <- df %>% filter(year < 2020) %>% nrow()
stoch <- df %>% filter(year >= 2020) %>% nrow()
mean_seq <- seq(from = 0, to = mean, length.out = stoch)
sd_seq <- seq(from = 0, to = sd, length.out = stoch)
# stationary autoregressive process
x <- w <- rnorm(n = stoch, mean = mean_seq, sd = sd_seq)
for(t in 2:stoch) x[t] <- (x[t - 1] / 2) + w[t]
x1 <- c(rep(0, det), x)
x <- w <- rnorm(n = stoch, mean = mean_seq, sd = sd_seq)
for(t in 2:stoch) x[t] <- (x[t - 1] / 2) + w[t]
x2 <- c(rep(0, det), x)
x <- w <- rnorm(n = stoch, mean = mean_seq, sd = sd_seq)
for(t in 2:stoch) x[t] <- (x[t - 1] / 2) + w[t]
x3 <- c(rep(0, det), x)
df %>%
mutate(temp_centigrade = temp_centigrade * (1 + x1),
precip_mm = precip_mm * (1 + x2),
pet_mm = pet_mm * (1 + x3),
temp_centigrade = ifelse(temp_centigrade < 0, 0, temp_centigrade),
precip_mm = ifelse(precip_mm < 0, 0, precip_mm),
pet_mm = ifelse(pet_mm < 0, 0, pet_mm)) %>%
return()
}))
# write out climate data
write_rds(Dat_clim, "~/Desktop/Global Weather/Model 1/Sweden-example-climate-data.rds")
# Now lets take a look at temperature
Dat_clim$data_full[[1]] %>% head(100)
predicted_clim_raw <- as.data.frame(Dat_clim$data_full)
pred_precip <- data.frame(predicted_clim_raw$year, predicted_clim_raw$month, predicted_clim_raw$precip_mm)
pred_precip <- aggregate(pred_precip$predicted_clim_raw.precip_mm, by=list(predicted_clim_raw.year =pred_precip$predicted_clim_raw.year), FUN=mean)
names(pred_precip)[names(pred_precip)=='predicted_clim_raw.year'] <- 'Year'
names(pred_precip)[names(pred_precip)=='x'] <- 'Precipitation'
# names(predicted_precip)[names(predicted_precip)=='predicted_clim_raw.month'] <- 'month'
predicted_temp <- data.frame(predicted_clim_raw$month, predicted_clim_raw$year, predicted_clim_raw$temp_centigrade)
predicted_temp <- aggregate(predicted_temp$predicted_clim_raw.temp_centigrade, by=list(predicted_clim_raw.year =predicted_temp$predicted_clim_raw.year), FUN=mean)
predicted_temp
# names(predicted_temp)[names(predicted_temp)=='predicted_clim_raw.month'] <- 'month'
names(predicted_temp)[names(predicted_temp)=='predicted_clim_raw.year'] <- 'year'
names(predicted_temp)[names(predicted_temp)=='x'] <- 'Temperature'
# names(predicted_temp)[names(predicted_temp)=='predicted_clim_raw.precip_mm'] <- 'Precipitation'
predicted_temp[which.max(predicted_temp$Temperature),]
av_pred_clim <- data.frame(predicted_temp$year, predicted_temp$Temperature, pred_precip$Precipitation)
names(av_pred_clim)[names(av_pred_clim)=='predicted_temp.year'] <- 'Year'
names(av_pred_clim)[names(av_pred_clim)=='predicted_temp.Temperature'] <- 'Temperature'
names(av_pred_clim)[names(av_pred_clim)=='pred_precip.Precipitation'] <- 'Precipitation'
ggplot(av_pred_clim, aes(x=Year)) +
geom_line( aes(y=Temperature), color='red') +
geom_line( aes(y=Precipitation/3), color='blue') +
scale_y_continuous(name = "Temperature",
sec.axis = sec_axis(~.*3, name="Precipitation"))+
labs(colour = c("Temperature", "Precipitation"))
# ggplot()+
# geom_line(data=predicted_temp,
# aes(x = year, y= Temperature, colour='red'))+
# geom_line(data=pred_precip,
# aes(x = Year, y= Precipitation), color='blue')
Dat_clim$data_full[[1]] %>% head(10)
predicted_clim_raw <- as.data.frame(Dat_clim$data_full)
predicted_clim5 <- data.frame(predicted_clim_raw$month.5, predicted_clim_raw$year.5, predicted_clim_raw$temp_centigrade.5)
predicted_clim5
pred_precip5 <- data.frame(predicted_clim_raw$year.5, predicted_clim_raw$precip_mm.5)
pred_precip5 <- aggregate(pred_precip5$predicted_clim_raw.precip_mm.5, by=list(predicted_clim_raw.year.5 =pred_precip5$predicted_clim_raw.year.5), FUN=sum)
names(pred_precip5)[names(pred_precip5)=='predicted_clim_raw.year.5'] <- 'Year'
names(pred_precip5)[names(pred_precip5)=='x'] <- 'Precipitation'
predicted_clim5 <- data.frame(predicted_clim_raw$month.5, predicted_clim_raw$year.5, predicted_clim_raw$temp_centigrade.5)
predicted_clim5
names(predicted_clim5)[names(predicted_clim5)=='predicted_clim_raw.month.5'] <- 'month'
names(predicted_clim5)[names(predicted_clim5)=='predicted_clim_raw.year.5'] <- 'year'
names(predicted_clim5)[names(predicted_clim5)=='predicted_clim_raw.temp_centigrade.5'] <- 'Temperature'
predicted_clim5[which.max(predicted_clim5$Temperature),]
av_pred_clim5 <- aggregate(predicted_clim5$Temperature, list(year=predicted_clim5$year), FUN=mean)
names(av_pred_clim5)[names(av_pred_clim5)=='x'] <- 'Temperature'
av_pred_clim5 <- data.frame(av_pred_clim5$year, av_pred_clim5$Temperature, pred_precip5$Precipitation)
names(av_pred_clim5)[names(av_pred_clim5)=='av_pred_clim5.year'] <- 'Year'
names(av_pred_clim5)[names(av_pred_clim5)=='av_pred_clim5.Temperature'] <- 'Temperature'
names(av_pred_clim5)[names(av_pred_clim5)=='pred_precip5.Precipitation'] <- 'Precipitation'
pred_precip1 <- data.frame(predicted_clim_raw$year.1, predicted_clim_raw$precip_mm.1)
pred_precip1 <- aggregate(pred_precip1$predicted_clim_raw.precip_mm.1, by=list(predicted_clim_raw.year.1 =pred_precip1$predicted_clim_raw.year.1), FUN=sum)
names(pred_precip1)[names(pred_precip1)=='predicted_clim_raw.year.1'] <- 'Year'
names(pred_precip1)[names(pred_precip1)=='x'] <- 'Precipitation'
predicted_clim1 <- data.frame(predicted_clim_raw$month.1, predicted_clim_raw$year.1, predicted_clim_raw$temp_centigrade.1)
predicted_clim1
names(predicted_clim1)[names(predicted_clim1)=='predicted_clim_raw.month.1'] <- 'month'
names(predicted_clim1)[names(predicted_clim1)=='predicted_clim_raw.year.1'] <- 'year'
names(predicted_clim1)[names(predicted_clim1)=='predicted_clim_raw.temp_centigrade.1'] <- 'Temperature'
av_pred_clim1 <- aggregate(predicted_clim1$Temperature, list(year=predicted_clim1$year), FUN=mean)
names(av_pred_clim1)[names(av_pred_clim1)=='x'] <- 'Temperature'
av_pred_clim1 <- data.frame(av_pred_clim1$year, av_pred_clim1$Temperature, pred_precip1$Precipitation)
names(av_pred_clim1)[names(av_pred_clim1)=='av_pred_clim1.year'] <- 'Year'
names(av_pred_clim1)[names(av_pred_clim1)=='av_pred_clim1.Temperature'] <- 'Temperature'
names(av_pred_clim1)[names(av_pred_clim1)=='pred_precip1.Precipitation'] <- 'Precipitation'
names(predicted_clim1)[names(predicted_clim1)=='predicted_clim_raw.month.1'] <- 'month'
names(predicted_clim1)[names(predicted_clim1)=='predicted_clim_raw.year.1'] <- 'year'
names(predicted_clim1)[names(predicted_clim1)=='predicted_clim_raw.temp_centigrade.1'] <- 'Temperature'
predicted_clim1[which.max(predicted_clim1$Temperature),]
predicted_clim2 <- data.frame(predicted_clim_raw$month.2, predicted_clim_raw$year.2, predicted_clim_raw$temp_centigrade.2)
predicted_clim2
pred_precip2 <- data.frame(predicted_clim_raw$year.2, predicted_clim_raw$precip_mm.2)
pred_precip2 <- aggregate(pred_precip2$predicted_clim_raw.precip_mm.2, by=list(predicted_clim_raw.year.2 =pred_precip2$predicted_clim_raw.year.2), FUN=sum)
names(pred_precip2)[names(pred_precip2)=='predicted_clim_raw.year.2'] <- 'Year'
names(pred_precip2)[names(pred_precip2)=='x'] <- 'Precipitation'
names(predicted_clim2)[names(predicted_clim2)=='predicted_clim_raw.month.2'] <- 'month'
names(predicted_clim2)[names(predicted_clim2)=='predicted_clim_raw.year.2'] <- 'year'
names(predicted_clim2)[names(predicted_clim2)=='predicted_clim_raw.temp_centigrade.2'] <- 'Temperature'
predicted_clim2[which.max(predicted_clim2$Temperature),]
predicted_clim3 <- data.frame(predicted_clim_raw$month.3, predicted_clim_raw$year.3, predicted_clim_raw$temp_centigrade.3)
predicted_clim3
pred_precip3 <- data.frame(predicted_clim_raw$year.3, predicted_clim_raw$precip_mm.3)
pred_precip3 <- aggregate(pred_precip3$predicted_clim_raw.precip_mm.3, by=list(predicted_clim_raw.year.3 =pred_precip3$predicted_clim_raw.year.3), FUN=sum)
names(pred_precip3)[names(pred_precip3)=='predicted_clim_raw.year.3'] <- 'Year'
names(pred_precip3)[names(pred_precip3)=='x'] <- 'Precipitation'
names(predicted_clim3)[names(predicted_clim3)=='predicted_clim_raw.month.3'] <- 'month'
names(predicted_clim3)[names(predicted_clim3)=='predicted_clim_raw.year.3'] <- 'year'
names(predicted_clim3)[names(predicted_clim3)=='predicted_clim_raw.temp_centigrade.3'] <- 'Temperature'
predicted_clim3[which.max(predicted_clim3$Temperature),]
predicted_clim4 <- data.frame(predicted_clim_raw$month.4, predicted_clim_raw$year.4, predicted_clim_raw$temp_centigrade.4)
predicted_clim4
pred_precip4 <- data.frame(predicted_clim_raw$year.4, predicted_clim_raw$precip_mm.4)
pred_precip4 <- aggregate(pred_precip4$predicted_clim_raw.precip_mm.4, by=list(predicted_clim_raw.year.4 =pred_precip4$predicted_clim_raw.year.4), FUN=sum)
names(pred_precip4)[names(pred_precip4)=='predicted_clim_raw.year.4'] <- 'Year'
names(pred_precip4)[names(pred_precip4)=='x'] <- 'Precipitation'
names(predicted_clim4)[names(predicted_clim4)=='predicted_clim_raw.month.4'] <- 'month'
names(predicted_clim4)[names(predicted_clim4)=='predicted_clim_raw.year.4'] <- 'year'
names(predicted_clim4)[names(predicted_clim4)=='predicted_clim_raw.temp_centigrade.4'] <- 'Temperature'
predicted_clim4[which.max(predicted_clim4$Temperature),]
av_pred_clim1 <- aggregate(predicted_clim1$Temperature, list(year=predicted_clim1$year), FUN=mean)
names(av_pred_clim1)[names(av_pred_clim1)=='x'] <- 'Temperature'
av_pred_clim1 <- data.frame(av_pred_clim1$year, av_pred_clim1$Temperature, pred_precip1$Precipitation)
names(av_pred_clim1)[names(av_pred_clim1)=='av_pred_clim1.year'] <- 'Year'
names(av_pred_clim1)[names(av_pred_clim1)=='av_pred_clim1.Temperature'] <- 'Temperature'
names(av_pred_clim1)[names(av_pred_clim1)=='pred_precip1.Precipitation'] <- 'Precipitation'
av_pred_clim2 <- aggregate(predicted_clim2$Temperature, list(year=predicted_clim2$year), FUN=mean)
names(av_pred_clim2)[names(av_pred_clim2)=='x'] <- 'Temperature'
av_pred_clim2 <- data.frame(av_pred_clim2$year, av_pred_clim2$Temperature, pred_precip2$Precipitation)
names(av_pred_clim2)[names(av_pred_clim2)=='av_pred_clim2.year'] <- 'Year'
names(av_pred_clim2)[names(av_pred_clim2)=='av_pred_clim2.Temperature'] <- 'Temperature'
names(av_pred_clim2)[names(av_pred_clim2)=='pred_precip2.Precipitation'] <- 'Precipitation'
av_pred_clim3 <- aggregate(predicted_clim3$Temperature, list(year=predicted_clim3$year), FUN=mean)
names(av_pred_clim3)[names(av_pred_clim3)=='x'] <- 'Temperature'
av_pred_clim3 <- data.frame(av_pred_clim3$year, av_pred_clim3$Temperature, pred_precip3$Precipitation)
names(av_pred_clim3)[names(av_pred_clim3)=='av_pred_clim3.year'] <- 'Year'
names(av_pred_clim3)[names(av_pred_clim3)=='av_pred_clim3.Temperature'] <- 'Temperature'
names(av_pred_clim3)[names(av_pred_clim3)=='pred_precip3.Precipitation'] <- 'Precipitation'
av_pred_clim4 <- aggregate(predicted_clim4$Temperature, list(year=predicted_clim4$year), FUN=mean)
names(av_pred_clim4)[names(av_pred_clim4)=='x'] <- 'Temperature'
av_pred_clim4 <- data.frame(av_pred_clim4$year, av_pred_clim4$Temperature, pred_precip4$Precipitation)
names(av_pred_clim4)[names(av_pred_clim4)=='av_pred_clim4.year'] <- 'Year'
names(av_pred_clim4)[names(av_pred_clim4)=='av_pred_clim4.Temperature'] <- 'Temperature'
names(av_pred_clim4)[names(av_pred_clim4)=='pred_precip4.Precipitation'] <- 'Precipitation'
p <- ggplot() +
geom_line(data=av_pred_clim5, mapping= aes(x=Year, y=Temperature), color='red') +
geom_line(data=av_pred_clim5, mapping=aes(x=Year, y=Precipitation/40), color='blue') +
geom_line(data=av_pred_clim1, mapping=aes(x=Year, y=Temperature), color='red') +
geom_line(data=av_pred_clim1, mapping=aes(x=Year,y=Precipitation/40), color='blue')+
geom_line(data=av_pred_clim2, mapping=aes(x=Year, y=Temperature), color='red') +
geom_line(data=av_pred_clim2, mapping=aes(x=Year,y=Precipitation/40), color='blue')+
geom_line(data=av_pred_clim3, mapping=aes(x=Year, y=Temperature), color='red') +
geom_line(data=av_pred_clim3, mapping=aes(x=Year, y=Precipitation/40), color='blue')+
geom_line(data=av_pred_clim4, mapping=aes(x=Year, y=Temperature), color='red') +
geom_line(data=av_pred_clim4, mapping=aes(x=Year, y=Precipitation/40), color='blue') +
scale_y_continuous(name = "Annual Average Temperature (Celcius)",
sec.axis = sec_axis(~.*40, name="Annual Total Precipitation (mm)"))+
labs(colour = c("Annual Average Temperature (Celcius)", "Annual Total Precipitation (mm)"))+
theme(panel.background = element_rect(fill = "white", colour = "white"))+
theme(axis.line = element_line(color = "black"))
p
mean(av_pred_clim1$Precipitation)
mean(av_pred_clim2$Precipitation)
mean(av_pred_clim3$Precipitation)
mean(av_pred_clim4$Precipitation)
mean(av_pred_clim5$Precipitation)
x.sub1 <- subset(av_pred_clim1, Year <2019)
mean(x.sub1$Precipitation)
min(x.sub1$Temperature)
max(x.sub1$Temperature)
x.sub1[which.max(x.sub1$Temperature),]
x.sub1[which.min(x.sub1$Temperature),]
av_pred_clim1[which.max(av_pred_clim1$Temperature),]
av_pred_clim2[which.max(av_pred_clim2$Temperature),]
av_pred_clim3[which.max(av_pred_clim3$Temperature),]
av_pred_clim4[which.max(av_pred_clim4$Temperature),]
av_pred_clim5[which.max(av_pred_clim5$Temperature),]
###############
# NOW WE LOOK AT COMPARISONS AND TRY TO SEE WHATS UP
#############ß
manure32 <- read_csv("~/Desktop/Diss-data/Sweden/Manure/compare-manure.csv")
ggplot()+
geom_line(data=manure32, aes(x=Year, y=Total.Carbon, colour=Manure))+
labs(x="Year", y="Total Carbon Stock (t ha-1)", fill="Manure Type") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10))+
theme(panel.background = element_rect(fill = "white", colour = "white"))+
theme(axis.line = element_line(color = "black"))
x.sub2 <- subset(manure, Year >2019, Year <2030)
x.sub3 <- subset(x.sub2, Year < 2030)
ggplot()+
geom_line(data=x.sub3, aes(x=Year, y=Total.Carbon, colour=Manure))+
labs(x="Year", y="Total Carbon Stock (t ha-1)", fill="Manure Type") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10))+
theme(panel.background = element_rect(fill = "white", colour = "white"))+
theme(axis.line = element_line(color = "black"))
crops32 <- read_csv("~/Desktop/Diss-data/Sweden/compare-crops.csv")
ggplot()+
geom_line(data=crops32, aes(x=Year, y=Total.Carbon, colour=Crop))+
labs(x="Year", y="Total Carbon Stock (t ha-1)", fill="Crop") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10))+
theme(panel.background = element_rect(fill = "white", colour = "white"))+
theme(axis.line = element_line(color = "black"))
manure38 <- read_csv("~/Desktop/Diss-data/Sweden/Manure/compare-manure-38.csv")
ggplot()+
geom_line(data=manure38, aes(x=Year, y=Total.Carbon, colour=Manure))+
labs(x="Year", y="Total Carbon Stock (t ha-1)", fill="anure Type") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10))+
theme(panel.background = element_rect(fill = "white", colour = "white"))+
theme(axis.line = element_line(color = "black"))
x.sub4 <- subset(manure38, Year >2019, Year <2030)
x.sub5 <- subset(x.sub4, Year < 2030)
ggplot()+
geom_line(data=x.sub5, aes(x=Year, y=Total.Carbon, colour=Manure))+
labs(x="Year", y="Total Carbon Stock (t ha-1)", fill="Manure Type") +
theme(plot.title = element_text(hjust=0.5)) + theme(axis.text.x=element_text(size=9), legend.title = element_text(size=10))+
theme(panel.background = element_rect(fill = "white", colour = "white"))+
theme(axis.line = element_line(color = "black"))
|
89dbdf7433bc56cd6296c0cdfd1435075c45292b | a3a95b468a64492be0d6067a14b350b4d281a123 | /man/map_5Lto3L.Rd | 47d44d602a7e19ec9ef5c636296009efa6eb79fe | [] | no_license | sheejamk/valueEQ5D | 25555943195782d2b1f1ee6edbb16afe6a9edfb7 | 24a8cba859996fd8c61b38924c4362702c0dc1a8 | refs/heads/master | 2022-10-19T23:07:01.287073 | 2022-10-03T20:20:57 | 2022-10-03T20:20:57 | 197,168,794 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,403 | rd | map_5Lto3L.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/eq5d.R
\name{map_5Lto3L}
\alias{map_5Lto3L}
\title{Function to map EQ-5D-5L scores to EQ-5D-3L index values as per the
specific country and group by gender and age}
\usage{
map_5Lto3L(
eq5dresponse_data,
mobility,
self_care,
usual_activities,
pain_discomfort,
anxiety,
country = "UK",
method = "CW",
groupby = NULL,
agelimit = NULL
)
}
\arguments{
\item{eq5dresponse_data}{the data containing eq5d5L responses}
\item{mobility}{column name for EQ-5D-5L mobility}
\item{self_care}{column name for response for EQ-5D-5L self care}
\item{usual_activities}{column name for response for EQ-5D-5L usual
activities}
\item{pain_discomfort}{column name for response for EQ-5D-5L pain/discomfort}
\item{anxiety}{column name for response for EQ-5D-5L anxiety/depression}
\item{country}{country of interest, by default is UK, if groupby has to
specify the country should be specified}
\item{method}{CW cross walk}
\item{groupby}{male or female -grouping by gender, default NULL}
\item{agelimit}{vector of ages to show upper and lower limits}
}
\value{
index value if success, negative values for failure
}
\description{
Function to map EQ-5D-5L scores to EQ-5D-3L index values
}
\examples{
map_5Lto3L(data.frame(
mo = c(1), sc = c(4), ua = c(4), pd = c(3),
ad = c(3)
), "mo", "sc", "ua", "pd", "ad")
}
|
9d3d64824815f904b00cbe2fff4449ea175b485b | f0820801d84fdc435f14fac1e3da6c74fd948b8b | /3.pre_process2012.R | af2535c91f422e7b4be8ad1b18ff89f637cf2e0d | [] | no_license | mlieng/peds_ready_transfers | 45134389e963a4cec7a4ece5dab0bac6153aff1f | b69626afb8c0c05853452827cb1568a85b71ca4e | refs/heads/master | 2020-06-12T14:24:47.155481 | 2019-11-09T04:22:11 | 2019-11-09T04:22:11 | 194,328,925 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 20,161 | r | 3.pre_process2012.R | # Goal: Extract 2012 individual data, similar to `2.pre-process_and_merge`
# except it doesn't include derivation of hospital-level data
#
# Set-up ----
#
# Import libraries
library(RPostgres) #database
library(tidyverse) # data munging, plotting etc
library(feather) # output
library(icdpicr) # for illness severity
library(lubridate) # for managing dates
library(stringr) # for managing strings
# Parameters
odx_max = 10
run_injury_sev = TRUE
# Custom functions
source('custom_functions/2.complex_chronic_conditions.R')
# Import files
oshpd_folder = file.path(getwd(),'local_data','oshpd_full_data')
urban_classif = file.path(getwd(),'data_dropbox','cdc',
'NCHSURCodes2013.csv')
urban_classif = read.csv(urban_classif, header=TRUE, fileEncoding="UTF-8-BOM")
# county # -> county name
county_map = file.path(getwd(),'data_dropbox', '2019.02.14_county.csv')
county_map = read.csv(county_map, header=TRUE, fileEncoding="UTF-8-BOM")
# icd 9 cm -> 18 groups
ccs_multi_dx_tool = file.path(
'data_dropbox', 'hcup_ahrq_ccs', 'Multi_Level_CCS_2015', 'ccs_multi_dx_tool_2015.csv')
ccs_multi_dx_tool = read.csv(ccs_multi_dx_tool, header=TRUE)
pecarn_illness_severity = read.csv(
'data_dropbox/PECARN_DGS_severity/PECARN_ICD9_MASTER_to_illness_severity.csv')
census.income = read.csv('data_dropbox/census_ACS/s1903_income/ACS_11_5YR_S1903_with_ann.csv')
census.edu = read.csv('data_dropbox/census_ACS/s1501_education/ACS_11_5YR_S1501_with_ann.csv')
#
# Connect to database----
#
con = dbConnect(RPostgres::Postgres(),
dbname='oshpd_postgres',
host="localhost", port=5433,
user='postgres',
password='')
dbListTables(con)
#
# Pull from database----
#
combined_peds = tbl(con, 'combined_peds') # make a dplyr table object
start.time = Sys.time()
# pull from SQL database
encounters = combined_peds %>%
# filter, only choose individuals less than 18
filter(start_year==2012 & age<18) %>%
select(id, database, rln, birthdate, age, age_days, pat_zip, pat_county, sex,
race_group, lang_spoken, start_date, end_date, start_day_of_week,
start_month, start_quarter, start_year, end_year, oshpd_id,
ed_disp, ip_source_site, ip_source_route, ip_source_license, ip_disp,
payer, insurance, ccs_dx_prin, fac_county,
dx_prin, odx1, odx2, odx3, odx4, odx5, odx6, odx7, odx8, odx9, odx10,
# odx11, odx12, odx13, odx14, odx15, odx16, odx17, odx18, odx19, odx20,
# odx21, odx22, odx23, odx24,
ec_prin, ec1, ec2, ec3, ec4) %>%
rename(sql_id = id) %>%
collect()
end.time=Sys.time()
print(paste('Time Finished: ', end.time))
print(end.time-start.time)
#
# Individual Data: Post-process ----
#
#
# __Recode OSHPD data ----
#
data_ = encounters
data_ %>% xtabs(~database+ ip_source_route, data=., addNA=TRUE)
# filter inpatient so that they came through the ed
data_ = data_ %>% filter(database=='edd' | (
database=='pdd' & ip_source_route==1) & !is.na(ip_source_route))
# data_$ip_source_route %>% table(useNA = 'always')
data_ %>% xtabs(~database+ ip_source_route, data=., addNA=TRUE)
# replace 'missing'
data_$rln[data_$rln=="---------"] = NA
# clean up neonate
data_$age_days[data_$age>=1]=NA #replace 0 with NULL
data_$neonate = data_$age_days<28 %>% replace_na(FALSE)
data_$neonate = data_$neonate %>% replace_na(FALSE) # replace age>1 with FALSE
data_ = data_ %>%
mutate(
start_date = ymd(start_date),
end_date = ymd(end_date),
ip_course = paste0(ip_source_site, ip_source_license,
ip_source_route),
has.rln = !is.na(rln),
# transferred = ed_disp %in% c(2,5),
# admitted = ip_source_route==1,
# dc_home = ed_disp==1,
ed_disp2 = case_when(
ip_source_route==1~'admitted',
TRUE~as.character(ed_disp)
),
outcome = case_when(
ed_disp %in% c(2,5) ~ 'transferred',
ip_source_route==1 ~'admitted',
ed_disp==1~'dc home'
),
transferred = outcome=='transferred',
transferred.factor = transferred %>% factor(levels=c('FALSE', 'TRUE')),
transferred.char = as.character(transferred),
# copied from 2018-11-12_Transfer RFS
# recode language spoken
lang_spoken2 = recode(
lang_spoken, ENG='English', SPA='Spanish',
CHI='Chinese',VIE='Vietnamese',ARA='Arabic',`999`='Unknown/I/B',
`*` = 'Unknown/I/B',`-`='Unknown/I/B',.default='Other') %>%
# specify order of factor
factor(levels = c('English', 'Spanish','Arabic', 'Chinese',
'Vietnamese', 'Other', 'Unknown/I/B')),
lang_spoken3 = recode(
lang_spoken, ENG='English', SPA='Spanish', .default='Other/Unknown') %>%
# specify order of factor
factor(levels = c('English', 'Spanish','Other/Unknown')),
# recode race group
race_group2 = recode(
race_group, `1`='White', `2`='Black', `3`='Hispanic', `4`='A/PI',
`5`='AI/AN', `6`='Other', `0`='Unknown') %>%
# specify order of factor
factor(
levels = c('Hispanic', 'White','Black','A/PI',
'Other','Unknown','AI/AN')),
race_group2.5 = recode(
race_group2,
`White` = 'White',
`Black` = 'Black',
`Hispanic` = 'Hispanic/Latino',
`A/PI` = 'Asian/Pacific Islander',
.default = 'Other/Unknown'
) %>% factor(levels=c('White', 'Hispanic/Latino', 'Black', 'Asian/Pacific Islander',
'Other/Unknown')),#relevel('White')
race_group3 = recode(
race_group2,
`White` = 'White',
`Black` = 'Black',
`Hispanic` = 'Hispanic/Latino',
#`A/PI` = 'Asian/Pacific Islander',
.default = 'Other/Unknown'
) %>% factor(levels=c('White', 'Hispanic/Latino', 'Black', #'Asian/Pacific Islander',
'Other/Unknown')),#relevel('White')
# copied from 2018-11-16 test descriptive
sex2 = recode(
sex, F='Female', M='Male') %>% factor(levels=c('Male', 'Female')),
birthdate = ymd(birthdate),
age_exact = (interval(birthdate, start_date))/years(1), # age at beginning of encounter
# originally copied from 2018-11-16 test descriptive
# age categories from NICHD "Standard 6: Age Groups for Pediatric Trials"
age_cats = case_when(
age_days<28 ~ "0-27d",
age_days>=28 & age<1 ~ "28d-12m",
age>=1 & age<2 ~"13-23m",
age>=2 & age<6 ~"2-5y",
age>=6 & age<12~"6-11y",
age>=12 & age<18~"12-17y",
age>=18 & age<21 ~"18-21y" #& age<22)
) %>% factor(
levels=c('0-27d', '28d-12m', '13-23m',
'2-5y', '6-11y', '12-17y', '18-21y')),
age_cats2 = case_when(
age_days<28 ~ "0-27d",
age_days>=28 & age<1 ~ "28d-12m",
age>=1 & age<12 ~ "1y-11y",
age>=12 & age<18 ~"12y-17y",
age>=18 & age<21 ~NA_character_) %>% factor(
levels=c('0-27d', '28d-12m', '1y-11y',
'12y-17y', '18-21y')
), #%>% relevel('12y-17y'),
age_cats3 = case_when(
age_days<28 ~ "0-27d",
age_days>=28 & age<1 ~ "28d-12m",
age>=1 & age<18 ~"1y-17y",
age>=18 & age<21 ~NA_character_) %>% factor(
levels=c('0-27d','28d-12m','1y-17y')) ,#%>% relevel('1y-17y'),
start_weekend = start_day_of_week %in% c('Sat', 'Sun'),
start_month.factor = factor(start_month, levels=c(1:12) %>% as.character()),
enc_season = case_when(
start_month %in% c(12,1,2) ~ "Winter",
start_month %in% c(3,4,5) ~ "Spring",
start_month %in% c(6,7,8) ~ "Summer",
start_month %in% c(9,10,11) ~ "Fall") %>%
factor(levels = c('Winter', 'Spring', 'Summer', 'Fall')),
# ccs mental health #TODO double check if this is correct
# ccs_mental_health = ccs_dx_prin >= 650 & ccs_dx_prin <= 670
insurance2.5 = recode(insurance,
`Private`='Private',
`Public-Medicare-MediCal`='Public',
`Self-Pay`='Uninsured/self-pay', #self-pay is the same as uninsured
.default='Other'
) %>% factor(levels=c('Private', 'Public', 'Uninsured/self-pay',
'Other')),
# recode similar to Huang paper
insurance2 =case_when(
database=='pdd' & payer=='3'~'Private',
database=='pdd' & payer=='2'~'Medicaid',
database=='pdd' & payer=='8'~'Uninsured/self-pay',
database=='pdd' & payer %in% c('4', '5', '6', '7', '9')~'Other',
database=='pdd' & payer=='1'~'Medicare',
database=='pdd' & payer=='9'~'Unknown',
database=='edd' & payer %in% c('12','13','14','16','BL','CI','HM')~'Private',
database=='edd' & payer=='MC'~'Medicaid',
database=='edd' & payer=='09'~'Uninsured/self-pay',
database=='edd' & payer %in% c('11','AM','CH','DS','OF', 'TV','VA','WC','00')~'Other',
database=='edd' & payer %in% c('MA','MB')~'Medicare',
database=='edd' & payer=='99'~'Unknown'
) %>% factor(levels=c('Medicaid', 'Private', 'Uninsured/self-pay', 'Medicare','Other', 'Unknown')),
insurance3 = recode(
insurance2, 'Medicare'='Other', 'Unknown'=NA_character_) %>%
factor(levels=c('Medicaid', 'Private', 'Uninsured/self-pay','Other')
),
has_medicare = insurance2 =='Medicare'
)
#
# __Clinical Classifications Software (18 categories) ----
#
ccs = ccs_multi_dx_tool %>%
# clean up
mutate(dx_prin = X.ICD.9.CM.CODE. %>% str_remove_all("\'") %>% str_trim(),
ccs_group = as.integer(X.CCS.LVL.1.),
# combine 'Mental illness' with '
ccs_label = X.CCS.LVL.1.LABEL. %>% str_replace('Mental illness', 'Mental Illness')) %>%
select(dx_prin, ccs_group, ccs_label)
# translate principle diagnosis
data_ = left_join(data_, ccs, by='dx_prin')
# translate other diagnoses
orig_cols = c('dx_prin', 'ccs_group', 'ccs_label')
for(i in seq(1:odx_max)){
new_cols = c(paste0('odx',i), paste0('ccs_group.',i), paste0('ccs_label.',i))
data_ = ccs %>%
# rename columns to the appropriate number (e.g. dx_prin -> odx1, ccs_group --> ccs_group.1)
select(orig_cols) %>% setNames(new_cols) %>%
left_join(data_, ., by=paste0('odx',i))
}
# count number of injury codes
df_has_injury = data_%>% select(starts_with('ccs_label')) %>%
mutate_all(~(.=='Injury and poisoning'))
data_$ccs_injury_count = apply(df_has_injury, 1, function(x) sum(x, na.rm=TRUE))
remove(df_has_injury)
# convert counting
data_ = data_ %>% mutate(
ccs_injury_any = ccs_injury_count >= 1, #replace_na(FALSE), unnecessary
ccs_mental_health = ccs_label =='Mental Illness',
ccs_injury = ccs_label == 'Injury and poisoning'
)
#
# __PECARN Illness Severity (Based on ICD9) (Alessandrini et al. 2012)----
#
illness_severity = pecarn_illness_severity %>% mutate(
dx_prin = ICD9_Code %>% as.character(),
sev.score = Severity_Score,
# create variable where "other categories" -> NA (missing)
sev.score.int = recode(
Severity_Score,
"1" = '1',
"2" = '2',
"3" = '3',
"4" = '4',
"5" = '5',
"Invalid: Additional digit required" = NA_character_,
"Not Categorized" = NA_character_,
"No code entered" = NA_character_
) %>% as.numeric(),
sev.score.factor = sev.score %>% factor(levels=c('1','2','3','4','5')),
sev.major_group = Major_Group_Desc,
sev.subgroup = Subgroup_Desc
) %>% select(dx_prin, sev.score, sev.score.factor, sev.score.int, sev.major_group, sev.subgroup)
# join with data
data_ = left_join(data_, illness_severity, by='dx_prin')
# translate other diagnoses
orig_cols = c('dx_prin', 'sev.score.int')
for(i in seq(1:odx_max)){
new_cols = c(paste0('odx',i), paste0('sev.score.int.',i))
data_ = illness_severity %>%
# rename columns to the appropriate number (e.g. dx_prin -> odx1, sev.score.int --> sev.score.int.1)
select(orig_cols) %>% setNames(new_cols) %>%
# merge with original data
left_join(data_, ., by=paste0('odx',i))
}
# otherwise outputs an error if all are NA
my.max <- function(x) ifelse( !all(is.na(x)), max(x, na.rm=T), NA)
# calculate maximum illness severity
data_$sev.all.max.int = data_ %>%
select(starts_with('sev.score.int')) %>%
apply(1, my.max)
data_ = data_ %>% mutate(
sev.all.max.factor = factor(sev.all.max.int, levels=c('1','2','3','4','5'))
)
#
# __Complex Chronic Conditions (Feudtner et al. 2014) ----
#
# Note: When doing PAT will need to use the four different categories and combine together
# data_ = data_ %>% select(dx_prin, starts_with('odx'))
# convert principle diagnosis
data_ = data_ %>% mutate(
ccc_label = convert_icd9dx_TO_ccc(dx_prin),
has_ccc = !is.na(ccc_label)
)
# convert other diagnoses
for(i in seq(1:odx_max)){
data_[[paste0('ccc_label.',i)]] = convert_icd9dx_TO_ccc(data_[[paste0('odx',i)]])
}
# count number of injury codes
data_$ccc_count = data_ %>%
select(starts_with('ccc_label')) %>%
mutate_all(~(!is.na(.))) %>% # checks if there is a label for type
# select(ccc_label, ccc_label.1, ccc_label.2) %>%
# calculates the sum
apply(1, function(x) sum(x, na.rm=TRUE))
data_ = data_ %>% mutate(
has_ccc_any = ccc_count >=1, # don't need replaceNA, if all are NA --> 0
has_ccc_any.factor = has_ccc_any %>% factor(levels=c('FALSE', 'TRUE'))
)
#
# __Injury Severity Score (Clark 2018) ----
#
# https://github.com/ablack3/icdpicr, https://link.springer.com/article/10.1186/s40621-018-0149-8
old_cols = c('sql_id', 'dx_prin', paste0(rep('odx', odx_max), seq(1:odx_max))) #odx1, odx2...odx(n)
new_cols = c('sql_id', paste0(rep('dx', odx_max), seq(1:odx_max+1))) #dx1, dx2 ... dx(n+1)
# needs to be in the format 'id, dx1, dx2 ....dxn'
df_in = data_ %>%
# filter(ccs_injury_any) %>%
select(old_cols) %>% setNames(new_cols)
if(run_injury_sev){
start.time = Sys.time()
iss = df_in %>% icdpicr::cat_trauma('dx', icd10=FALSE)
remove(df_in)
end.time=Sys.time()
print(paste('Time Finished: ', end.time))
print(end.time-start.time)
iss2 = iss %>% select(sql_id, maxais, riss, sev_1) %>%
rename(injury.sev = riss,
max.injury.sev=maxais, # 9 = unknown
injury.sev.dx_prin = sev_1 ) %>% #9 = unknown) %>%
mutate(
# recode into categories based on Huang 2017
injury.sev.cat = case_when(
injury.sev >=1 & injury.sev<=9 ~ 'Minor',
injury.sev >= 10 ~ 'Moderate to severe'
), # can go from 0 ---> 100
# maximum injury severity
max.injury.sev2 = case_when(
max.injury.sev==9 ~ 'Unknown',
is.na(max.injury.sev) ~ 'Missing/Not Assigned',
TRUE ~ as.character(max.injury.sev)
), # 2 types of missing
max.injury.sev.factor = max.injury.sev %>%
factor(levels=c(1,2,3,4,5,6,9),
labels=c('Minor', 'Moderate', 'Serious', 'Severe', 'Critical', 'Unsurvivable', 'Unknown')) %>%
relevel(1), # drops 0
max.injury.sev.int = max.injury.sev %>% replace(max.injury.sev==9, NA) %>% as.numeric(),
# injury severity based on principle diagnosis
injury.sev.dx_prin2 = case_when(
injury.sev.dx_prin==9 ~ 'Unknown',
is.na(injury.sev.dx_prin) ~ 'Missing/Not Assigned',
TRUE ~ as.character(injury.sev.dx_prin)
), # 2 types of missing
injury.sev.dx_prin.factor = injury.sev.dx_prin %>%
factor(levels=c(1,2,3,4,5,6,9),
labels=c('Minor', 'Moderate', 'Serious', 'Severe', 'Critical', 'Unsurvivable', 'Unknown')) %>%
relevel(1), # drops 0
injury.sev.dx_prin.int = injury.sev.dx_prin %>% replace(injury.sev.dx_prin==9, NA) %>% as.numeric()
)
# join data
data_ = left_join(data_, iss2, by='sql_id')
remove(iss)
} else {message('Did not run injury severity score algorithm')}
#
# __Census Data (American FactFinder)----
#
# Income Data
# set 1st row as labels and delete
census.income.labels = census.income[1,] %>% mutate_all(as.character)
Hmisc::label(census.income) = census.income.labels
census.income = census.income %>% slice(2:nrow(census.income))
census.income.subset = census.income %>%
select(GEO.id2,HC02_EST_VC02) %>%
# rename to human readable
rename(
census.zcta = GEO.id2,
census.med.income = HC02_EST_VC02) %>%
mutate(
census.zcta = census.zcta %>% as.character %>% as.numeric,
census.med.income = census.med.income %>%
as.character() %>%
str_replace_all(
c('2,500-' = '2500',
'250,000\\+' = '250000',
'-' = NA_character_ )) %>%
as.numeric()
)
#
# Education Data
#
# set 1st row as labels and delete
census.edu.labels = census.edu[1,] %>% mutate_all(as.character)
Hmisc::label(census.edu) = census.edu.labels
census.edu = census.edu %>% slice(2:nrow(census.edu))
# subset and rename
census.edu.subset = census.edu %>%
select(GEO.id2, HC01_EST_VC16, HC01_EST_VC17) %>%
# rename to human-human readable
rename(
census.zcta=GEO.id2,
census.hs_higher=HC01_EST_VC16,
census.bach_higher=HC01_EST_VC17
) %>%
mutate(
census.hs_higher = replace(census.hs_higher, census.hs_higher=='-', NA),
census.bach_higher = replace(census.bach_higher, census.bach_higher=='-', NA)
) %>%
# convert all to numeric
mutate_if(is.factor, ~as.numeric(as.character(.)))
census.data = full_join(census.income.subset, census.edu.subset, by='census.zcta') %>%
filter(!is.na(census.zcta)) %>% mutate(pat_zip = as.character(census.zcta))
data_ = left_join(data_, census.data, by='pat_zip')
# Remove extra data sets
remove(list=c('census.income', 'census.income.labels', 'census.income.subset',
'census.edu', 'census.edu.labels', 'census.edu.subset'))
#
# __NCHS Urban Rural Designation----
#
NCHS_urban_rural_scheme = c(
'Large central metro', 'Large fringe metro', 'Medium metro',
'Small metro','Micropolitan','Noncore')
urban_classif_reduced = urban_classif %>% filter(State.Abr.=='CA') %>%
mutate(county = County.name %>% str_replace_all(" County", ""),
fac_county.name = county,
pat_county.name = county,
urban_rural.int = X2013.code,
urban_rural.factor = factor(X2013.code, levels=c(1,2,3,4,5,6),
labels=NCHS_urban_rural_scheme),
urban_rural.factor2 = case_when(
#X2013.code==5~4,
X2013.code==6~5,
TRUE~as.numeric(X2013.code)
) %>% factor(levels=c(1,2,3,4,5),
labels=c('Large central metro', 'Large fringe metro',
'Medium metro', 'Small metro', 'Non metro'))
)
# recode OSHPD data from numbers to county names (e.g. 58 -> Yuba)
county_map = county_map %>% mutate(
County = County %>% as.character() %>% str_trim(),
fac_county = pat_county,
pat_county.name = County,
fac_county.name = County
)
# add county names for patient
data_ = county_map %>% select(pat_county, pat_county.name) %>%
left_join(data_, ., by='pat_county')
# add rurality
data_ = urban_classif_reduced %>%
rename(nchs.pat_urban_rural = urban_rural.factor,
nchs.pat_urban_rural2 = urban_rural.factor2,
nchs.pat_urban_rural.int = urban_rural.int) %>%
select(pat_county.name, nchs.pat_urban_rural, nchs.pat_urban_rural2,
nchs.pat_urban_rural.int) %>%
left_join(data_, ., by='pat_county.name')
# Export data----
write_feather(data_, 'local_transfers_dev/2019-05-14_2012_all_peds.feather')
|
33ce765c3d94ec39d5a43f1bf9f7ec31abad6435 | 7ce20df30ce7a013177aad42b13ef7497c6e8fde | /scriptTests/depends.r | 2784820bf59cb0eb8253abebfbcc630b3d6163ed | [] | no_license | Gabriel-Cardoso-de-Carvalho/RProvenance | 4d2e57e155fd77509884dde74936935dacceb5aa | 9a65ee951187857de4aa41affb9c79f8d4054edd | refs/heads/master | 2020-05-21T02:57:38.968905 | 2019-06-28T21:27:01 | 2019-06-28T21:27:01 | 185,888,266 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,418 | r | depends.r | ### DEPENDS.R ###
#
# This file checks the current R installation for packages on which
# tests in examples/ depend on. It attempts to install them if they
# are not installed yet.
###
usePackage <- function(p) {
print(p)
if (!is.element(p, installed.packages()[,1])){
print("Installing...")
install.packages(p, dependencies = TRUE, repos = "http://cran.us.r-project.org",
clean=TRUE, quiet=TRUE)
}
print("Installed!")
return(TRUE)
}
installFonts <- function() {
# create folder to store fonts and add to search path
path <- path.expand("~/.fonts")
dir.create(path, showWarnings=FALSE)
font.paths(path)
download.file("http://simonsoftware.se/other/xkcd.ttf", destfile="~/.fonts/xkcd.ttf", mode="wb")
font.add("xkcd", regular = path.expand("~/.fonts/xkcd.ttf"))
font_import(paths= path.expand("~/.fonts"), prompt=FALSE)
}
# List of packages that are needed
pkgs <- c("RDataTracker", "chron", "gWidgets", "dplR", "zoo", "ggplot2",
"gdata", "grid", "gridExtra", "mgcv", "akima", "spatstat", "reshape2", "RCurl", "plyr",
"xkcd", "sysfonts", "extrafont")
# Install the packages that might be missing
if (all(unlist(Map(usePackage, pkgs)))) print("All required packages installed.")
# Once installed, we want to require the sysfonts package to check for the xckd font
# require(sysfonts)
# require(extrafont)
# if (!("xkcd.ttf" %in% font.files())) installFonts()
|
c05bbc10d5fb84ab3acb315f795c799480d3508a | 634907fa4b9ab946b9285b09e1614b363a8f9726 | /ModelTesting.R | d0ebe490cbc6b7ff85abff35b476f49476bf9c07 | [] | no_license | sophiehiscock/ST201-Sleep-Project | ea4f6647f28000169e8b47d2326c967a062a9768 | b2ea31be80149d3be50cc72370a0d7a9399ee9ed | refs/heads/master | 2020-04-30T08:18:50.640565 | 2019-04-26T22:26:58 | 2019-04-26T22:26:58 | 176,711,528 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 7,681 | r | ModelTesting.R | #dat<-read.csv("sleepedit.csv",header=T) #pre-edited data, without aliased coefficients
dat<-read.csv("sleepcut.csv", header=T) #missing first 10 rows so we can test with this later
head(dat)
#Testing variables from each group
dat$LarkOwl<-relevel(dat$LarkOwl,ref="Neither")
m5<-lm(CognitionZscore~Gender + LarkOwl + NumEarlyClass + ClassesMissed + PoorSleepQuality + PoorSleepQuality*ClassesMissed + GPA + DASScore + Drinks + WeekdayRise , data=dat)
summary(m5)
fullm5<-lm(CognitionZscore~ Gender + LarkOwl + NumEarlyClass + ClassesMissed + PoorSleepQuality + PoorSleepQuality*ClassesMissed + GPA + Happiness + Drinks + WeekdayRise , data=dat)
summary(fullm5)
m6<-lm(CognitionZscore~ Gender + NumEarlyClass + ClassesMissed + PoorSleepQuality + PoorSleepQuality*ClassesMissed + GPA + DASScore + Drinks + WeekdayRise + NumEarlyClass*GPA, data=dat)
summary(m6)
anova(m6)
m7<-lm(CognitionZscore~ Gender + NumEarlyClass + ClassesMissed + PoorSleepQuality + PoorSleepQuality*ClassesMissed + GPA + StressScore + Drinks + WeekdayRise + NumEarlyClass*GPA, data=dat)
summary(m7)
anova(m7)
m8<-lm(CognitionZscore~ Gender + NumEarlyClass + ClassesMissed + PoorSleepQuality + GPA+ PoorSleepQuality*GPA + StressScore + Drinks + WeekdayRise + NumEarlyClass*GPA, data=dat)
summary(m8)
m9<- lm(CognitionZscore~ Gender + NumEarlyClass + EarlyClass + ClassesMissed + PoorSleepQuality + GPA+ PoorSleepQuality*GPA + NumEarlyClass*PoorSleepQuality+ StressScore + Drinks + WeekdayRise + NumEarlyClass*GPA, data=dat)
summary(m9)
new.dat<-read.csv("ExtraData.csv")
predict(m9, newdata=new.dat, interval='confidence')
pred.int <- predict(m9, interval = "prediction")
mydata <- cbind(dat, pred.int)
# 2. Regression line + confidence intervals
library("ggplot2")
p <- ggplot(mydata, aes(x=all.vars(), CognitionZscore)) +
geom_point() +
stat_smooth(method = lm)
# 3. Add prediction intervals
p + geom_line(aes(y = lwr), color = "red", linetype = "dashed")+
geom_line(aes(y = upr), color = "red", linetype = "dashed")
#Building from m9
m10<- lm(CognitionZscore~ Gender + NumEarlyClass + EarlyClass + ClassesMissed + PoorSleepQuality + GPA+ PoorSleepQuality*GPA + NumEarlyClass*PoorSleepQuality+ StressScore + Drinks + WeekdayRise + WeekdayBed + NumEarlyClass*GPA, data=dat)
summary(m10)
predict(m10, newdata=new.dat, interval='confidence')
#Building from m10 - exchanging stress for anxiety
m11<- lm(CognitionZscore~ Gender + NumEarlyClass + EarlyClass + ClassesMissed + PoorSleepQuality + GPA+ PoorSleepQuality*GPA + NumEarlyClass*PoorSleepQuality+ AnxietyScore + Drinks + WeekdayRise + WeekdayBed + NumEarlyClass*GPA, data=dat)
summary(m11)
#Building from m11
m12<- lm(CognitionZscore~ Gender + NumEarlyClass + EarlyClass + PoorSleepQuality + GPA+ PoorSleepQuality*GPA + NumEarlyClass*PoorSleepQuality+ StressScore + Drinks + WeekdayRise + WeekdayBed + NumEarlyClass*GPA, data=dat)
summary(m12)
predict(m12, newdata=new.dat, interval='confidence')
#Building from m12
#Best Model So Far
m13<- lm(CognitionZscore~ Gender + NumEarlyClass + EarlyClass + PoorSleepQuality + GPA+ PoorSleepQuality*GPA + NumEarlyClass*PoorSleepQuality+ StressScore + Drinks + WeekdayBed + WeekdayRise + WeekdayRise*GPA+ NumEarlyClass*GPA, data=dat)
summary(m13)
predict(m13, newdata=new.dat, interval='confidence')
#_____________________________#
#Analysing modle m13
#LINEARITY?
m13.stdres<- rstandard(m13)
with(dat, plot(GPA, m13.stdres))
with(dat, plot(StressScore, m13.stdres))
with(dat, plot(ClassesMissed, m13.stdres))
with(dat, plot(EarlyClass*ClassesMissed, m13.stdres))
with(dat, plot(WeekdayBed, m13.stdres))
#NORMALITY?
#histogram
hist(m13.stdres)
plot(density(m13.stdres))
#Q-Q plot
plot(m4, which=c(2))
#P-P plot
probDist <- pnorm(m13.stdres)
plot(ppoints(length(m13.stdres)), sort(probDist), main = 'PP Plot', xlab = 'Observed Probability', ylab = 'Expected Probability')
#CONSTANT VARIANCE?
plot(m13, which=c(1))
#INDEPENDENCE?
plot(m13.stdres)
#Other areas to test
#COLLINEARITY?
#correlation matrix, >|0.8|?
dtf <- subset(dat, select = c(StressScore,ClassesMissed,GPA,EarlyClass,NumEarlyClass,Gender,WeekdayRise,WeekdayBed))
cor(dtf[sapply(dtf, is.numeric)])
cor(dat$NumEarlyClass,dat$EarlyClass) #0.8089492
#scatterplot matrix
pairs(dtf[sapply(dtf, is.numeric)])
#VIF, >10? serious problem
install.packages('car')
library(car)
vif(m4) #NumEarlyClass, EarlyClass and their product~3
#Testing Data
install.packages("sigr")
rand <- sample(1:254, 20, replace = FALSE)
test <- dat[rand, ]
a <- predict(m4,newdata=test,interval='confidence')
cor(test$CognitionZscore, a)
#d<-data.frame(prediction=test$CognitionZscore,actual=dat$CognitionZscore)
#cor.test(d$prediction,d$actual)
rand <- sample(1:254, 20, replace = FALSE)
test <- dat[rand, ]
a <- predict(m4,newdata=test,interval='confidence')
cor(test$CognitionZscore, a)
rand <- sample(1:254, 25, replace = FALSE)
test <- dat[rand, ]
a <- predict(m13,newdata=test,interval='confidence')
cor(test$CognitionZscore, a)
rand <- sample(1:254, 25, replace = FALSE)
test <- dat[rand, ]
a <- predict(m4,newdata=test,interval='confidence')
cor(test$CognitionZscore, a)
rand <- sample(1:254, 25, replace = FALSE)
test <- dat[rand, ]
a <- predict(m1,newdata=test,interval='confidence')
cor(test$CognitionZscore, a)
#building from m3
m3<-lm(CognitionZscore~ WeekdayRise+StressScore+ClassesMissed+EarlyClass*ClassesMissed+GPA+EarlyClass+NumEarlyClass+Gender, data=dat)
summary(m3)
m4<-lm(CognitionZscore~ NumEarlyClass+StressScore+ClassesMissed+EarlyClass*ClassesMissed+GPA+EarlyClass+Gender, data=dat)
summary(m4)
#Partial F tests__________________________________________________________
#StressScore*Gender
full1<-lm(CognitionZscore~ StressScore*Gender+NumEarlyClass+StressScore+ClassesMissed+EarlyClass*ClassesMissed+GPA+EarlyClass+Gender, data=dat)
anova(full1,m4)
#compare with m1
summary(m1)
anova(m1,m4) #SIGNIFICANT YASSSSS
#AlcoholUse
full2<-lm(CognitionZscore~factor(AlcoholUse)+ClassYear+NumEarlyClass+StressScore+ClassesMissed+EarlyClass*ClassesMissed+GPA+EarlyClass+Gender, data=dat)
anova(full2,m4)
summary(full2)
#Drinks
full3<-lm(CognitionZscore~Drinks+ClassYear+NumEarlyClass+StressScore+ClassesMissed+EarlyClass*ClassesMissed+GPA+EarlyClass+Gender, data=dat)
anova(full3,m4)
#AverageSleep
full4<-lm(CognitionZscore~AverageSleep+ClassYear+NumEarlyClass+StressScore+ClassesMissed+EarlyClass*ClassesMissed+GPA+EarlyClass+Gender, data=dat)
anova(full4,m4)
#testing assumptions on m3______________________________________________________
#LINEARITY?
m4.stdres<- rstandard(m4)
with(dat, plot(GPA, m4.stdres))
with(dat, plot(StressScore, m4.stdres))
with(dat, plot(ClassesMissed, m4.stdres))
with(dat, plot(EarlyClass*ClassesMissed, m3.stdres))
#NORMALITY?
#histogram
hist(m4.stdres)
plot(density(m4.stdres))
#Q-Q plot
plot(m4, which=c(2))
#P-P plot
probDist <- pnorm(m4.stdres)
plot(ppoints(length(m4.stdres)), sort(probDist), main = 'PP Plot', xlab = 'Observed Probability', ylab = 'Expected Probability')
#CONSTANT VARIANCE?
plot(m4, which=c(1))
#INDEPENDENCE?
plot(m4.stdres)
#Other areas to test
#COLLINEARITY?
#correlation matrix, >|0.8|?
dtf <- subset(dat, select = c(StressScore,ClassesMissed,GPA,EarlyClass,NumEarlyClass,Gender))
cor(dtf[sapply(dtf, is.numeric)])
cor(dat$NumEarlyClass,dat$EarlyClass) #0.8089492
#scatterplot matrix
pairs(dtf[sapply(dtf, is.numeric)])
#VIF, >10? serious problem
install.packages('car')
library(car)
vif(m4) #NumEarlyClass, EarlyClass and their product~3
#Testing heteroskedasticity
dat$resi<-m4$residuals
library(ggplot2)
ggplot(data=dat, aes_(y = CognitionZScore, x = all.vars()) + geom_point(col = 'blue') + geom_abline(slope = 0)) |
039bfed5184e9b53eb18e22c4c9e558923fc5f19 | 0893b15352297d95bc5a51997b8e73a085620a54 | /r_plotting.r | a22e75860054d7883dcee4fe0189234b5e591d9a | [] | no_license | mrinalmanu/chipseq_and_peak_calling_pipelines | 893258e9a731e14b3fd70e704a81797513836006 | 5e9238349535ae5e953733306291b1da09546b5e | refs/heads/master | 2020-05-17T10:15:31.073959 | 2019-04-26T18:28:50 | 2019-04-26T18:28:50 | 183,652,574 | 4 | 0 | null | null | null | null | UTF-8 | R | false | false | 994 | r | r_plotting.r |
#_________________________________________________________________________________________
install.packages('BiocManager')
# .libPaths("/tmp/RtmpYs45an/downloaded_packages")
library(BiocManager)
BiocManager::install('ChIPseeker')
BiocManager::install('TxDb.Hsapiens.UCSC.hg19.knownGene')
BiocManager::install('org.Hs.eg.db')
library(ChIPseeker)
library(TxDb.Hsapiens.UCSC.hg19.knownGene)
library(org.Hs.eg.db)
peaks <- readPeakFile("/home/manu/Documents/chipseq_and_peak_calling_pipelines/main/macs2_broad/GSM1102797_CD14_H3K4me3_hg19.chr15_hg19_broad_0.1_peaks.broadPeak")
peaks
txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene
peakAnno <- annotatePeak("/home/manu/Documents/chipseq_and_peak_calling_pipelines/main/macs2_broad/GSM1102797_CD14_H3K4me3_hg19.chr15_hg19_broad_0.1_peaks.broadPeak", tssRegion=c(-3000, 3000), TxDb=txdb, annoDb="org.Hs.eg.db")
plotAnnoPie(peakAnno)
plotAnnoBar(peakAnno)
#_________________________________________________________________________________________
|
93e3a828e73d158c7f33280682d742c125e714c4 | 774df122ebc991da788d6ef4ffd5fea804ffd93c | /CODE/07-functional_diversity_plot.R | 127b57e2989383f0b8ae442c99cc8daf399096d1 | [
"MIT"
] | permissive | wabarr/heterogeneity-functional-traits | 7875b18b6a614018419897969ecd635b15df9e39 | 12f0a049cbb5f5cd80215f8d51cec64b61120eda | refs/heads/master | 2021-04-17T12:41:03.560430 | 2020-04-02T19:02:07 | 2020-04-02T19:02:07 | 249,446,134 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 5,314 | r | 07-functional_diversity_plot.R | library(ggplot2)
StatChull <- ggproto("StatChull", Stat,
compute_group = function(data, scales) {
data[chull(data$x, data$y), , drop = FALSE]
},
required_aes = c("x", "y")
)
stat_chull <- function(mapping = NULL, data = NULL, geom = "polygon",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {
layer(
stat = StatChull, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
theme_set(theme_classic(6))
## multivariate richness
set.seed(14)
n <- 30
forgg <- data.frame(trait1=rnorm(n,sd=1),
trait2=rnorm(n, sd=1),
FRic=rep(c("High","Low"), each=n/2))
fric <- ggplot(forgg, aes(trait1, trait2)) +
geom_point(size=2) +
stat_chull(linetype="dashed", color="black", alpha=0.3) +
theme(legend.position = "none") +
labs(x="PCoA Axis 1", y="PCoA Axis 2", title="Functional richness (FRic)\nconvex hull volume") +
scale_fill_manual(values=c("#a4c045", "#045480")) +
scale_color_manual(values=c("#a4c045", "#045480"))
## Evenness
tree <- ape::mst(dist(forgg[,c("trait1","trait2")]))
edgeCount <- length(which(tree==1))
edgelist <- data.frame(from=rep(NA, edgeCount), to=rep(NA, edgeCount))
counter<-1
for(i in 1:nrow(tree)){
for(j in 1:nrow(tree)){
if(tree[i,j]==1){
edgelist[counter,] <- c(i, j)
counter <- counter + 1
}
}}
edgelist$trait1_from <- forgg$trait1[edgelist$from]
edgelist$trait2_from <- forgg$trait2[edgelist$from]
edgelist$trait1_to <- forgg$trait1[edgelist$to]
edgelist$trait2_to <- forgg$trait2[edgelist$to]
feve <- ggplot(forgg, aes(trait1, trait2)) +
geom_segment(edgelist,
mapping=aes(x=trait1_from, y=trait2_from, xend=trait1_to, yend=trait2_to),
color="grey70") +
geom_point(size=2) +
labs(x="PCoA Axis 1", y="PCoA Axis 2", title="Functional Evenness (FEve)\nregularity on min. spanning tree")
## Functional Diversity (FDiv)
centroid_trait1 <- mean(forgg$trait1)
centroid_trait2 <- mean(forgg$trait2)
forgg$dist_from_centroid <- as.matrix(dist(data.frame(trait1=c(centroid_trait1,forgg$trait1), trait2=c(centroid_trait2,forgg$trait2))))[2:(nrow(forgg)+1),1]
# fdis<-ggplot(forgg, aes(trait1, trait2)) +
# geom_segment(aes(x=trait1,
# y=trait2,
# xend=centroid_trait1,
# yend=centroid_trait2),
# size=0.2) +
# geom_point(size=2) +
# annotate("point", x=centroid_trait1, y=centroid_trait2, size=3, color="#045480", shape=15) +
# #annotate("text", x=2.05, y=-1.05, label=paste0("bar('dC')"), parse=TRUE, color="#a4c045", size=14) +
# #scale_x_continuous(limits=c(-4, 2.5)) +
# #scale_y_continuous(limits=c(-4, 2.5)) +
# theme(
# panel.grid.major.y = element_blank(),
# panel.grid.major.x = element_blank(),
# panel.grid.minor.y = element_blank(),
# panel.grid.minor.x = element_blank(),
# ) +
# labs(x="PCoA Axis 1", y="PCoA Axis 2", title="Functional dispersion (FDis)\nsummed distances from centroid\n ")
#
chull_indices <- chull(forgg$trait1, forgg$trait2)
centroid_hull_trait1 <- mean(forgg$trait1[chull_indices])
centroid_hull_trait2 <- mean(forgg$trait2[chull_indices])
forgg$dist_from_hull_centroid <- as.matrix(dist(data.frame(trait1=c(centroid_hull_trait1,forgg$trait1), trait2=c(centroid_hull_trait2,forgg$trait2))))[2:(nrow(forgg)+1),1]
fdiv<-ggplot(forgg, aes(trait1, trait2)) +
stat_chull(linetype="dashed", color="black", alpha=0.3) +
geom_segment(data=dplyr::filter(forgg, dist_from_hull_centroid > mean(dist_from_hull_centroid)),
aes(x=trait1,
y=trait2,
xend=centroid_hull_trait1,
yend=centroid_hull_trait2),
color="red", size=0.2, linetype="longdash") +
annotate("polygon",
x=centroid_hull_trait1 + mean(forgg$dist_from_hull_centroid)* cos(seq(0,2*pi,length.out=100)),
y=centroid_hull_trait2 + mean(forgg$dist_from_hull_centroid)* sin(seq(0,2*pi,length.out=100)), fill="white", color="#a4c045") +
geom_segment(data=dplyr::filter(forgg, dist_from_hull_centroid < mean(dist_from_hull_centroid)),
aes(x=trait1,
y=trait2,
xend=centroid_hull_trait1,
yend=centroid_hull_trait2),
size=0.2) +
geom_point(size=2) +
annotate("point", x=centroid_hull_trait1, y=centroid_hull_trait2, size=3, color="#045480", shape=17) +
theme(
panel.grid.major.y = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.y = element_blank(),
panel.grid.minor.x = element_blank(),
) +
labs(x="PCoA Axis 1", y="PCoA Axis 2", title="Functional divergence (FDiv)\nsummed deviations divided by\nsummed absolute deviations")
print(fdiv)
# this figure requres some tweaks in illustrator so comment it so you don't overwrite it everytime
#pdf("./FIGURES/Fig1_combined_fdiv_fric_fdis.pdf", width=6, height=3, useDingbats = FALSE)
#gridExtra::grid.arrange(fric, fdiv, feve, ncol=3, nrow=1)
#dev.off()
|
71333bb4f74b534713792a37df6ce9d33d04b565 | 9beeff6c4999aca9db1fe34ce82772fe0123560a | /man/mm.Rd | 6943b0bb394773e1dab8949e7ce4fa5ff26b1526 | [] | no_license | billpine/MQMF | fb028eebb7ae47b4c284a86c425a25fe14985c2d | cbf5472bc1799c210ad20d1b69fa736ce40dccf2 | refs/heads/master | 2020-09-03T04:35:18.252430 | 2019-11-02T08:41:40 | 2019-11-02T08:41:40 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 704 | rd | mm.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fisheries.r
\name{mm}
\alias{mm}
\title{mm calculates the predicted Michaelis-Menton length at age}
\usage{
mm(p, ages)
}
\arguments{
\item{p}{is a vector the first three cells of which are a, b, c
for the mm curve.}
\item{ages}{is a vector of ages; could be a single number}
}
\value{
a vector of predicted lengths for a vector of ages in 'ages'
}
\description{
mm calculates length at age for the generalized
Michaelis-Menton curve.
}
\examples{
\dontrun{
ages <- seq(0,20,1) # sigma is ignored here
pars <- c(a=23.0,b=1.0,c=1.0,sigma=1.0) # a, b, c, sigma
cbind(ages,mm(pars,ages))
}
}
|
3b347b17ebab45a8549258b74cad45f71476d4f0 | 7f02263a680124a9b6fed6e709013034be0dc2e8 | /SciDataEpi2020/functions/arrow_overlay.r | 2e5c705c2fff9b2f4f41756a86a65cda284d79b9 | [] | no_license | Hindrance/EpiSciData2020 | a8fa07e67a240a81d76391b614175593369e2810 | b271bb99bd793992fea7f41fe46ef1a981e33e61 | refs/heads/master | 2022-11-10T14:53:32.093301 | 2020-06-23T11:21:55 | 2020-06-23T11:21:55 | 266,233,813 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 835 | r | arrow_overlay.r | # This is an arrow overlay function. It adds an overlay to plots where
# individual points are linked (I.E time-point data). It is currently limited to
# two point connections (df[1,n][1:2]) lthough it can be extended by explicitly calling the function
# for the 2:3, 3:4 and (n):(n+1) cases.
arrow.overlay <- function(dataset, from=1:(length(dataset[,1])/2), to=(length(dataset[,1])/2+1):(length(dataset[,1])), arrow.factor=0.9, angle = 35, length=0.1, ...){
# dataset in form of df[x,y]
arrows(
dataset[to,1] - arrow.factor * (dataset[to,1] - dataset[from,1]), dataset[to,2] - arrow.factor * (dataset[to,2] - dataset[from,2]),
dataset[from,1] + arrow.factor * (dataset[to,1] - dataset[from,1]), dataset[from,2] + arrow.factor * (dataset[to,2] - dataset[from,2]),
angle=angle, length=length
)
}
|
fd1788e18b08fddbc10e848a249348f8a4eaec04 | 51d0c9d86c8aefe380a2aa15fa1bcb8c7575ec41 | /GAM/inst/make_examples.R | d495818f4bc298c3168029e6f1c0496fceff753f | [
"MIT"
] | permissive | ctlab/GAM | e0153d0d7e4c00175a527abdc03b2e4a7f371334 | e2e3ad335d944924c4bb25b3836b8d4a5130b4fc | refs/heads/master | 2022-08-28T18:01:40.966816 | 2022-08-11T09:13:11 | 2022-08-11T09:13:11 | 23,662,897 | 7 | 6 | null | null | null | null | UTF-8 | R | false | false | 2,426 | r | make_examples.R | #!/usr/bin/env Rscript
library("devtools")
library("GAM.db")
library("RCurl")
load_all("GAM")
load_all("GAM.networks")
library("igraph")
gene.de.M0.M1 <- read.csv(text=getURL("http://artyomovlab.wustl.edu/publications/supp_materials/GAM/Ctrl.vs.MandLPSandIFNg.gene.de.tsv"), sep="\t")
met.de.M0.M1 <- read.csv(text=getURL("http://artyomovlab.wustl.edu/publications/supp_materials/GAM/Ctrl.vs.MandLPSandIFNg.met.de.tsv"), sep="\t")
data("kegg.mouse.network")
data(met.id.map)
mets <- unique(c(kegg.mouse.network$graph.raw$met.x, kegg.mouse.network$graph.raw$met.y))
mets.hmdb <- met.id.map$HMDB[met.id.map$KEGG %in% mets]
rxns <- unique(kegg.mouse.network$graph.raw$rxn)
genes <- kegg.mouse.network$rxn2gene$gene[kegg.mouse.network$rxn2gene$rxn %in% rxns]
genes.refseq <- kegg.mouse.network$gene.id.map$RefSeq[kegg.mouse.network$gene.id.map$Entrez %in% genes]
gene.de.M0.M1 <- gene.de.M0.M1[gene.de.M0.M1$ID %in% genes.refseq, ]
met.de.M0.M1 <- met.de.M0.M1[met.de.M0.M1$ID %in% mets.hmdb, ]
es.re <- makeExperimentSet(network=kegg.mouse.network,
met.de=met.de.M0.M1,
gene.de=gene.de.M0.M1,
reactions.as.edges=T)
met.fdr=c(3e-5)
rxn.fdr=c(3e-5)
absent.met.score=c(-20)
es.re.sc <- scoreNetwork(es.re,
met.fdr=met.fdr,
rxn.fdr=rxn.fdr,
absent.met.score=absent.met.score
)
heinz.py <- "/usr/local/lib/heinz/heinz.py"
if (file.exists(heinz.py)) {
solver <- heinz.solver(heinz.py, timeLimit=60)
} else {
warning(sprintf("%s not found, using randHeur.solver instead", heinz.py))
solver <- randHeur.solver()
}
module.re <- findModule(es.re.sc, solver=solver)
module.re
es.rn <- makeExperimentSet(network=kegg.mouse.network,
met.de=met.de.M0.M1,
gene.de=gene.de.M0.M1,
reactions.as.edges=F,
plot=F)
met.fdr=c(2e-7)
rxn.fdr=c(2e-7)
absent.met.score=c(-20)
es.rn.sc <- scoreNetwork(es.rn,
met.fdr=met.fdr,
rxn.fdr=rxn.fdr,
absent.met.score=absent.met.score
)
module.rn <- findModule(es.rn.sc, solver=solver)
module.rn
save(gene.de.M0.M1, met.de.M0.M1, es.re, es.rn, module.re, module.rn, file="examplesGAM.rda")
|
5f6aac7ba0e209ebf0a72fe797b09f42dc6483e7 | 12ae74bd0ba9d5494d7301b521b45d1bfa5ff84a | /R/join.R | 408f8da318014270fa2c95c47a5b44425bb90f73 | [] | no_license | cran/do | 62b609a0f0cc0f0c0cc879adb821b1d9d95b6632 | fa0d7c8f9799326ffa6f0763f490c2873597131b | refs/heads/master | 2021-08-15T11:59:00.793187 | 2021-08-03T10:40:02 | 2021-08-03T10:40:02 | 206,034,685 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,150 | r | join.R | #' @title Join two dataframes together
#' @description Join two dataframes by the same id column.
#' @details join_inner(), join_full(), join_left(), join_right() and join_out() are five
#' functons to joint two dataframes together. They are based on package 'data.table',
#' so they are more efficient and fast.
#' @param x one dataframe
#' @param y the other dataframe
#' @param by the id name in x and y dataframe
#' @importFrom data.table `.__T__[:base`
#' @name join
#' @return one joined dataframe.
#' @export
#'
#' @examples
#' df1=data.frame(x=rep(c('b','a','c'),each=3),
#' y=c(1,3,6),
#' v=1:9)
#'
#' df2=data.frame(x=c('c','b','e'),
#' v=8:6,
#' foo=c(4,2,1))
#' join_inner(df1,df2,'x')
#' join_full(df1,df2,'x')
#' join_left(df1,df2,'x')
#' join_right(df1,df2,'x')
#' join_out(df1,df2,'x')
join_inner <- function(x,y,by=NULL){
if (is.null(by)){
by=(names(x)[names(x) %in% names(y)])[1]
message('Joinging by: ',by)
}
if (data.table::is.data.table(x)) x=data.frame(x)
if (is.matrix(x)) x=data.frame(x)
if (data.table::is.data.table(y)) y=data.frame(y)
if (is.matrix(y)) y=data.frame(y)
if (is.factor(x[,by])) x[,by]=as.character(x[,by])
if (is.factor(y[,by])) y[,by]=as.character(y[,by])
xi=data.table::data.table(x)
yi=data.table::data.table(y)
data.frame(xi[yi,on=by,nomatch=0])
}
#' @rdname join
#' @export
join_full <- function(x,y,by=NULL){
if (is.null(by)){
by=(names(x)[names(x) %in% names(y)])[1]
message('Joinging by: ',by)
}
if (data.table::is.data.table(x)) x=data.frame(x)
if (data.table::is.data.table(y)) y=data.frame(y)
if (is.factor(x[,by])) x[,by]=as.character(x[,by])
if (is.factor(y[,by])) y[,by]=as.character(y[,by])
ukey=unique(c(x[,by], y[,by]))
ukey=data.table::data.table(ukey)
names(ukey)=by
xjoint=data.table::data.table(x)
yjoint=data.table::data.table(y)
string1=paste0('data.table::setkey(xjoint,',by,')')
string2=paste0('data.table::setkey(yjoint,',by,')')
eval(parse(text = string1))
eval(parse(text = string2))
data.frame(yjoint[xjoint[list(ukey), on=by] ])
}
#' @rdname join
#' @export
join_left <- function(x,y,by=NULL){
if (is.null(by)){
by=(names(x)[names(x) %in% names(y)])[1]
message('Joinging by: ',by)
}
if (data.table::is.data.table(x)) x=data.frame(x)
if (data.table::is.data.table(y)) y=data.frame(y)
if (is.factor(x[,by])) x[,by]=as.character(x[,by])
if (is.factor(y[,by])) y[,by]=as.character(y[,by])
xi=data.table::data.table(x)
yi=data.table::data.table(y)
data.frame(yi[xi,on=by])
}
#' @rdname join
#' @export
join_right <- function(x,y,by=NULL){
if (is.null(by)){
by=(names(x)[names(x) %in% names(y)])[1]
message('Joinging by: ',by)
}
if (data.table::is.data.table(x)) x=data.frame(x)
if (data.table::is.data.table(y)) y=data.frame(y)
if (is.factor(x[,by])) x[,by]=as.character(x[,by])
if (is.factor(y[,by])) y[,by]=as.character(y[,by])
xi=data.table::data.table(x)
yi=data.table::data.table(y)
data.frame(xi[yi,on=by])
}
#' @rdname join
#' @export
join_out <- function(x,y,by=NULL){
if (is.null(by)){
by=(names(x)[names(x) %in% names(y)])[1]
message('Joinging by: ',by)
}
if (data.table::is.data.table(x)) x=data.frame(x)
if (data.table::is.data.table(y)) y=data.frame(y)
if (is.factor(x[,by])) x[,by]=as.character(x[,by])
if (is.factor(y[,by])) y[,by]=as.character(y[,by])
ukey=unique(c(x[,by][! x[,by] %in% y[,by]], y[,by][! y[,by] %in% x[,by]]))
ukey=data.table::data.table(ukey)
names(ukey)=by
xjoint=data.table::data.table(x)
yjoint=data.table::data.table(y)
string1=paste0('data.table::setkey(xjoint,',by,')')
string2=paste0('data.table::setkey(yjoint,',by,')')
eval(parse(text = string1))
eval(parse(text = string2))
data.frame(yjoint[xjoint[list(ukey), on=by] ])
}
|
c8f7f6130c2b2b0c4d1474f3cf6b136c60321857 | 1ba08b8bce8d1af9712f9ee02f24f89793e02a32 | /R/main.R | c5ed4ae0b3b2ffda71c15383995762556c9421cf | [] | no_license | fabiorcampos/software_analysis | 5c6557d62b4bc6c3cda8d050ad72660adaa10888 | 8c56822c6e97b6d98b5cbb36ce82b619c3fcacd2 | refs/heads/master | 2021-05-05T17:07:23.355517 | 2018-01-14T20:03:08 | 2018-01-14T20:03:08 | 117,342,473 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,161 | r | main.R | ### Load Libraries
library(dplyr)
library(tidyr)
### Load data
setwd("~/MEGA/SOFTEX/PREDICT/R/predict_2017/database")
df = read.csv("dataset.csv", header = TRUE, sep = ",", dec = ",")
### Classifications
#countries = c("BR", "CA", "CH", "KR", "FI", "IR", "UK", "US", "DE")
#sector = c("582, 62, 631, 951", "5821", "5829", "6201", "6202", "6203", "6209",
# "6311", "6312", "9511", "9512", "261-264, 582, 61, 62, 631, 951")
### EMP
emp_df = filter(df, Variable.code == "EMP",
Country.code %in% c("BR", "CA", "CN", "KR", "FI", "IR", "UK", "US", "DE"),
Classification.code %in% c("582, 62, 631, 951", "5821", "5829", "6201", "6202", "6203", "6209",
"6311", "6312", "9511", "9512", "261-264, 582, 61, 62, 631, 951"))
write.csv(emp_df, file = "emp.csv", sep = ",", dec = ",")
### BERD
berd_df = filter(df, Variable.code == "EMP",
Country.code %in% c("BR", "CA", "CN", "KR", "FI", "IR", "UK", "US", "DE"),
Classification.code %in% c("582, 62, 631, 951", "5821", "5829", "6201", "6202", "6203", "6209",
"6311", "6312", "9511", "9512", "261-264, 582, 61, 62, 631, 951"))
write.csv(berd_df, file = "emp.csv", sep = ",", dec = ",")
### PRODEMP
prod_df = filter(df, Variable.code == "PRODEMP",
Country.code %in% c("BR", "CA", "CN", "KR", "FI", "IR", "UK", "US", "DE"),
Classification.code %in% c("582, 62, 631, 951", "5821", "5829", "6201", "6202", "6203", "6209",
"6311", "6312", "9511", "9512", "261-264, 582, 61, 62, 631, 951"))
write.csv(prod_df, file = "prod1.csv", sep = ",", dec = ",")
### GVA
gva_df = filter(df, Variable.code == "GVA",
Country.code %in% c("BR", "CA", "CN", "KR", "FI", "IR", "UK", "US", "DE"),
Classification.code %in% c("582, 62, 631, 951", "5821", "5829", "6201", "6202", "6203", "6209",
"6311", "6312", "9511", "9512", "261-264, 582, 61, 62, 631, 951"))
write.csv(gva_df, file = "gva.csv", sep = ",", dec = ",")
|
b9a4afaa58e7ab67b452b3202dfc705ccb13695e | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/bayesTFR/examples/plot-trajectories.Rd.R | e2281524e5eb4a1be312ab743150cc6b54a6ca91 | [] | no_license | surayaaramli/typeRrh | d257ac8905c49123f4ccd4e377ee3dfc84d1636c | 66e6996f31961bc8b9aafe1a6a6098327b66bf71 | refs/heads/master | 2023-05-05T04:05:31.617869 | 2019-04-25T22:10:06 | 2019-04-25T22:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 538 | r | plot-trajectories.Rd.R | library(bayesTFR)
### Name: tfr.trajectories.plot
### Title: Output of Posterior Distribution of TFR Trajectories
### Aliases: tfr.trajectories.plot tfr.trajectories.plot.all
### tfr.trajectories.table
### Keywords: hplot
### ** Examples
## Not run:
##D sim.dir <- file.path(find.package("bayesTFR"), "ex-data", "bayesTFR.output")
##D pred <- get.tfr.prediction(sim.dir)
##D tfr.trajectories.plot(pred, country="Burkina Faso", pi=c(80, 95))
##D tfr.trajectories.table(pred, country="Burkina Faso", pi=c(80, 95))
## End(Not run)
|
c5b5e06fe7678241930f67cc420886e95cc5dbbb | 33fc8a4cf2f0ba9229306d3cbd576355a6916deb | /Algorithm.R | 23d7d941646b57241e39c11476c9f2f2ff8eb198 | [] | no_license | sagaraa/Unnati | a3762a66bb6faecc0f7db967599ec15848827c61 | 64d40ea985f0547212d9cc8949b72c3226b570b1 | refs/heads/master | 2021-01-21T20:08:20.355644 | 2017-05-23T17:08:29 | 2017-05-23T17:08:29 | 92,198,518 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 7,082 | r | Algorithm.R | unnati = read.csv("all_unnati.csv")
test = unnati[unnati$Status == "New",]
train = unnati[unnati$Status != "New",]
train$StatusValue[train$Status == "Enrolled"] = 1
train$StatusValue[train$Status == "Interested - Call Back"] = 1
train$StatusValue[train$Status == "Closed"] = 0
train$StatusValue[train$Status == "FollowUp - Call Back"] = 0
train$StatusValue[train$Status == "Not Known"] = 0
train$StatusValue[train$Status == "Personal Visit-Walkin"] = 1
table(train$StatusValue)
table(train$Status)
library(caTools)
set.seed(143)
split = sample.split(train$StatusValue, SplitRatio = 0.7)
training = subset(train, split == TRUE)
testing = subset(train, split == FALSE)
referred = as.data.frame(unclass(table(training$ReferredFrom, training$Status == c("Enrolled", "Interested - Call Back"))))
colnames(referred) = c("Not_Enrolled", "Enrolled")
referred$Not_Enrolled = as.numeric(as.character(referred$Not_Enrolled))
referred$Enrolled = as.numeric(referred$Enrolled)
referred$ReferredValue = referred$Enrolled/(referred$Not_Enrolled + referred$Enrolled)
referred = referred[order(referred$ReferredValue, decreasing = TRUE), ]
write.csv(referred, file = "ReferredValue.csv")
rm(referred)
referred = read.csv("ReferredValue.csv")
colnames(referred) = c("ReferredFrom","No_OF_0","No_OF_1","ReferredValue")
referred$No_OF_0 = NULL
referred$No_OF_1 = NULL
training = merge(training,referred)
center = data.frame(unclass(table(training$Center, training$Status == c("Enrolled", "Interested - Call Back"))))
colnames(center) = c("Not_Enrolled", "Enrolled_Interested")
center$Not_Enrolled = as.numeric(center$Not_Enrolled)
center$Enrolled_Interested = as.numeric(center$Enrolled_Interested)
center$CenterValue = center$Enrolled_Interested/(center$Not_Enrolled + center$Enrolled_Interested)
center = center[order(center$CenterValue, decreasing = TRUE), ]
write.csv(center,"CenterValue.csv")
rm(center)
centre = read.csv("CenterValue.csv")
colnames(centre) = c("Center","a","b","CenterValue")
centre$a = NULL
centre$b = NULL
training = merge(training,centre)
SourceValue = data.frame(unclass(table(training$Source , training$Status == c("Enrolled", "Interested - Call Back"))))
colnames(SourceValue) = c("Not_Enrolled", "Enrolled_Interested")
SourceValue$Not_Enrolled = as.numeric(SourceValue$Not_Enrolled)
SourceValue$Enrolled_Interested = as.numeric(SourceValue$Enrolled_Interested)
SourceValue$SourceValue = SourceValue$Enrolled_Interested/(SourceValue$Not_Enrolled + SourceValue$Enrolled_Interested)
SourceValue = SourceValue[order(SourceValue$SourceValue, decreasing = TRUE), ]
write.csv(SourceValue,"SourceValue.csv")
rm(SourceValue)
source = read.csv("SourceValue.csv")
colnames(source) = c("Source","a","b","SourceValue")
source$a = NULL
source$b = NULL
training = merge(training,source)
PriorityValue = data.frame(unclass(table(training$Priority , training$Status == c("Enrolled", "Interested - Call Back"))))
colnames(PriorityValue) = c("Not_Enrolled", "Enrolled_Interested")
PriorityValue$Not_Enrolled = as.numeric(PriorityValue$Not_Enrolled)
PriorityValue$Enrolled_Interested = as.numeric(PriorityValue$Enrolled_Interested)
PriorityValue$PriorityValue = PriorityValue$Enrolled_Interested/(PriorityValue$Not_Enrolled + PriorityValue$Enrolled_Interested)
PriorityValue = PriorityValue[order(PriorityValue$PriorityValue, decreasing = TRUE), ]
write.csv(PriorityValue,"PriorityValue.csv")
rm(PriorityValue)
priority = read.csv("PriorityValue.csv")
colnames(priority) = c("Priority", "a","b","PriorityValue")
priority$a = NULL
priority$b = NULL
training = merge(training,priority)
CourseValue = data.frame(unclass(table(training$Course , training$Status == c("Enrolled", "Interested - Call Back"))))
colnames(CourseValue) = c("Not_Enrolled", "Enrolled_Interested")
CourseValue$Not_Enrolled = as.numeric(CourseValue$Not_Enrolled)
CourseValue$Enrolled_Interested = as.numeric(CourseValue$Enrolled_Interested)
CourseValue$CourseValue = CourseValue$Enrolled_Interested/(CourseValue$Not_Enrolled + CourseValue$Enrolled_Interested)
CourseValue = CourseValue[order(CourseValue$CourseValue, decreasing = TRUE), ]
write.csv(CourseValue,"CourseValue.csv")
rm(CourseValue)
Course = read.csv("CourseValue.csv")
colnames(Course) = c("Course", "a","b","CourseValue")
Course$a = NULL
Course$b = NULL
training = merge(training,Course)
SourceTypeValue = data.frame(unclass(table(training$SourceType , training$Status == c("Enrolled", "Interested - Call Back"))))
colnames(SourceTypeValue) = c("Not_Enrolled", "Enrolled_Interested")
SourceTypeValue$Not_Enrolled = as.numeric(SourceTypeValue$Not_Enrolled)
SourceTypeValue$Enrolled_Interested = as.numeric(SourceTypeValue$Enrolled_Interested)
SourceTypeValue$SourceTypeValue = SourceTypeValue$Enrolled_Interested/(SourceTypeValue$Not_Enrolled + SourceTypeValue$Enrolled_Interested)
SourceTypeValue = SourceTypeValue[order(SourceTypeValue$SourceTypeValue, decreasing = TRUE), ]
write.csv(SourceTypeValue,"SourceTypeValue.csv")
rm(SourceTypeValue)
SourceType = read.csv("SourceTypeValue.csv")
colnames(SourceType) = c("SourceType", "a","b","SourceTypeValue")
SourceType$a = NULL
SourceType$b = NULL
training = merge(training,SourceType)
ReasonValue = data.frame(unclass(table(training$Reason , training$Status == c("Enrolled", "Interested - Call Back"))))
colnames(ReasonValue) = c("Not_Enrolled", "Enrolled_Interested")
ReasonValue$Not_Enrolled = as.numeric(ReasonValue$Not_Enrolled)
ReasonValue$Enrolled_Interested = as.numeric(ReasonValue$Enrolled_Interested)
ReasonValue$ReasonValue = ReasonValue$Enrolled_Interested/(ReasonValue$Not_Enrolled + ReasonValue$Enrolled_Interested)
ReasonValue = ReasonValue[order(ReasonValue$ReasonValue, decreasing = TRUE), ]
write.csv(ReasonValue,"ReasonValue.csv")
rm(ReasonValue)
Reason = read.csv("ReasonValue.csv")
colnames(Reason) = c("Reason", "a","b","ReasonValue")
Reason$a = NULL
Reason$b = NULL
training = merge(training,Reason)
training$StatusValue = as.numeric(training$StatusValue)
unnati_log = glm(StatusValue~ReferredValue+CenterValue+SourceValue+PriorityValue+CourseValue+SourceTypeValue+ReasonValue, data = training , family = "binomial")
trainingPrediction = predict(unnati_log, data = training, type = "response")
testing = merge(testing,referred)
testing = merge(testing,centre)
testing = merge(testing,SourceType)
testing = merge(testing,priority)
testing = merge(testing,Course)
testing = merge(testing,source)
testing = merge(testing,Reason)
testingPrediction = predict(unnati_log, newdata = testing, type = "response")
test = merge(test,referred)
rm(referred)
test = merge(test,centre)
rm(centre)
test = merge(test,SourceType)
rm(SourceType)
test = merge(test,priority)
rm(priority)
test = merge(test,Course)
rm(Course)
test = merge(test,source)
rm(source)
test = merge(test,Reason)
rm(Reason)
test$StatusValue = predict(unnati_log, newdata = test, type = "response")
target = subset(test, test$StatusValue > 0.4)
nrow(target)
write.csv(target, "target.csv", row.names = FALSE)
table(training$StatusValue, trainingPrediction > 0.5)
table(testing$StatusValue, testingPrediction > 0.5)
|
1e047130f60c6cffa71dddff920152a0cea2cae7 | 06d7da77c509f52f6d1629307b9c9a59ab106020 | /Rcode/03-preprocessing.R | b5f5c5e05a7c5d557fcc947b8b0ed2a2a4fdf278 | [] | no_license | happyrabbit/CE_JSM2017 | b823883d01c7787a77e424aa099464564005aedc | bddf17356b156c41bfe948ce6f86ee2d1198e4f8 | refs/heads/master | 2021-01-17T12:00:37.183957 | 2017-07-31T21:19:07 | 2017-07-31T21:19:07 | 95,393,608 | 8 | 4 | null | 2017-07-06T16:18:56 | 2017-06-26T00:27:40 | HTML | UTF-8 | R | false | false | 4,730 | r | 03-preprocessing.R | ### -----------------------------
### Hui Lin
### @gossip_rabbit
###
### http://scientistcafe.com
### -----------------------------
## Data Preprocessing
## -----------------------------
sim.dat <- read.csv("https://raw.githubusercontent.com/happyrabbit/DataScientistR/master/Data/SegData.csv ")
summary(sim.dat)
# set problematic values as missings
sim.dat$age[which(sim.dat$age>100)]<-NA
sim.dat$store_exp[which(sim.dat$store_exp<0)]<-NA
# see the results
summary(subset(sim.dat,select=c("age","income")))
## Missing Values
## -----------------------------
# save the result as another object
demo_imp<-impute(sim.dat,method="median/mode")
# check the first 5 columns, there is no missing values in other columns
summary(demo_imp[,1:5])
imp<-preProcess(sim.dat,method="medianImpute")
demo_imp2<-predict(imp,sim.dat)
summary(demo_imp2[,1:5])
## Missing Values: K-nearest neighbors
## -----------------------------
imp<-preProcess(sim.dat,method="knnImpute",k=5)
# need to use predict() to get KNN result
demo_imp<-predict(imp,sim.dat)
## Solve the problem
# find factor columns
imp<-preProcess(sim.dat,method="knnImpute",k=5)
idx<-which(lapply(sim.dat,class)=="factor")
demo_imp<-predict(imp,sim.dat[,-idx])
summary(demo_imp[,1:3])
## Missing Values: Bagging Tree
## -----------------------------
imp<-preProcess(sim.dat,method="bagImpute")
demo_imp<-predict(imp,sim.dat)
summary(demo_imp[,1:5])
## Centering and Scaling
## -----------------------------
# DIY
income<-sim.dat$income
# calculate the mean of income
mux<-mean(income,na.rm=T)
# calculate the standard deviation of income
sdx<-sd(income,na.rm=T)
# centering
tr1<-income-mux
# scaling
tr2<-tr1/sdx
# preProcess()
sdat<-subset(sim.dat,select=c("age","income"))
# set the "method" option
trans<-preProcess(sdat,method=c("center","scale"))
# use predict() function to get the final result
transformed<-predict(trans,sdat)
## Resolve Skewness
## -----------------------------
describe(sim.dat)
# select the two columns and save them as dat_bc
dat_bc<-subset(sim.dat,select=c("store_trans","online_trans"))
(trans<-preProcess(dat_bc,method=c("BoxCox")))
# Use predict() to get the transformed result
transformed<-predict(trans,dat_bc)
# Check before and after
par(mfrow=c(1,2),oma=c(2,2,2,2))
hist(dat_bc$store_trans,main="Before Transformation",xlab="store_trans")
hist(transformed$store_trans,main="After Transformation",xlab="store_trans")
## Resolve Outliers
## -----------------------------
## Z-score and modified Z-score
# calculate median of the absolute dispersion for income
ymad<-mad(na.omit(sdat$income))
# calculate z-score
zs<-(sdat$income-mean(na.omit(sdat$income)))/ymad
# count the number of outliers
sum(na.omit(zs>3.5))
## Spatial Sign Transformation
# KNN imputation
sdat<-sim.dat[,c("income","age")]
imp<-preProcess(sdat,method=c("knnImpute"),k=5)
sdat<-predict(imp,sdat)
transformed <- spatialSign(sdat)
transformed <- as.data.frame(transformed)
par(mfrow=c(1,2),oma=c(2,2,2,2))
plot(income ~ age,data = sdat,col="blue",main="Before")
plot(income ~ age,data = transformed,col="blue",main="After")
## Collinearity
## -----------------------------
# corrplot()
# select non-survey numerical variables
sdat<-subset(sim.dat,select=c("age","income","store_exp","online_exp","store_trans","online_trans" ))
# use bagging imputation here
imp<-preProcess(sdat,method="bagImpute")
sdat<-predict(imp,sdat)
# get the correlation matrix
correlation<-cor(sdat)
# plot
par(oma=c(2,2,2,2))
corrplot.mixed(correlation,order="hclust",tl.pos="lt",upper="ellipse")
# The `findCorrelation()` function in package `caret` will apply the above algorithm.
(highCorr<-findCorrelation(cor(sdat),cutoff=.75))
# delete highly correlated columns
sdat<-sdat[-highCorr]
# check the new correlation matrix
cor(sdat)
## Sparse Variables
## -----------------------------
# make a copy
zero_demo<-sim.dat
# add two sparse variable
# zero1 only has one unique value
# zero2 is a vector with the first element 1 and the rest are 0s
zero_demo$zero1<-rep(1,nrow(zero_demo))
zero_demo$zero2<-c(1,rep(0,nrow(zero_demo)-1))
nearZeroVar(zero_demo,freqCut = 95/5, uniqueCut = 10)
## Re-encode Dummy Variables
## -----------------------------
# `class.ind()` from `nnet` package
dumVar<-class.ind(sim.dat$gender)
head(dumVar)
# `dummyVars()` from `caret`
dumMod<-dummyVars(~gender+house+income,
data=sim.dat,
# use "origional variable name + level" as new name
levelsOnly=F)
head(predict(dumMod,sim.dat))
# the function can create interaction term
dumMod<-dummyVars(~gender+house+income+income:gender,
data=sim.dat,
levelsOnly=F)
head(predict(dumMod,sim.dat))
|
4cb5c9b5e650d2dd14d1bcf29eccf12370375f4b | 1611e65477a0da49c4d36a2b65c07b121362e55e | /pkg/R/read_ess_report.R | bca13f61346a34b60b2e26b97b369d29fc7c1186 | [] | no_license | olavtenbosch/validatereport | 9ee51659f9f5e35ba5ee91e1fd45a38b6686237b | 2058efd3ce66cce4a9001449f08a441b0b2a9a35 | refs/heads/master | 2021-09-05T18:47:12.135905 | 2018-01-30T10:55:11 | 2018-01-30T10:55:11 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 6,524 | r | read_ess_report.R | #' @import rmarkdown
{}
#' Receive ESS json schema definition string.
#'
#' @note Currently only version 1.0.0 is supported.
#'
#' @param version \code{[character]} Version of reporting scheme.
#'
#' @references
#' M. van der Loo and O. ten Bosch. Design of a generic machine-readable
#' validation report structure. Version 1.0.0.
#' \href{https://github.com/data-cleaning/ValidatReport}{link}.
#'
#' @export
ess_json_schema <- function(version="1.0.0"){
if (version == "1.0.0"){
ess_json_schema_1.0.0
} else {
warning("Unknown scheme version")
invisible(NULL)
}
}
check_ess_json <- function(txt,version,...){
schema <- ess_json_schema(version)
v <- tryCatch( jsonvalidate::json_validate(txt, schema, verbose=TRUE)
, error=function(e){
stop("Validation against ESS json schema stopped.:\n %s",e$message)
})
if (!v){
warning("This is not a valid ESS json validation report structure:\n")
print(attr(v,"errors"))
}
invisible(NULL)
}
#' Read ESS validation report structure
#'
#' @param file \code{[character]} file An URL or file location
#' @param check \code{[check]} logical Toggle checking against json schema.
#' @param ... options passed to \code{\link[base]{readLines}}
#'
#' @family IO
#'
#' @return A \code{data.frame} of class \code{vrs}.
#'
#' @export
read_vrs <- function(file, check=TRUE, ...){
txt <- paste0(readLines(file,...),collapse="\n")
parse_ess_validation_report(txt,check=check)
}
#' Parse ess json validation report.
#'
#' @param txt \code{[character]} json validation report string
#' @param check \code{[logical]} toggle check against json schema
#' @param version \code{[character]} json schema version to check against
#'
#' @return Object of class \code{c("vrs","data.frame")}
parse_ess_validation_report <- function(txt, check=TRUE, version="1.0.0"){
if ( check ) check_ess_json(txt, version=version)
a <- jsonlite::fromJSON(txt,flatten = TRUE)
a$data.source <- gsub("c\\((.*)\\)","[\\1]",a$data.source)
a$data.target <- gsub("c\\((.*)\\)","[\\1]",a$data.target)
a$rule.severity <- factor(a$rule.severity, levels=c("information","warning","error"))
a$value <- factor(a$value, levels=c("0","1","NA"),labels=c("TRUE","FALSE","NA"))
if (is.list(a$data.target)){
a$data.target <- sapply(a$data.target, function(x){
paste0("[",paste(x,collapse=","),"]")
})
}
if (is.list(a$data.source)){
a$data.source <- sapply(a$data.source, function(x){
paste0("[",paste(x,collapse=","),"]")
})
}
class(a) <- c("vrs",class(a))
a
}
# easy line concatenation
`%+=%` <- function(lhs,rhs){
out_var <- as.character(sys.call()[[2]])
str <- paste0(lhs, "\n", rhs)
assign(out_var, str,pos=parent.frame())
}
#' Create a human-readable report
#'
#' @param x an object to be downmarked
#' @param ... Currently not used
#'
#' @export
as_markdown <- function(x,...){
# generic, so we can overload for json string, 'validation' objects.
UseMethod("as_markdown")
}
#' @rdname as_markdown
#' @export
as_markdown.vrs <- function(x,...){
md.str <- ""
for (i in seq_len(nrow(x))){
md.str %+=% md_rec(x[i,])
}
md.str
}
md_rec <- function(x){
md.str <- sprintf("\n- Event id : %s",x[["id"]] )
md.str %+=% sprintf(" - type : %s",x[["type"]])
md.str %+=% sprintf(" - actor : %s",x[["event.actor"]])
md.str %+=% sprintf(" - agent : %s",x[["event.agent"]])
md.str %+=% sprintf(" - trigger : %s",x[["event.trigger"]])
md.str %+=% sprintf("- Value : %s",x[["value"]])
md.str %+=% sprintf("- Source data : %s",x[["data.source"]])
md.str %+=% sprintf("- Target data : %s",x[["data.target"]])
md.str %+=% sprintf("- Data description:\n\n```\n%s\n\n```"
, paste(" ",strwrap(x[["data.description"]],width=60),collapse="\n"))
md.str %+=% sprintf("- Rule :")
md.str %+=% sprintf(" - language : %s",x[["rule.language"]])
md.str %+=% sprintf(" - severity : %s",x[["rule.severity"]])
md.str %+=% sprintf(" - change : %s",x[["rule.change"]])
md.str %+=% sprintf("- Rule description:\n\n```\n%s\n```"
, gsub("`","",paste(" ", strwrap(x[["rule.description"]],width=60),collapse="\n")))
md.str %+=% sprintf("- Rule expression:\n\n```\n%s\n```\n\n"
, gsub("\\n","\n ", paste(" ",x[["rule.expression"]])))
md.str %+=% paste(rep("-",80),collapse="")
md.str
}
#' Create a human-readable summary
#'
#' @param x an object to be downmarked
#' @param ... Currently unused.
#' @export
md_summary <- function(x,...){
UseMethod("md_summary")
}
#' @rdname as_markdown
#' @param author \code{[character]} author
md_summary.vrs <- function(x, author=Sys.info()["user"], ...){
md.str <- "# Validation report summary"
md.str %+=% sprintf("Generated by %s, %s",author,date())
md.str %+=% "\n## Overview of validation procedure\n"
md.str %+=% "\nEvaluations:\n"
basic_info <-
data.frame(
Information = c("Nr of validations", "Nr of rules checked")
, Value = c(nrow(x), length(unique(x$rule.expression)))
)
md.str %+=% paste(knitr::kable(basic_info, format="markdown"), collapse="\n")
md.str %+=% "\nEvents by actor:\n"
tab <- as.data.frame(table(x$event.actor))
names(tab) <- c("actor","events")
md.str %+=% paste(knitr::kable(tab),collapse="\n")
md.str %+=% "\nSeverity changes:\n"
tab <- table(severity = x$rule.severity, change = x$rule.change)
md.str %+=% paste(knitr::kable(tab,format="markdown"),collapse="\n")
md.str %+=% "\n## Overview of validation results\n"
md.str %+=% "\nResults by severity (possibly after change):\n"
tab <- stats::addmargins(table(severity = x$rule.severity, result = x$value))
md.str %+=% paste(knitr::kable(tab,format="markdown", caption="Results by severity"), collapse="\n")
md.str %+=% "\n## Results by rule:\n"
i <- 0
for ( rl in unique(x$rule.expression)){
i = i + 1
y <- x[x$rule.expression == rl,]
md.str %+=% "------------------------------------------------------------\n"
md.str %+=% sprintf("\n**Rule %03d: Description:**\n",i)
md.str %+=% y$rule.description[1]
md.str %+=% "\n**Expression:**\n"
md.str %+=% "\n```"
md.str %+=% rl
md.str %+=% "```\n"
md.str %+=% "\n\n**Results:**\n\n"
tab <- as.data.frame(t(as.matrix(stats::addmargins(table(value = y$value)))))
md.str %+=% paste(knitr::kable(tab, format="markdown"),collapse="\n")
}
md.str
}
|
23fcc68aa9d180ab33da10d1113af7482a33c898 | 5cd2e7251a1f3f2e5b3bb595ec147c05fe8b4fba | /workshop_scripts.R | e0345bef2afe06d3f218b5e03495a115be868c37 | [] | no_license | hshsl-training/R-workshop | 2f6c039d5ef9b1093bbe5319135fb945213c7080 | f6a0d4255325bd95a9ff6408843d3571183e1393 | refs/heads/master | 2021-01-10T10:12:20.663583 | 2016-03-01T17:07:03 | 2016-03-01T17:07:03 | 52,875,724 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 10,620 | r | workshop_scripts.R | x <- 4
y <- 5
z <- x + y
z
example("read.csv")
help.search("knit")
example("knit")
newV <- 1:10
newV
class(newV)
newV * 2
newW <- c(1:10, 4)
newW
help(c)
write.csv(newW, file="newW.csv")
list.files()
inTheFlesh <- read.csv("newW.csv", header = F)
View(inTheFlesh)
#
# Use the diamonds data to show basic exploration of data
# - summary
# - plot to show counts w/ histogram
# - reorder bars in histogram
#
library(ggplot2)
data(diamonds)
head(diamonds)
p <- ggplot(diamonds, aes(x=clarity, fill=cut))
p + geom_bar() + labs(title="Counts of diamond clarities filled by cut count")
summary(diamonds)
p <- ggplot(diamonds, aes(color))
p + geom_bar()
reorder_size <- function(x) {
factor(x, levels = names(sort(table(x))))
}
ggplot(diamonds, aes(reorder_size(color))) + geom_bar() + labs(title="Diamonds color count filled by cut count")
#
# Begin visualization w/ ggplot2
#
# Load the ggplot2 package
library("ggplot2")
# Load the diamonds dataset provided by ggplot2
data("diamonds")
# Show only the first 6 rows of the diamonds data
head(diamonds)
# Show all of the diamonds data
View(diamonds)
# Show metadata about the diamonds data
help(diamonds)
# Create default scatter plot from diamonds data
# This plot will show a relationship between two attributes
# in the dataset: as weight increases, price increases.
# Now, there are three parts to a ggplot2 graph. The first is the data
# we'll be graphing. In this case, we are plotting the diamonds data frame,
# so we type "diamonds". Second, we show the mapping of aesthetics to the
# attributes we'll be plotting. We type aes- meaning aesthetics- then open
# parentheses, and now our assignments: we say "x=carat", saying we want to
# put carat on the x-axis, then "y=price", saying what we want to put on the y-axis.
#
# Now that we've defined the structure of our graph, we are going to add a
# "layer" to it: that is, define what time of graph it is. In this case, we
# want to make a scatter plot: the name for that layer is geom_point. "geom"
# is a typical start for each of these layers. Now we've defined our graph,
# and hit return, and we see our scatter plot.
ggplot(diamonds, aes(x=carat, y=price)) + geom_point()
# Now, this plot shows two aesthetics- weight and price- but there are many
# other attributes of the data we can communicate. For example, we might
# want to see how the quality of the cut, or the color, or the clarity,
# affects the price.
# Let's add the clarity attritube, which is a measure of the clarity of
# each diamond, to color our points.
ggplot(diamonds, aes(x=carat, y=price, color=clarity)) + geom_point()
# Notice the legend that appeared on the right of the of plot.
# We can change clarity for color to see how color of diamonds affects the price.
ggplot(diamonds, aes(x=carat, y=price, color=color)) + geom_point()
# Now every item in the color legend is one of the ratings of color.
# Or we can change it to "cut":
ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point()
# This way we can explore the relationship of each of these variables
# and how it affects the carat/price relationship.
#
# Now, what if we want to see the effect of both color and cut?
# We can use a fourth aesthetic, such as the size of the points.
# So here we have color representing the clarity. Let's add another
# aesthetic- let's say "size=cut."
ggplot(diamonds, aes(x=carat, y=price, color=clarity, size=cut)) + geom_point()
# Now the size of every point is determined by the cut even while the
# color is still determined by the clarity. Similarly, we could use
# the shape to represent the cut:
ggplot(diamonds, aes(x=carat, y=price, color=clarity, shape=cut)) + geom_point()
# Now every shape represents a different cut of the diamond.
# Now, this scatter plot is one "layer", which means we can add
# additional layers besides the scatter plot using the plus sign.
# For example, what if we want to add a smoothing curve that shows
# the general trend of the data? That's a layer called geom_smooth.
# So let's take this plot, take out the color, and add a smoothing trend:
ggplot(diamonds, aes(x=carat, y=price)) + geom_point() + geom_smooth()
# The gray area around the curve is a confidence interval, suggesting
# how much uncertainty there is in this smoothing curve. If we want to
# turn off the confidence interval, we can add an option to the geom_smooth
# later; specifically "se=FALSE", where "s.e." stands for "standard error."
ggplot(diamonds, aes(x=carat, y=price)) + geom_point() + geom_smooth(se=FALSE)
# This gets rid of the gray area and now we can just see the smoothing curve.
# Similarly, if we would rather show a best fit straight line rather than a
# curve, we can change the "method" option in the geom_smooth layer. In this
# case it's method="lm", where "lm" stands for "Linear model".
ggplot(diamonds, aes(x=carat, y=price)) + geom_point() + geom_smooth(se=FALSE, method="lm")
# There we fit a best fit line to the relationship between carat and price
# with this geom_smooth layer.
# If you used a color aesthetic, ggplot will create one smoothing curve for
# each color. For example, if we add "color=clarity":
ggplot(diamonds, aes(x=carat, y=price, color=clarity)) + geom_point() + geom_smooth(se=FALSE)
# Now we see it actually fits one curve for each of these colors. This is
# a useful way to compare and contrast multiple trends. Note that you can
# show this smoothing curve layer without showing your scatter plot layer,
# simply by removing the geom_point() layer:
ggplot(diamonds, aes(x=carat, y=price, color=clarity)) + geom_smooth(se=FALSE) + labs(title="Smoothing trends of diamond carat prices by clarity of diamond")
# This might be a bit clearer: we can see just the fit curves without
# seeing the actual points.
###
###
###
### STATISTICAL ANALYSES
###
###
###
data("mtcars")
head(mtcars)
help(mtcars)
mtcars$mpg
# To compare two samples to see if they have different means,
# or averages, statisticians traditionally use a Student's T-test.
# This can be performed in R with the t.test function:
t.test(mpg ~ am, data=mtcars)
# First we give it the formula: mpg ~ am. In R, a tilde (~)
# represents "explained by"- so this means "miles per gallon
# explained by automatic transmission." Secondly we give it the
# data we're plotting, which is mtcars. So this is saying "Does the
# miles per gallon depend on whether it's an automatic or manual
# transmission in the mtcars dataset."
# We get a lot of information from the t-test. Most notably, we get a p-value:
# this shows the probability that that this apparent difference between
# the two groups could appear by chance. This is a low p-value, so we
# can be fairly confident that there is an actual difference between the groups.
# We can also see a 95% confidence interval. This interval describes how much
# lower the miles per gallon is in manual cars than it is in automatic cars.
# We can be confident that the true difference is between 3.2 and 11.3.
# These other values: such as the T test statistic and the number of degrees of
# freedom used in the test, have relevance in the actual mathematical formulation
# of the test.
# Now you're able to see these results manually.
# But what if you want to extract them in R into its own variable,
# for instance so that you could graph or report them later? Well,
# first save the entire t-test into a variable. Recall that in R you
# can do this by putting tt = at the start of the line:
tt = t.test(mpg ~ am, data=mtcars)
# This assigns the result of the t-test to the variable tt.
# So now tt contains the result of the t-test.
tt
# We can also extract single values out using the dollar sign.
tt$p.value
# Similarly we can extract the confidence interval.
tt$conf.int
# A t-test examined whether a numeric variable differed ...
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()
# [READ FROM THE WEBSITE FROM HERE OUT]
# http://varianceexplained.org/RData/code/code_lesson3/#segment2
cor.test(mtcars$mpg, mtcars$wt)
fit = lm(mpg ~ wt, mtcars)
summary(fit)
#
# Basic arithmetic
#
3 + 5 # addition
20 - 5 # subtraction
10 * 10 # multiplication
3 / 4 # division
18 %/% 12 # just the integer part of the quotient
18 %% 12 # just the remainder part (modulo)
10 ^ 2 # exponentiation
log(10) # natural log (base e)
exp(2.302585)# antilog, e raised to a power
log10(100) # base 10 logs; log(100, base=10) is the same
sqrt(100) # square root
#
# More Useful Syntax
#
# Working with variables
x <- 5
y <- 9
y - x
[1] 4
sqrt(y)
[1] 3
# Keyword functions
install.packages("ggplot2") # Install the ggplot2 library
library("ggplot2") # Load the ggplot2 library into current workspace
library() # List all the packages built in to base R
data() # List all the datasets built in to base R
help(mtcars) # Show the description of the mtcars dataset
example("ggplot2") # Show examples of using the ggplot2 library
getwd() # Get the current working directory for current workspace
setwd() # Set the current working directory for current workspace
list.files() # List the files in the working directory
# ---------------------------------------
# Show all datasets in the base R datasets library
data()
# Show all datasets in all installed libraries
data(package = .packages(all.available = TRUE))
# ---------------------------------------
# Vector and other misc practice
ma = matrix(1:6, nrow=3, ncol=2)
ma
# "example" is a function keyword, shows examples of an action
example("read.csv")
getwd()
setwd()
list.files()
newV <- 1:10
newV
# [1] 1 2 3 4 5 6 7 8 9 10
class(newV)
# [1] "integer"
newV * 2
# [1] 2 4 6 8 10 12 14 16 18 20
newW <- c(1:10, 4)
newW
# [1] 1 2 3 4 5 6 7 8 9 10 4
write.csv(newW, file="newW.csv")
# You can view a file not in use by R, in R
View("./newW.csv")
newV
# [1] 1 2 3 4 5 6 7 8 9 10
write.csv(newV, file="newV.csv")
matrix(newV)
# [,1]
# [1,] 1
# [2,] 2
# [3,] 3
# [4,] 4
# [5,] 5
# [6,] 6
# [7,] 7
# [8,] 8
# [9,] 9
# [10,] 10
newMatrixV <- matrix(newV)
write.csv(newMatrixV, file="newV.csv")
View(newMatrixV)
write.csv(newMatrixV, file="newV.csv", col.names = NA, row.names = FALSE)
# Warning message:
# In write.csv(newMatrixV, file = "newV.csv", col.names = NA, row.names = FALSE) :
# attempt to set 'col.names' ignored |
12f973d137c3b717b2e5bde5d568d4c22a7879bd | db4ab344e60cbbbd9a726dc8e84db32018dcb2e8 | /man/ncaa_schedule_info.Rd | 59cbedd0f044007429d9d803bb646a27a21b1641 | [
"MIT"
] | permissive | robert-frey/baseballr | 8491c93a9c1fdf74c74a75c3a6e2ebb65a7862e8 | 060cd8b18c080cbb50fae444460a4c0a4db175e9 | refs/heads/master | 2023-03-09T17:21:52.013535 | 2023-02-24T18:06:56 | 2023-02-24T18:06:56 | 248,656,064 | 3 | 0 | null | 2020-03-20T03:04:29 | 2020-03-20T03:04:29 | null | UTF-8 | R | false | true | 991 | rd | ncaa_schedule_info.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ncaa_schedule_info.R
\name{ncaa_schedule_info}
\alias{ncaa_schedule_info}
\title{\strong{Get Schedule and Results for NCAA Baseball Teams}}
\usage{
ncaa_schedule_info(teamid = NULL, year = NULL)
}
\arguments{
\item{teamid}{The team's unique NCAA id.}
\item{year}{The season (i.e. use 2016 for the 2015-2016 season,
etc.)}
}
\value{
A data frame with the following fields: date, opponent,
result, score, innings (if more than regulation), and the url
for the game itself.\tabular{ll}{
col_name \tab types \cr
date \tab character \cr
opponent \tab character \cr
result \tab character \cr
score \tab character \cr
innings \tab character \cr
opponent_slug \tab character \cr
slug \tab character \cr
game_info_url \tab character \cr
}
}
\description{
\strong{Get Schedule and Results for NCAA Baseball Teams}
}
\examples{
\donttest{
try(ncaa_schedule_info(teamid = 736, year = 2021))
}
}
|
83263f0442e8cb44ad8d3418fd4ee25d4d74af1f | de8eece112a5bdd437b2a2baad8a59a2380ec36f | /course5/assignment1/assignment1.R | 51b51a6b2b0d480a6ef24b9ce717eeb00bed8925 | [] | no_license | anthonylst6/datasciencecoursera | 58e536f25bf98ec0b95a2a200e9c52176aa7e878 | 87e44fb2f10acd66818292832148863d884af7ab | refs/heads/master | 2020-08-07T19:43:59.446528 | 2020-03-01T09:04:54 | 2020-03-01T09:04:54 | 212,740,406 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,017 | r | assignment1.R | library(ggplot2)
library(dplyr)
# Loading and preprocessing the data
data <- read.csv("activity.csv", header = TRUE)
# What is mean total number of steps taken per day?
data1 <- data %>%
group_by(date) %>%
summarise(steps_total = sum(steps))
ggplot(data1, aes(steps_total)) + geom_histogram(bins = 10) + labs(x = "Number of steps", y = "Frequency", title = "Frequency of total steps per day (excluding missing values)")
mean(data1$steps_total, na.rm = TRUE)
median(data1$steps_total, na.rm = TRUE)
# What is the average daily activity pattern?
data2 <- data %>%
group_by(interval) %>%
summarise(steps_avg = mean(steps, na.rm = TRUE))
ggplot(data2, aes(interval, steps_avg)) + geom_line() + labs(x = "Interval", y = "Number of steps", title = "Average number of steps in 5 minute intervals (excluding missing values)")
data2$interval[which.max(data2$steps_avg)]
# Imputing missing values
sum(is.na(data$steps))
data_imputed <- data %>%
group_by(interval) %>%
mutate(steps = ifelse(is.na(steps), mean(steps, na.rm = TRUE), steps)) %>%
arrange(date)
data3 <- data_imputed %>%
group_by(date) %>%
summarise(steps_total = sum(steps))
ggplot(data3, aes(steps_total)) + geom_histogram(bins = 10) + labs(x = "Number of steps", y = "Frequency", title = "Frequency of total steps per day (with imputed missing values)")
mean(data3$steps_total)
median(data3$steps_total)
# Are there differences in activity patterns between weekdays and weekends?
day <- gsub("^S(.*)day", "weekend", weekdays(as.Date(data3$date)))
day <- as.factor(gsub("(.*)day", "weekday", day))
data_imputed <- data_imputed %>%
mutate(day_type = day)
data4 <- data_imputed %>%
group_by(day_type, interval) %>%
summarise(steps_avg = mean(steps))
ggplot(data4, aes(interval, steps_avg)) + geom_line() + facet_grid(day_type ~ .) + labs(x = "Interval", y = "Number of steps", title = "Average number of steps in 5 minute intervals (with imputed missing values)")
|
68b98d790b0b79fe9299c74d78bfe700d0aaa6e4 | 9c20dfe75c41283db15d80bef6ff60fbf4cb5255 | /Sol_and_mason_writing_a_function_AUG22.R | eb4bf491d1c08fe01f8f124f42db26350994f789 | [] | no_license | kristyrobledo/CodingConundrums | c9eadaa313afa5e04e47ecf5e016936b9bee328b | 7713b19a28774c75b9ae0e48b8ff7d648a40d278 | refs/heads/master | 2023-08-04T11:30:56.604221 | 2023-07-27T03:02:00 | 2023-07-27T03:02:00 | 237,126,082 | 4 | 0 | null | null | null | null | UTF-8 | R | false | false | 7,165 | r | Sol_and_mason_writing_a_function_AUG22.R |
library(tidyverse)
library(dplyr)
# why make a function?
# often when we're writing script we find a chunk of code
# we want to repeat over again with new input
# instead of having to write the code over and over again
# we can put that code in a function, then with the function
# you do not need to rewrite the code
# you only need to add in the new input (parameters)
# when you use a function you've saved,
# the template of code is called
# and the new input is replaced into that code
#this saves a lot of time and can streamline your code
function_name <- function(input){
#process you want to apply to input
input*10
}
function_name(20)
#calculate BMI (kg/m^2)
calculate_BMI <- function(weight_in_kg, height_in_M){
BMI <- weight_in_kg / height_in_M^2
return(BMI)
}
calculate_BMI(weight_in_kg =70, height_in_M = 1.77)
sols_BMI <-calculate_BMI(70, 1.77)
# Can add defaults
calculate_BMI_with_defaults <- function(weight_in_kg=66, height_in_M=1.55){
BMI <- weight_in_kg / height_in_M^2
return(BMI)
}
average_BMI <-calculate_BMI_with_defaults()
#sometimes you want to use a function to call
# on column names in a dataframe
#calling on column names using dplyr in functions requires a special formatting
#first we'll make a fake dataset to try this on
example_df <- data.frame(weight = c(76,89,55,145,90,468, NA,80,60),
height = rnorm(n=9, mean = 1.7, sd = 0.2),
outcome = c(1,1,1,1,0,0,0,0,1),
intervention = rbinom(n=9, size=1, prob=1/2),
infant_id = seq(1,9,1))
# Functions require special formatting when using dplyr and calling column names from dataframes
#this will not work
summarise_groups <- function(dataframe, grouping_var, column_name){
dataframe %>%
group_by(grouping_var) %>%
summarise(mean(column_name, na.rm = TRUE))
}
summarise_groups(example_df, intervention, weight)
#returns error can't find the variable
#To fix this error so that R can find the variable while using
#dplyr in a function you can use the double curly bracket
#see below
summarise_groups1 <- function(dataframe, grouping_var, column_name){
dataframe %>%
group_by({{grouping_var}}) %>%
summarise(mean = mean({{column_name}}, na.rm = TRUE))
}
summarise_groups1(example_df, intervention, weight)
#why curly curly are needed when using dplyr in custom functions (pretty dry only look at if you're interested)
#https://www.tidyverse.org/blog/2019/06/rlang-0-4-0/
# to illustrate how useful functions can be
# below is a simplified example of a more complex function the NextGen team has used.
# The function is applied to print descriptives and check continuous variables
# It checks whether the lower and upper bound are within range and produces other
# summary stats in a table
library(flextable)
check_continuous <- function(variable_name,lower, upper, treatment_name, dataset_mod){
if (any(!is.na(dataset_mod %>% select({{variable_name}})))) {
#summary per treatment
df1 <- dataset_mod %>%
filter(!is.na({{treatment_name}})) %>%
group_by({{treatment_name}}) %>%
dplyr::summarise( N = n(),
Missing = sum(is.na({{variable_name}})),
`Mean \n(SD)` = paste(round(mean({{variable_name}}, na.rm = TRUE), digit = 2), "\n(", round(sd({{variable_name}}, na.rm = TRUE),digit = 2), ")"),
`Median \n(IQR)` = paste(round(median.default({{variable_name}}, na.rm = TRUE),1),"\n(",round(IQR({{variable_name}}, na.rm = TRUE),digit = 2), ")"),
Q1 = quantile({{variable_name}}, probs = c(0.25), na.rm = TRUE),
Q3 = quantile({{variable_name}}, probs = c(0.75), na.rm = TRUE),
Range = paste0("(",min({{variable_name}}, na.rm = TRUE), " - ", max({{variable_name}}, na.rm = TRUE), ")"),
`Acceptable range?` = (range({{variable_name}}, na.rm=T)[1]>=lower & range({{variable_name}}, na.rm=T)[2]<=upper)) %>% as.data.frame()
#summary overall
df2 <- dataset_mod %>%
filter(!is.na({{treatment_name}})) %>%
dplyr::summarise({{treatment_name}} := paste0("Total"),
N = n(),
Missing = sum(is.na({{variable_name}})),
`Mean \n(SD)` = paste(round(mean({{variable_name}}, na.rm = TRUE), digit = 2), "\n(", round(sd({{variable_name}}, na.rm = TRUE),digit = 2), ")"),
`Median \n(IQR)` = paste(round(median.default({{variable_name}}, na.rm = TRUE),1),"\n(",round(IQR({{variable_name}}, na.rm = TRUE),digit = 2), ")"),
Q1 = quantile({{variable_name}}, probs = c(0.25), na.rm = TRUE),
Q3 = quantile({{variable_name}}, probs = c(0.75), na.rm = TRUE),
Range = paste0("(",min({{variable_name}}, na.rm = TRUE), " - ", max({{variable_name}}, na.rm = TRUE), ")"),
`Acceptable range?` = (range({{variable_name}}, na.rm=T)[1]>=lower & range({{variable_name}}, na.rm=T)[2]<=upper)) %>% as.data.frame()
#binding treatment summaries and overall summary
df3 <- rbind(df1,df2)
#make into flextable
flx <- df3 %>%
flextable() %>%
align(align = "center", part = "all") %>%
fontsize(size = 8, part = "all") %>%
width(width = (6.3/ncol(df3))) %>%
hline(part = "all")
flx <- bg(flx, i = ~ `Acceptable range?`== TRUE,
j = 8,
bg="palegreen", part = "body")
flx <- bg(flx, i = ~ `Acceptable range?`== FALSE,
j = 8,
bg="lightpink", part = "body")
return(flx)
} else{
print("This variable is all NA")
}
}
# test function for variable weight, with a lower bound of
# 20kg, upper bound of 400kg, split by the variable labelled intervention
# from the dataframe labelled example df
check_continuous(weight, 20, 400,intervention, example_df )
# and now swap the variable of interest and the bounds
check_continuous(height, 50, 250,intervention, example_df )
#note they were all out of bound because I accidentally provided in cm instead of meters
#redoing but putting the the correct units
check_continuous(height, 0.50, 2.50,intervention, example_df )
#occasionally helpful symbols
#
# <<- assigns object straight to the global environment within a custom function
# name a object in the custom function using a parameter in curly curly brackets
# := allows you to use a parameter so that you can assign objects to that parameter name in a function
#e.g., df %>% summarise({{parameter}} := count({parameter}))
#
# also helpful
# saving a group of functions in a script (e.g., all your data checking functions)
#then you can call all these functions for future use without having to rewrite them out
# source("filepath/../../functions.R")
# this runs everything in the script "functions.R" (loading each function in that script)
#e.g., this is useful when cleaning a new dataset because every checking/cleaning function
# will be loaded for use
|
4f5cb51718afec87ec94a1a34062d8505e851785 | 0648e4a6470f4f7bdd324a55ae03ac723092d7f7 | /R/DataSetCreation/combine_sets.R | 9920a5e32eabdd30a6fa7161b7908b294412c0f5 | [] | no_license | icklerly/assignment_11 | babe14a5e2e240f76ad43d2ee515b4d6fc8600ad | 799b5a0327f2ea7d3191db81a74a6cd0da111a3a | refs/heads/master | 2021-01-10T10:16:59.343262 | 2015-10-11T22:11:33 | 2015-10-11T22:11:33 | 43,315,938 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 742 | r | combine_sets.R | methyl<-read.csv("/Users/icklerly/Desktop/UNI/PROJECT/data/completed_methyl_Set.csv",sep="\t",header=T)
mRNA<-read.csv("/Users/icklerly/Desktop/UNI/PROJECT/data/mRNA_Set.csv",sep="\t",header=T)
for (i in 1:516){
rownames(mRNA)[i]<-paste("BRCA+",strsplit(rownames(mRNA)[i],"\\+")[[1]][2],sep="")
}
#merge the two data types by their row names
#Merge them together
mix<-merge(methyl, mRNA[,-1], by = "row.names", all = F)
rownames(mix)<-mix[,1]
mix<-mix[,-1]
mix<-mix[-125:-121,]
write.table(mix,paste("/Users/icklerly/Desktop/UNI/PROJECT/data/mixed_Set.csv"),sep="\t",quote = FALSE,row.names=T,col.names =T)
write.table(mix,paste("/Users/icklerly/Desktop/UNI/PROJECT/data/mixed_Flink.csv"),sep="\t",quote = FALSE,row.names=F,col.names =F)
|
22e8771b54c8e7fb1c7af6dc3ca0bd1167f1d4bb | c6ed09339ff21fa70f154f34328e869f0dd8e394 | /blog/20171212/mxnet_R/iris_hnn.R | 1487430e3df9cf5255b061f0522668453d96b5c7 | [] | no_license | fits/try_samples | f9b15b309a67f7274b505669db4486b17bd1678b | 0986e22d78f35d57fe1dd94673b68a4723cb3177 | refs/heads/master | 2023-08-22T14:35:40.838419 | 2023-08-07T12:25:07 | 2023-08-07T12:25:07 | 642,078 | 30 | 19 | null | 2022-12-28T06:31:24 | 2010-05-02T02:23:55 | Java | UTF-8 | R | false | false | 805 | r | iris_hnn.R | library(mxnet)
train_size = 0.7
n = nrow(iris)
perm = sample(n, size = round(n * train_size))
train <- iris[perm, ]
test <-iris[-perm, ]
train.x <- data.matrix(train[1:4])
# 0-2
train.y <- as.numeric(train$Species) - 1
test.x <- data.matrix(test[1:4])
# 1-3
test.y <- as.numeric(test$Species)
mx.set.seed(0)
model <- mx.mlp(train.x, train.y,
hidden_node = 5,
out_node = 3,
num.round = 100,
learning.rate = 0.1,
array.batch.size = 10,
activation = 'relu',
array.layout = 'rowmajor',
eval.metric = mx.metric.accuracy)
pred <- predict(model, test.x, array.layout = 'rowmajor')
# 1-3
pred.y <- max.col(t(pred))
acc <- sum(pred.y == test.y) / length(pred.y)
print(acc)
|
48529ea1ec81329d6b5eab44137984c893463429 | 20bf2aace1538884b136f45a4bf8b8bc55488757 | /man/flag_variants.Rd | 9407d0a4cc2bde56830beef8bb5bde3ed2cb9361 | [
"MIT"
] | permissive | annaquaglieri16/samplepower | 9e1df31348c316e724962004e6f655708ed2b641 | 976df30813faf9cedd3621f3bf073909b9526301 | refs/heads/master | 2020-04-01T00:06:05.889841 | 2019-11-05T03:08:13 | 2019-11-05T03:08:13 | 152,682,047 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,370 | rd | flag_variants.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/flag_variants.R
\name{flag_variants}
\alias{flag_variants}
\title{Flag and annotate variants using external databases and panel of normals information}
\usage{
flag_variants(variants, normal_variants, flag_patterns, exon_ranges,
homop_ranges, RNAedit_ranges, repeats_ranges, flag_qualities = TRUE)
}
\arguments{
\item{variants}{dataframe containing all the variants in the cohort. This is created within the `variants_power()` function}
\item{normal_variants}{link to panel of normal file parsed with `samplepower::parse_pon`}
\item{flag_patterns}{dataframe containing the flags to assign to variants. THIS NEEDS TO BE SET AS INTERNAL TO THE PACKAGE}
\item{exon_ranges}{GRanges object with exon boundaries relative to the reference genome used}
\item{homop_ranges}{GRanges object with homopolymers regions of more than 5bp relative to the reference genome used}
\item{RNAedit_ranges}{GRanges object with RNA editing sites relative to the reference genome used}
\item{repeats_ranges}{GRanges object with repetitive regions of the reference genome used}
\item{flag_qualities}{logical. TRUE by default, variants are flagged based on quality measures. If FALSE this step is skipped.}
}
\description{
Flag and annotate variants using external databases and panel of normals information
}
|
a9a2a1c28583717e47adac43039c9746a5218683 | 1802ce06d84e890fb5e38dafcf8444fa75e9c957 | /logRank1s.Rcheck/00_pkg_src/logRank1s/tests/testthat/test_power.R | dfd13bf4d3b89eebd66517f17e6bff25656846bf | [] | no_license | XiaomengYuan9709/logRank1s | 0f29f1c6e440ef88283b3971ad8a4d3cef4714c8 | d8f5660c87aaf61c016b8b1895eaef9277bdfa22 | refs/heads/main | 2023-02-05T01:19:15.549476 | 2020-12-28T17:20:01 | 2020-12-28T17:20:01 | 319,453,727 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 177 | r | test_power.R | test_that("test if f function is correct", {
expect_equal(power(alpha = 0.05, n = 88, ta = 5, tf = 3,
m0 = 9, delta = 1/1.75, k = 1.22), 0.803)
}
) |
70b24a7ec68c29ca5386a0b193cb225bd7ea4c4b | 2b5c9578a769743cd993e449e19039486c3416b7 | /calc/old/analyses_anes.R | 2d8a83f993912aa978d38342b6556b45525d579b | [] | no_license | pwkraft/knowledge | 3eebd4d8205058c7b9aed92405f0ee6caeb4d7cc | 71d6dd6f82c017d32aca93dd2bd2106cbf46ee64 | refs/heads/master | 2023-07-07T10:30:41.230585 | 2023-07-04T08:18:39 | 2023-07-04T08:18:39 | 55,650,963 | 7 | 0 | null | null | null | null | UTF-8 | R | false | false | 21,745 | r | analyses_anes.R | ### ============================================================= ###
### Measuring Political Sophistication using Open-ended Responses ###
### Patrick Kraft ###
### ============================================================= ###
## main ANES analyses for paper + presentation (based on data created in prep.R)
rm(list = ls())
gc()
library(MASS)
library(tidyverse)
library(car)
library(quanteda)
library(stm)
library(corrplot)
library(ggplot2)
library(xtable)
library(gridExtra)
library(GGally)
library(dplyr)
library(pmisc)
library(stargazer)
library(rstan)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
setwd("/data/Dropbox/Uni/projects/2016/knowledge/calc")
## load data and stm results
load("out/anes2012.Rdata")
load("out/anes2016.Rdata")
load("out/anes2020.Rdata")
## QUESTION: remove wc=0 and spanish=1?
source("func.R")
## plot defaults
plot_default <- theme_classic(base_size=9) + theme(panel.border = element_rect(fill=NA))
plot_empty <- theme_classic(base_size=9) + theme(panel.border = element_rect(fill="white"))
### Check more comprehensive sophistication measure instead of pure factual knowledge
#data2012$polknow_factual <- with(data2012, polknow_factual + educ + faminc)/3
#data2016$polknow_factual <- with(data2016, polknow_factual + educ + faminc)/3
########
# correlation matrices: compare with common measures
########
## 2012 ANES
datcor <- data2012[,c("polknow_text_mean","polknow_factual","polknow_evalpre")]
colnames(datcor) <- paste0("v",1:ncol(datcor))
ggpairs(datcor, lower = list(continuous = wrap("smooth", alpha =.05, size=.2)), axisLabels="none"
, columnLabels = c("Discursive\nSophistication","Factual\nKnowledge"
,"Interviewer\nEvaluation")) + plot_default
ggsave("../fig/anes2012_corplot.pdf",width=3.2, height=3.2)
## 2016 ANES
datcor <- data2016[,c("polknow_text_mean","polknow_factual","polknow_evalpre")]
colnames(datcor) <- paste0("v",1:ncol(datcor))
ggpairs(datcor, lower = list(continuous = wrap("smooth", alpha =.05, size=.2)), axisLabels="none"
, columnLabels = c("Discursive\nSophistication","Factual\nKnowledge"
,"Interviewer\nEvaluation")) + plot_default
ggsave("../fig/anes2016_corplot.pdf",width=3.2, height=3.2)
## 2020 ANES
datcor <- data2020[,c("polknow_text_mean","polknow_factual")]
colnames(datcor) <- paste0("v",1:ncol(datcor))
ggpairs(datcor, lower = list(continuous = wrap("smooth", alpha =.05, size=.2)), axisLabels="none"
, columnLabels = c("Discursive\nSophistication","Factual\nKnowledge")) + plot_default
ggsave("../fig/anes2020_corplot.pdf",width=3.2, height=3.2)
## 2016 ANES poster version
ggpairs(datcor, lower = list(continuous = wrap("smooth", alpha =.05, size=.2)), axisLabels="none"
, columnLabels = c("Discursive\nSophistication","Factual\nKnowledge"
,"Interviewer\nEvaluation")) + plot_default
#ggsave("../fig/anes2016_corplot.pdf",width=4, height=4)
## ANES 2012 components
datcor <- data2012[,c("considerations","consistency","wordchoice")]
colnames(datcor) <- paste0("v",1:ncol(datcor))
ggpairs(datcor, lower = list(continuous = wrap("smooth", alpha =.05, size=.2)), axisLabels="none"
, columnLabels = c("Considerations","Consistency","Word Choice")) + plot_default
ggsave("../fig/anes2012_corplot_components.pdf",width=2.6, height=2.6)
## empty plot
ggpairs(datcor, lower = list(continuous = wrap("smooth", alpha =.05, size=.2)), axisLabels="none"
, columnLabels = c("Considerations","Consistency","Word Choice")) + plot_empty
ggsave("../fig/anes2012_corplot_components0.pdf",width=2.6, height=2.6)
## ANES 2016 components
datcor <- data2016[,c("considerations","consistency","wordchoice")]
colnames(datcor) <- paste0("v",1:ncol(datcor))
ggpairs(datcor, lower = list(continuous = wrap("smooth", alpha =.05, size=.2)), axisLabels="none"
, columnLabels = c("Considerations","Consistency","Word Choice")) + plot_default
ggsave("../fig/anes2016_corplot_components.pdf",width=2.6, height=2.6)
## label definition
dvnames <- c("Discursive\nSophistication","Factual\nKnowledge")
ivnames <- c("Intercept", "Gender\n(Female)", "Media\nExposure", "Political\nDiscussions", "Education\n(College)"
, "Income", "log(Age)", "Race\n(Black)", "Church\nAttendance", "Survey Mode\n(Online)")
########
# validation: effect on political engagement
########
### Joint model controlling for both measures + wordsum index
m4a <- m4b <- m4c <- NULL
m4a[[1]] <- glm(vote ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum, data = data2012, family=binomial("logit"))
m4a[[2]] <- lm(part ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum, data = data2012)
m4a[[3]] <- lm(effic_int ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum, data = data2012)
m4a[[4]] <- lm(effic_ext ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum, data = data2012)
m4b[[1]] <- glm(vote ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum, data = data2016, family=binomial("logit"))
m4b[[2]] <- lm(part ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum, data = data2016)
m4b[[3]] <- lm(effic_int ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum, data = data2016)
m4b[[4]] <- lm(effic_ext ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum, data = data2016)
m4c[[1]] <- glm(vote ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig, data = data2020, family=binomial("logit"))
m4c[[2]] <- lm(part ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig, data = data2020)
m4c[[3]] <- lm(effic_int ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig, data = data2020)
m4c[[4]] <- lm(effic_ext ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig, data = data2020)
res <- rbind(sim(m4a, iv=data.frame(polknow_text_mean=sdrange(data2012$polknow_text_mean))),
sim(m4a, iv=data.frame(polknow_factual=sdrange(data2012$polknow_factual))),
sim(m4b, iv=data.frame(polknow_text_mean=sdrange(data2016$polknow_text_mean))),
sim(m4b, iv=data.frame(polknow_factual=sdrange(data2016$polknow_factual))),
sim(m4c, iv=data.frame(polknow_text_mean=sdrange(data2016$polknow_text_mean))),
sim(m4c, iv=data.frame(polknow_factual=sdrange(data2016$polknow_factual))))
res$dvlab <- factor(res$dv, level = c("vote","part","effic_int","effic_ext")
, labels = c("Turnout","Non-conv. Participation"
, "Internal Efficacy","External Efficacy"))
res$ivlab <- factor(res$iv, labels = c("Discursive Sophistication", "Factual Knowledge"))
res$Year <- rep(c("2012 ANES","2016 ANES", "2020 ANES"), each=8)
ggplot(res, aes(y=ivlab, x=mean, xmin=cilo, xmax=cihi)) + geom_vline(xintercept = 0, color="grey") +
geom_point() + geom_errorbarh(height=0) + facet_grid(Year~dvlab, scale="free_x") +
xlab("Marginal Effect (-/+ 1 SD)") + ylab("Independent Variable") + plot_default +
scale_y_discrete(limits = rev(levels(res$ivlab))) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
ggsave("../fig/knoweff_pres.pdf", width=6.5, height=2.2)
ggplot(res, aes(y=ivlab, x=mean, xmin=cilo, xmax=cihi)) + geom_vline(xintercept = 0, color="grey") +
geom_point() + geom_errorbarh(height=0) + facet_grid(Year~dvlab, scale="free_x") +
xlab("Marginal Effect (-/+ 1 SD)") + ylab("Independent Variable") + plot_empty +
scale_y_discrete(limits = rev(levels(res$ivlab))) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
ggsave("../fig/knoweff_pres_empty.pdf", width=6.5, height=2.2)
## additional plots for presentation
filter(res, Year == "2012 ANES") %>%
ggplot(aes(y=ivlab, x=mean, xmin=cilo, xmax=cihi)) + geom_vline(xintercept = 0, color="grey") +
geom_point() + geom_errorbarh(height=0) + facet_wrap(.~dvlab, scale="free_x", ncol=2) +
xlab("Marginal Effect (-/+ 1 SD)") + ylab("Independent Variable") + plot_default +
scale_y_discrete(limits = rev(levels(res$ivlab)))
ggsave("../fig/knoweff_pres1.pdf", width=4, height=3)
filter(res, Year == "2012 ANES") %>%
ggplot(aes(y=ivlab, x=mean, xmin=cilo, xmax=cihi)) + geom_vline(xintercept = 0, color="grey") +
geom_point() + geom_errorbarh(height=0) + facet_wrap(.~dvlab, scale="free_x", ncol=2) +
xlab("Marginal Effect (-/+ 1 SD)") + ylab("Independent Variable") + plot_empty +
scale_y_discrete(limits = rev(levels(res$ivlab)))
ggsave("../fig/knoweff_pres0.pdf", width=4, height=3)
## plot for poster
res$dvlab <- factor(res$dv, level = c("vote","part","effic_int","effic_ext")
, labels = c("Turnout","Non-conv.\nParticip."
, "Internal\nEfficacy","External\nEfficacy"))
ggplot(res, aes(y=ivlab, x=mean, xmin=cilo, xmax=cihi)) + geom_vline(xintercept = 0, color="grey") +
geom_point(size=.5) + geom_errorbarh(height=0) + facet_grid(dvlab~Year, scale="free_x") +
xlab("Marginal Effect (-/+ 1 SD)") + ylab("Independent Variable") + plot_default +
scale_y_discrete(limits = rev(levels(res$ivlab)))
ggsave("../fig/knoweff_pres_poster.pdf", width=4, height=3)
### Robustness check: Joint model controlling for both measures + word count
m4c <- m4d <- NULL
m4c[[1]] <- glm(vote ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + lwc, data = data2012, family=binomial("logit"))
m4c[[2]] <- lm(part ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + lwc, data = data2012)
m4c[[3]] <- lm(effic_int ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + lwc, data = data2012)
m4c[[4]] <- lm(effic_ext ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + lwc, data = data2012)
m4d[[1]] <- glm(vote ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + lwc, data = data2016, family=binomial("logit"))
m4d[[2]] <- lm(part ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + lwc, data = data2016)
m4d[[3]] <- lm(effic_int ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + lwc, data = data2016)
m4d[[4]] <- lm(effic_ext ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + lwc, data = data2016)
res <- rbind(sim(m4c, iv=data.frame(polknow_text_mean=sdrange(data2012$polknow_text_mean)))
, sim(m4c, iv=data.frame(polknow_factual=sdrange(data2012$polknow_factual)))
, sim(m4d, iv=data.frame(polknow_text_mean=sdrange(data2016$polknow_text_mean)))
, sim(m4d, iv=data.frame(polknow_factual=sdrange(data2016$polknow_factual))))
res$dvlab <- factor(res$dv, level = c("vote","part","effic_int","effic_ext")
, labels = c("Turnout","Non-conv. Participation"
, "Internal Efficacy","External Efficacy"))
res$ivlab <- factor(res$iv, labels = dvnames)
res$Year <- rep(c("2012 ANES","2016 ANES"), each=8)
ggplot(res, aes(y=ivlab, x=mean, xmin=cilo, xmax=cihi)) + geom_vline(xintercept = 0, color="grey") +
geom_point() + geom_errorbarh(height=0) + facet_grid(Year~dvlab, scale="free_x") +
xlab("Marginal Effect (-/+ 1 SD)") + ylab("Independent Variable") + plot_default +
scale_y_discrete(limits = rev(levels(res$ivlab))) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
ggsave("../fig/knoweff_lwc.pdf", width=6.5, height=2.2)
### Robustness check: Joint model controlling for personality (extraversion and being reserved)
m4e <- m4f <- NULL
m4e[[1]] <- glm(vote ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + extraversion + reserved, data = data2012, family=binomial("logit"))
m4e[[2]] <- lm(part ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + extraversion + reserved, data = data2012)
m4e[[3]] <- lm(effic_int ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + extraversion + reserved, data = data2012)
m4e[[4]] <- lm(effic_ext ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + extraversion + reserved, data = data2012)
m4f[[1]] <- glm(vote ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + extraversion + reserved, data = data2016, family=binomial("logit"))
m4f[[2]] <- lm(part ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + extraversion + reserved, data = data2016)
m4f[[3]] <- lm(effic_int ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + extraversion + reserved, data = data2016)
m4f[[4]] <- lm(effic_ext ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum + extraversion + reserved, data = data2016)
res <- rbind(sim(m4e, iv=data.frame(polknow_text_mean=sdrange(data2012$polknow_text_mean)))
, sim(m4e, iv=data.frame(polknow_factual=sdrange(data2012$polknow_factual)))
, sim(m4f, iv=data.frame(polknow_text_mean=sdrange(data2016$polknow_text_mean)))
, sim(m4f, iv=data.frame(polknow_factual=sdrange(data2016$polknow_factual))))
res$dvlab <- factor(res$dv, level = c("vote","part","effic_int","effic_ext")
, labels = c("Turnout","Non-conv. Participation"
, "Internal Efficacy","External Efficacy"))
res$ivlab <- factor(res$iv, labels = dvnames)
res$Year <- rep(c("2012 ANES","2016 ANES"), each=8)
ggplot(res, aes(y=ivlab, x=mean, xmin=cilo, xmax=cihi)) + geom_vline(xintercept = 0, color="grey") +
geom_point() + geom_errorbarh(height=0) + facet_grid(Year~dvlab, scale="free_x") +
xlab("Marginal Effect (-/+ 1 SD)") + ylab("Independent Variable") + plot_default +
scale_y_discrete(limits = rev(levels(res$ivlab))) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
ggsave("../fig/knoweff_personality.pdf", width=6.5, height=2.2)
########
# validation: party/candidate placement precision
########
#hetreg_summary2012 <- filter(hetreg_summary2012, policy!="ideol")
hetreg_summary <- rbind(hetreg_summary2012, mutate(hetreg_summary2016, target=paste0("x", target))) %>%
filter(!target %in% c("rep", "dem"))
hetreg_summary$policy <- factor(hetreg_summary$policy
, labels = c("Ideology","Government\nSpending","Defense\nSpending"
,"Insurance\nPolicy","Job\nGuarantee","Aid to\nBlacks","Environment\nvs Jobs"))
hetreg_summary$measure <- factor(hetreg_summary$measure, levels = c("polknow_factual", "polknow_text_mean")
, labels = c("Factual\nKnowledge", "Discursive\nSophistication"))
hetreg_summary$target <- factor(hetreg_summary$target
, labels = c("Mitt\nRomney","Barack\nObama"
,"Donald\nTrump","Hillary\nClinton"))
hetreg_summary$Year <- rep(c("2012 ANES","2016 ANES"), each=nrow(hetreg_summary)/2)
ggplot(hetreg_summary, aes(y=measure, x=mean, xmin=cilo, xmax=cihi)) + geom_vline(xintercept = 0, color="grey") +
geom_point() + geom_errorbarh(height=0) + facet_grid(Year+target~policy) +
xlab("Error Variance Reduction (-/+ 1 SD)") + ylab("Independent Variable") +
plot_default + theme(axis.text.x = element_text(angle = 45, hjust = 1))
ggsave("../fig/hetreg.pdf",width = 6.5, height = 3.5)
hetreg_summary %>% filter(policy=="Ideology") %>%
ggplot(aes(y=measure, x=mean, xmin=cilo, xmax=cihi)) + geom_vline(xintercept = 0, color="grey") +
geom_point() + geom_errorbarh(height=0) + facet_wrap(~target, ncol=2) +
xlab("Error Variance Reduction (-/+ 1 SD)") + ylab("Independent Variable") + plot_default
ggsave("../fig/hetreg_pres.pdf",width = 4, height = 3)
#########
### validation: Correct Voting
#########
m5a <- glm(correct_vote ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum, data = data2012, family=binomial("logit"))
m5b <- glm(correct_vote ~ polknow_text_mean + polknow_factual + female + educ + faminc + log(age) + black + relig + mode + wordsum, data = data2016, family=binomial("logit"))
res <- rbind(data.frame(sim(m5a, iv=data.frame(polknow_text_mean=seq(min(data2012$polknow_text_mean),max(data2012$polknow_text_mean),length=10)))
, value=seq(min(data2012$polknow_text_mean),max(data2012$polknow_text_mean),length=10),Variable="Discursive Sophistication")
, data.frame(sim(m5a, iv=data.frame(polknow_factual=seq(0, 1,length=10)))
, value=seq(0, 1,length=10),Variable="Factual Knowledge")
, data.frame(sim(m5b, iv=data.frame(polknow_text_mean=seq(min(data2016$polknow_text_mean),max(data2016$polknow_text_mean),length=10)))
, value=seq(min(data2016$polknow_text_mean),max(data2016$polknow_text_mean),length=10),Variable="Discursive Sophistication")
, data.frame(sim(m5b, iv=data.frame(polknow_factual=seq(0, 1,length=10)))
, value=seq(0, 1,length=10),Variable="Factual Knowledge"))
res$ivlab <- factor(res$iv, labels = dvnames)
res$Year <- rep(c("2012 ANES","2016 ANES"), each=20)
ggplot(res, aes(x=value, y=mean, ymin=cilo,ymax=cihi, fill=Variable, lty=Variable)) + plot_default +
geom_ribbon(alpha=0.4, lwd=.1) + geom_line() +
facet_grid(~Year, scales="free_x") +
ylab("Expected Probability\nof Correct Vote") + xlab("Value of Independent Variable") + ylim(.75,1)
ggsave("../fig/correctvote.pdf",width=5,height=2)
###################
### Example Responses
###################
tmp <- data2012 %>%
filter(wc > (median(wc) - 5) & wc < (median(wc) + 5)
, polknow_factual == 0.6) %>%
arrange(polknow_text_mean)
tmp_select <- c(head(tmp$caseid), tail(tmp$caseid))
tmp <- anes2012opend %>%
filter(caseid %in% tmp_select) %>%
mutate(polknow_text_mean = data2012$polknow_text_mean[data2012$caseid %in% tmp_select]) %>%
arrange(polknow_text_mean)
write.csv(t(tmp), file="tmp/select2012.csv")
tmp <- data2016 %>%
filter(wc > (median(wc) - 5) & wc < (median(wc) + 5)
, polknow_factual == 0.75) %>%
arrange(polknow_text_mean)
tmp_select <- c(head(tmp$caseid), tail(tmp$caseid))
tmp <- anes2016opend %>%
filter(V160001 %in% tmp_select) %>%
mutate(polknow_text_mean = data2016$polknow_text_mean[data2016$caseid %in% tmp_select]) %>%
arrange(polknow_text_mean)
write.csv(t(tmp), file="tmp/select2016.csv")
## high/low considerations
tmp <- data2016 %>%
filter(wc > (median(wc) - 5) & wc < (median(wc) + 5)) %>%
arrange(ntopics)
tmp_select <- c(head(tmp$caseid, 10), tail(tmp$caseid, 10))
tmp <- anes2016opend %>%
filter(V160001 %in% tmp_select) %>%
mutate(ntopics = data2016$ntopics[data2016$caseid %in% tmp_select]) %>%
arrange(ntopics)
write.csv(t(tmp), file="tmp/select2016considerations.csv")
## high/low word choice
tmp <- data2016 %>%
filter(wc > (median(wc) - 5) & wc < (median(wc) + 5)) %>%
arrange(distinct)
tmp_select <- c(head(tmp$caseid, 10), tail(tmp$caseid, 10))
tmp <- anes2016opend %>%
filter(V160001 %in% tmp_select) %>%
mutate(distinct = data2016$distinct[data2016$caseid %in% tmp_select]) %>%
arrange(distinct)
write.csv(t(tmp), file="tmp/select2016wordchoice.csv")
## high/low ditem
tmp <- data2016 %>%
filter(wc > (median(wc) - 5) & wc < (median(wc) + 5)) %>%
arrange(ditem)
tmp_select <- c(head(tmp$caseid, 10), tail(tmp$caseid, 10))
tmp <- anes2016opend %>%
filter(V160001 %in% tmp_select) %>%
mutate(ditem = data2016$ditem[data2016$caseid %in% tmp_select]) %>%
arrange(ditem)
write.csv(t(tmp), file="tmp/select2016opinionation.csv")
data2016 %>%
filter(caseid %in% tmp_select) %>%
arrange(polknow_text_mean) %>%
dplyr::select(caseid, pid, ideol, educ, vc_pre, vc_post, vc_change, polknow_text_mean, polknow_factual)
###################
### Additional information: STM summaries
###################
summary(stm_fit2012)
summary(stm_fit2016)
pdf("../fig/anes_stm_prop.pdf", width=12, height=10)
par(mfrow=c(1,2), mar=c(4.2,0.5,2.5,0.5))
plot(stm_fit2012
, main=paste0("2012 ANES (k = ",stm_fit2012$settings$dim$K,")",collapse = "")
, n=5, labeltype = "prob", text.cex = 1)
plot(stm_fit2016
, main=paste0("2016 ANES (k = ",stm_fit2016$settings$dim$K,")",collapse = "")
, n=5, labeltype = "prob", text.cex = 1)
dev.off()
pdf("../fig/stm_labels.pdf")
par(mfrow=c(1,2), mar=c(0.5,0.5,2.5,0.5))
plot(stm_fit2012, "labels", topics=c(16,14,10,8), main="Sample Topics (2012 ANES)")
plot(stm_fit2016, "labels", topics=c(1,10,19,17), main="Sample Topics (2016 ANES)")
dev.off()
###################
### Save results for appendix
###################
save(m4a, m4b, m4c, m4d, m4e, m4f, m5a, m5b, hetreg_summary, file="out/anes_res.Rdata")
|
e569bdd783cd25ab6c80ae07580e21ea5c86dc37 | 9fc1b9975e2002ca3916ae02108d90962f5d2090 | /Gibbs_sampling_model.R | 52467a22576d59538e144f3a637fd2e78f392c61 | [] | no_license | sarcusa/varveR_Gibbs | 1391effa759258ceb3fce6d5ee72c39fbfe67597 | da1e89b9e8435e4534220baf3795b171a54d20bf | refs/heads/main | 2023-04-16T01:26:34.341906 | 2021-12-10T06:01:12 | 2021-12-10T06:01:12 | 301,879,865 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 18,712 | r | Gibbs_sampling_model.R | ######
# Original gibbs model algorithm for one observer. Best to run this not too many iterations.
#
# S. Arcusa
# 17-04-2020
lpdfile = "" # LipD file for COlumbine Lake. Available at https://doi.org/10.6084/m9.figshare.14417999
Obs3dir_172 = "" # Location folder containing data from observer 3 core COL17-2. Data available at https://doi.org/10.6084/m9.figshare.14251400.v1
Obs3dir_173 = "" # Location folder containing data from observer 3 core COL17-3. Data available at https://doi.org/10.6084/m9.figshare.14251400.v1
outputdir = "" # Folder location for output figures and output workstation
library("devtools")
library("varveR")
library("ggplot2")
library(geoChronR)
library("dplyr")
library(plyr)
library("lipdR")
library(matrixStats)
library(purrr)
library(tictoc)
# Load radiocarbon and lead data contained in the LiPD file
D <- readLipd(lpdfile)
# Run the BACON model
D <- runBacon(D,cutoff = 1e-10, lab.id.var = NULL, age.14c.var = "age14c",
age.14c.uncertainty.var = "age14cuncertainty",
age.uncertainty.var = "ageuncertainty",
reservoir.age.14c.var = NULL, rejected.ages.var = NULL,
reservoir.age.14c.uncertainty.var = NULL)
# Map the age ensemble to the data
core = mapAgeEnsembleToPaleoData(D, paleo.meas.table.num = 1, age.var = "ageensemble")
# Retrieving the age density distributions
# Prepare the 210Pb data
PB_distribution <- core$chronData[[1]]$model[[1]]$distributionTable
PB_probdens <- purrr::flatten(lapply(PB_distribution, function (x) x[c('probabilityDensity')]))
PB_dens <- purrr::flatten(lapply(PB_probdens, function (x) x[c('values')]))
PB_age <- purrr::flatten(lapply(PB_distribution, function (x) x[c('age')]))
PB_age_values <- purrr::flatten(lapply(PB_age, function (x) x[c('values')]))
# Combine 210Pb with 14C depths
depths_14C <- as.numeric(unlist(purrr::flatten(lapply(PB_distribution, function (x) x[c('depth')]))))
names(PB_dens) <- paste("depth_",depths_14C, sep = "")
names(PB_age_values) <- paste("depth_",depths_14C, sep = "")
# Prepare the 237Cs data
Cs_age <- seq(-15,-10,length.out = 250)
Cs_dens <-dnorm(Cs_age,-13,.25)
Cs_depth <- 3.25*10
Cs <- list(list(prop.table(Cs_dens),Cs_age,Cs_depth))
# Subset the 210Pb data
PB_dens <- PB_dens[c(13:19)]
PB_age_values <- PB_age_values[c(13:19)]
depths_14C <- depths_14C[c(13:19)]
# Prepare object containing 210Pb,237Cs,14Cs depths, densities and ages
C14 <- list()
l <- list()
for(i in 1: length(depths_14C)){
l[[1]] <- PB_dens[[i]]
l[[2]] <- PB_age_values[[i]]
l[[3]] <- depths_14C[i]*10
C14[[i]] <- l
}
C14 <- c(Cs,C14)
#Plot age-depth model
start = -70
end = 4000
chron.plot = plotChron(core, model.num = 1, age.var = "ageensemble",
x.bin = seq(start,end, by= 100),
dist.color = "#1E88E5",
probs = c(.1,.5,.9),y.bin = seq(0,300, by = 1))+
labs(title = "", x = "Age (yr BP)", y = "")+
xlim(end,start)+
theme_linedraw()+
theme(legend.position="none",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
plot(chron.plot)
## Load varve data for each core
col172 <- readVarveDirectory(Obs3dir_172,varveTop = "left")
col173 <- readVarveDirectory(Obs3dir_173,varveTop = "left")
o2 <- determineMarkerLayerOrder(col172)
names(col172)[o2]
o3 <- determineMarkerLayerOrder(col173)
names(col173)[o3]
col172_sequence <- combineSectionsByMarkerLayer(col172[o2])
col173_sequence <- combineSectionsByMarkerLayer(col173[o3])
# the following will calibrate the cumulative depth to the real depth at the last slide max depth
test3 <- vector()
OldMin = 0
NewMax = 1230
NewMin = 0
for(i in 1:nrow(col173_sequence)){
OldMax = max(cumsum(col173_sequence$thick), na.rm = T)
OldValue = col173_sequence$thick[i]
OldRange = (OldMax - OldMin)
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
test3[i] <- NewValue
}
col173_sequence$thick <- test3
test2 <- vector()
OldMin = 0
NewMax = 1270
NewMin = 0
for(i in 1:nrow(col172_sequence)){
OldMax = max(cumsum(col172_sequence$thick), na.rm = T)
OldValue = col172_sequence$thick[i]
OldRange = (OldMax - OldMin)
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
test2[i] <- NewValue
}
col172_sequence$thick <- test2
## Objective function
# Arguments
#
# ov1..n : overcounting probabilities for varve ID 1..n
# uc1..n : undercounting probabilities for varve ID 1..n
# C14 : a nested list with each sublist representing a radiocarbon depth and containing [1] the probability densities of each year, [2] the age value for each probability, and [3] the actual sample depth
# core 1 and core 2 should be col172_sequence and col173_sequence
objectiveFunction = function(ov1,uc1,ov2,uc2,ov3,uc3,C14,core1,core2){
# creates a table of codes
tt <- data.frame(codes = 1:6,
overcount = c(ov1,ov2,ov3,0,-2,-3),
undercount = c(uc1,uc2,uc3,.50,-2,-3))
# converts the codes to probabilities
seq1 <- translateCodesToProbabilities(core1,translationTable = tt,baselineProb = .05)
seq2 <- translateCodesToProbabilities(core2,translationTable = tt,baselineProb = .05)
# finds tie points and calculates varve thicknesses in each sequence
sseq1 <- simulateOverAndUndercounting(seq1)
g <- which(!is.na(sseq1$newThicks))
sseq1$ensThick <- sseq1$newThicks[g]
sseq1$tiePoints <- sseq1$newTiePoint[g]
sseq2 <- simulateOverAndUndercounting(seq2)
g <- which(!is.na(sseq2$newThicks))
sseq2$ensThick <- sseq2$newThicks[g]
sseq2$tiePoints <- sseq2$newTiePoint[g]
# creates a list of cores
ensList <- list(sseq1,sseq2)
#finds the common tiepoints
allTiePoints <- c("topOfCore",
na.omit(unique(c(unique(sseq1$newTiePoint)),
na.omit(unique(sseq2$newTiePoint)))))
#runs the model
MD <- fastVarveModel(ensList, allMarkerLayers = allTiePoints)
# Add cumulatitve depth in real unit
MD[[4]] <- cumsum(abs(MD[[2]][[2]]$thicks[which(!is.na(MD[[2]][[2]]$thicks))]))
# Add year
MD[[5]] <- seq(1,length(MD[[4]]),1)
# Rename each item in the varve model output
names(MD) <- c("ModelOutput", "PostInfo","MLpostAge","CumDepth", "Age")
y = vector() # vector of varve age at each depth
t = vector() # vector of positions of closest year in the each 14C sample age distribution
d = vector() # vector of age probability density for each 14C sample
for(j in 1:length(C14)){
# This finds the varve age at the same depth as the radiocarbon/lead sample.
# Note: the age scales must be the same so added calculation to do that
y[j] = 1950-(2018- MD$Age[which(abs(MD$CumDepth-as.numeric(C14[[j]][3])) ==
min(abs(MD$CumDepth-as.numeric(C14[[j]][3])),
na.rm = T))])
# Now looks for the closest year in the pdf of 14C
t[j] <- which(abs(unlist(C14[[j]][2])-y[j]) == min(abs(unlist(C14[[j]][2])-y[j]),
na.rm = T))
# and find its density
d[j] = unlist(C14[[j]][1])[which(abs(unlist(C14[[j]][2])-y[j]) ==
min(abs(unlist(C14[[j]][2])-y[j]),
na.rm = T))]
}
#print(d)
prob = prod(d) # multiply the density of all radiocarbon samples at that age
return(prob)
}
tic("myobjF")
objectiveFunction(0,0,0,0,0,0,C14 = C14,col172_sequence, col173_sequence)
objectiveFunction(0.01,0.01,0,0.1,0,0.25,C14 = C14,col172_sequence, col173_sequence)
objectiveFunction(0.05,0.05,0,0.2,0,0.6,C14 = C14,col172_sequence, col173_sequence)
toc()
logObjFun <- function(param,C14, core1, core2){
ov1 <- param[1]
ov2 <- param[3]
ov3 <- param[5]
uc1 <- param[2]
uc2 <- param[4]
uc3 <- param[6]
return(log(objectiveFunction(ov1,uc1,ov2,uc2,ov3,uc3,C14,core1,core2)))
}
tic("mylogF")
logObjFun(param = c(0,0,0,0,0,0),C14,col172_sequence, col173_sequence)
logObjFun(param = c(0.01,0.01,0,0.1,0,0.25),C14,col172_sequence, col173_sequence)
logObjFun(param = c(0.05,0.05,0,0.2,0,0.6),C14,col172_sequence, col173_sequence)
toc()
# this function sets the priors for varve ID 1 and 2 as gamma curves, ID 3 as flat line priors
pV<- function(priors){
pout <- vector()
pout[1] <- dgamma(priors[1],shape = 2,rate = 10)/100
pout[2] <- dgamma(priors[2],shape = 2,rate = 10)/100
pout[3] <- dgamma(priors[3],shape = 10,rate = 20)/100
pout[4] <- dgamma(priors[4],shape = 6,rate = 20)/100
pout[5] <- dunif(priors[5])/100
pout[6] <- dunif(priors[6]) /100
return(prod(pout))
}
tic("ourGibbs")
nIt <- 1e6
paramChain = matrix(NA,nrow = nIt,6)
objChain = matrix(NA,nrow = nIt,6)
paramChain[1,] = c(0.05,0.05,0.1,0.2,0.3,0.6)
objChain[1,1] <-logObjFun(param = c(paramChain[1,1],paramChain[1,2],paramChain[1,3],
paramChain[1,4],paramChain[1,5],paramChain[1,6]),
C14,col172_sequence,col173_sequence)
#objChain[1,2] <-logObjFun(param = c(paramChain[1,1],paramChain[1,2],paramChain[1,3],
# paramChain[1,4],paramChain[1,5],paramChain[1,6]),
# C14,col172_sequence, col173_sequence)
#objChain[1,3] <-logObjFun(param = c(paramChain[1,1],paramChain[1,2],paramChain[1,3],
# paramChain[1,4],paramChain[1,5],paramChain[1,6]),
# C14,col172_sequence, col173_sequence)
#objChain[1,4] <-logObjFun(param = c(paramChain[1,1],paramChain[1,2],paramChain[1,3],
# paramChain[1,4],paramChain[1,5],paramChain[1,6]),
# C14,col172_sequence, col173_sequence)
#objChain[1,5] <-logObjFun(param = c(paramChain[1,1],paramChain[1,2],paramChain[1,3],
# paramChain[1,4],paramChain[1,5],paramChain[1,6]),
# C14,col172_sequence, col173_sequence)
#objChain[1,6] <-logObjFun(param = c(paramChain[1,1],paramChain[1,2],paramChain[1,3],
# paramChain[1,4],paramChain[1,5],paramChain[1,6]),
# C14,col172_sequence, col173_sequence)
oldProb <- exp(objChain[1,1]) # changed from objChain[1,2]
objChain[1,] <- objChain[1,1]
tic("chain")
# loop through each step in the chain
for(i in 2:2){ #choose here if running loop in segments
#for(i in 2:nrow(paramChain)){ #choose here if running loop in one go
print(i)
#each time through initialize with the last time
paramChain[i,]=paramChain[i-1,]
# loop through each parameter
for(j in seq(1,ncol(paramChain),2)){
# This limits the parameters to between 0 and 1
repeat{
a = abs(rnorm(1,sd = 0.1)) # use 0.1 to start, then 0.05
b = abs(rnorm(1,sd = 0.1))
if(runif(1) > 0.5){
a = a*-1
}else{
b = b*-1
}
test1 = paramChain[i-1,j]+a
test2 = paramChain[i-1,j+1]+b
if(test1 >= 0 & test1 <=1 & test2 >= 0 & test2 <=1) break
}
#innovate on the parameter by adjusting by a random normal number
paramChain[i,j]=test1
paramChain[i,j+1]=test2 # this was added
#this tries the varve model and if an error arrises, it repeats the previous row
# Calculates the log objective function
#newProb <- try(logObjFun(param = c(paramChain[i,1],paramChain[i,2],paramChain[i,3],
# paramChain[i,4],paramChain[i,5],paramChain[i,6]),
# C14,col172_sequence, col173_sequence)) #removed on 22-06-20
# Takes into account the priors through the function pv
newProb <- try(exp(logObjFun(param = c(paramChain[i,1],paramChain[i,2],
paramChain[i,3],paramChain[i,4],
paramChain[i,5],paramChain[i,6]),
C14,col172_sequence,
col173_sequence))*pV(paramChain[i,]))
if(!class(newProb)=="try-error"){
#trying to get the number bigger
if( newProb/oldProb >= runif(1)){
#if it passes, update old prob
oldProb <- newProb
}else{
#if it fails, keep it the same
paramChain[i,j] <- paramChain[i-1,j]
paramChain[i,j+1] <- paramChain[i-1,j+1]
}
#update the objective tracker with the updated, or previous prob
objChain[i,j] <- log(oldProb)
#if there is an error, repeats
} else {
print("got error")
paramChain[i,j] <- paramChain[i-1,j]
paramChain[i,j+1] <- paramChain[i-1,j+1]
objChain[i,j] <- log(oldProb)
}
#print(oldProb)
}
p <- seq(0,nIt,10)
if(i %in% p){
print(objChain[(i-5):i,])
print(paramChain[(i-5):i,])
}
q <- seq(0,nIt,1000)
if(i %in% q){
save.image(paste0(outputdir,"gibbs_sampling_workstation.RData"))
}
}
save.image(paste0(outputdir,"gibbs_sampling_workstation.RData"))
toc()
## Plotting varve model results to check
#' Plots a varve age depth model with uncertainty using the last 1000 sets of parameters from the Gibbs sampler
#'
#' @description The function will loop through the last 1000 sets of parameters from the Gibbs sampler using the
#' fastVarveModel and plot the varve age depth model with uncertainty against the independent age depth model
#'
#' @param param the paramChain output from the Gibbs sampler
#' @param core1 The first core sequence output from the function combineSectionsByMarkerLayer
#' @param core2 The second core sequence output from the function combineSectionsByMarkerLayer
#' @param N The last possible iteration number of the Gibbs sampler. For example, if the sampler was run one
#' million times, then N would be set to one million
#' @param ind.plot The independent age depth model to compare the varve model to. This should be the output of
#' GeoChronR function plotChron
#' @param somedepths A vector of depths at which to calculate the age spread. This could be the depths of
#' radiocarbon samples
#' @param it The number of iterations to run the fastVarveModel for
#'
#' @return A plot comparing the independent age depth model against the varve age depth model
#' @return A
#'
plot_varve_model_Gibbs <- function(param, core1, core2, N, ind.plot, somedepths, it){
ens.thicks <- list()
for(i in 1:it){
print(i)
tt <- data.frame(codes = 1:6,
overcount = c(param[N-i,1],param[N-i,3],param[N-i,5],0,-2,-3),
undercount = c(param[N-i,2],param[N-i,4],param[N-i,6],.50,-2,-3))
seq1 <- translateCodesToProbabilities(core1,translationTable = tt,baselineProb = .05)
seq2 <- translateCodesToProbabilities(core2,translationTable = tt,baselineProb = .05)
sseq1 <- simulateOverAndUndercounting(seq1)
g <- which(!is.na(sseq1$newThicks))
sseq1$ensThick <- sseq1$newThicks[g]
sseq1$tiePoints <- sseq1$newTiePoint[g]
sseq2 <- simulateOverAndUndercounting(seq2)
g <- which(!is.na(sseq2$newThicks))
sseq2$ensThick <- sseq2$newThicks[g]
sseq2$tiePoints <- sseq2$newTiePoint[g]
ensList <- list(sseq1,sseq2)
allTiePoints <- c("topOfCore",
na.omit(unique(c(unique(sseq1$newTiePoint)),
na.omit(unique(sseq2$newTiePoint)))))
MD <- fastVarveModel(ensList, allMarkerLayers = allTiePoints)
ens.thicks[[i]] <- MD[[2]][[2]]$thicks
}
ens.cumSum <- lapply(ens.thicks, function(x) cumsum(abs(x[which(!is.na(x))])))
ens.age <- lapply(ens.cumSum, function(x) seq(1,length(x),1))
indx <- sapply(ens.thicks, length)
res <- as.data.frame(do.call(cbind,lapply(ens.thicks, `length<-`,max(indx))))
ageEns <- createEnsembleAgeDepthModel(res)
ageModel <- createDepth2AgeFunction(ageDepthMat = ageEns$ageDepthEns)
varveAges <- ageModel(somedepths*10) # somedepths must be in mm
compare.models <- ind.plot +
geom_ribbon(aes(y = ageEns$summaryTable[,1]/10,xmin = -67+ageEns$summaryTable[,2],
xmax = -67+ageEns$summaryTable[,6]),fill = "gray80")+
geom_line(aes(x = -67+ageEns$summaryTable[,4], y = ageEns$summaryTable[,1]/10), color = "red")
print(compare.models)
return(varveAges)
return(ageEns)
}
comp.plot <- plot_varve_model(param = paramChain, core1 = col172_sequence, core2 = col173_sequence, N = 30000, ind.plot = chron.plot, somedepths = depths_14C, it = 10)
## Plotting results of Gibbs
plot_Gibbs_results <- function(obj,param,n, plot.save){
# Plots the objective chain
if(plot.save == TRUE){
pdf(file = paste0(outputdir,"ObjChain_plot.pdf"))
plot((obj[,1]),type = "l", xlim = c(0,n),
xlab = "# iterations", ylab = "Objective Function (log)")
dev.off()
b <- readline("What burn in value to use?")
b <- as.numeric(unlist(strsplit(b, ",")))
names_param <- c("Overcounting prob.varve ID1",
"Undercounting prob. varve ID1",
"Overcounting prob. varve ID2",
"Undercounting prob. varve ID2",
"Overcounting prob. varve ID3",
"Undercounting prob. varve ID3")
pdf(file = paste0(outputdir,"ParamChain_plot.pdf"))
par(mfrow = c(3,2))
for(i in 1:6){
plot(param[,i],type = "l",xlim = c(0,n),
xlab = "# iterations", ylab = names_param[i])
}
dev.off()
tki <- seq(b,n,by = 1)
pdf(file = paste0(outputdir,"HistParam_plot.pdf"))
par(mfrow = c(3,2))
for(i in 1:6){
hist(param[tki,i], xlab = names_param[i], main = "")
}
dev.off()
}else{
plot((obj[,1]),type = "l", xlim = c(0,n),
xlab = "# iterations", ylab = "Objective Function (log)")
b <- readline("What burn in value to use?")
b <- as.numeric(unlist(strsplit(b, ",")))
names_param <- c("Overcounting prob.varve ID1",
"Undercounting prob. varve ID1",
"Overcounting prob. varve ID2",
"Undercounting prob. varve ID2",
"Overcounting prob. varve ID3",
"Undercounting prob. varve ID3")
par(mfrow = c(3,2))
for(i in 1:6){
plot(param[,i],type = "l",xlim = c(0,n),
xlab = "# iterations", ylab = names_param[i])
}
tki <- seq(b,n,by = 1)
dev.new()
par(mfrow = c(3,2))
for(i in 1:6){
hist(param[tki,i], xlab = names_param[i], main = "")
}
}
}
plot_Gibbs_results(obj = objChain, param = paramChain, n = 40000, plot.save = F)
min(which(is.na(objChain[,1])))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.