content large_stringlengths 0 6.46M | path large_stringlengths 3 331 | license_type large_stringclasses 2 values | repo_name large_stringlengths 5 125 | language large_stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.46M | extension large_stringclasses 75 values | text stringlengths 0 6.46M |
|---|---|---|---|---|---|---|---|---|---|
context("Stress HARA Risk Measure")
library("SWIM")
set.seed(0)
x <- data.frame(cbind(
"normal" = rnorm(1000),
"gamma" = rgamma(1000, shape = 2)))
################ stress via function ################
res1 <- stress_wass(type = "HARA RM", x = x, a=1, b=5, eta=0.5, alpha=0.95,
q_ratio=1.05, hu_ratio=1.05, k=1)
# output test
output_test_w(res1, x)
# specs test
test_that("specs", {
expect_named(get_specs(res1), c('type', 'k', 'q', 'alpha', 'hu', 'a', 'b', 'eta'))
expect_equal(res1$type[[1]], "HARA RM")
expect_type(res1$h, "list")
expect_type(res1$lam, "list")
expect_type(res1$str_fY, "list")
expect_type(res1$str_FY, "list")
expect_type(res1$str_FY_inv, "list")
expect_type(res1$gamma, "list")
})
################ stress via scenraio weights ################
res2 <- stress_HARA_RM_w(x = x, a=1, b=5, eta=0.5, alpha=0.95,
q_ratio=1.05, hu_ratio=1.05, k=2)
# output test
output_test_w(res2, x)
# specs test
test_that("specs", {
expect_named(get_specs(res2), c('type', 'k', 'q', 'alpha', 'hu', 'a', 'b', 'eta'))
expect_equal(res2$type[[1]], "HARA RM")
expect_type(res2$h, "list")
expect_type(res2$lam, "list")
expect_type(res2$str_fY, "list")
expect_type(res2$str_FY, "list")
expect_type(res2$str_FY_inv, "list")
expect_type(res2$gamma, "list")
})
################ merge two stresses ################
merge_test_w(res1, res2)
################ summary ################
sum_test(res1)
sum_test(res2) | /tests/testthat/test_stress_HARA_RM.R | no_license | spesenti/SWIM | R | false | false | 1,544 | r | context("Stress HARA Risk Measure")
library("SWIM")
set.seed(0)
x <- data.frame(cbind(
"normal" = rnorm(1000),
"gamma" = rgamma(1000, shape = 2)))
################ stress via function ################
res1 <- stress_wass(type = "HARA RM", x = x, a=1, b=5, eta=0.5, alpha=0.95,
q_ratio=1.05, hu_ratio=1.05, k=1)
# output test
output_test_w(res1, x)
# specs test
test_that("specs", {
expect_named(get_specs(res1), c('type', 'k', 'q', 'alpha', 'hu', 'a', 'b', 'eta'))
expect_equal(res1$type[[1]], "HARA RM")
expect_type(res1$h, "list")
expect_type(res1$lam, "list")
expect_type(res1$str_fY, "list")
expect_type(res1$str_FY, "list")
expect_type(res1$str_FY_inv, "list")
expect_type(res1$gamma, "list")
})
################ stress via scenraio weights ################
res2 <- stress_HARA_RM_w(x = x, a=1, b=5, eta=0.5, alpha=0.95,
q_ratio=1.05, hu_ratio=1.05, k=2)
# output test
output_test_w(res2, x)
# specs test
test_that("specs", {
expect_named(get_specs(res2), c('type', 'k', 'q', 'alpha', 'hu', 'a', 'b', 'eta'))
expect_equal(res2$type[[1]], "HARA RM")
expect_type(res2$h, "list")
expect_type(res2$lam, "list")
expect_type(res2$str_fY, "list")
expect_type(res2$str_FY, "list")
expect_type(res2$str_FY_inv, "list")
expect_type(res2$gamma, "list")
})
################ merge two stresses ################
merge_test_w(res1, res2)
################ summary ################
sum_test(res1)
sum_test(res2) |
\name{setStyleNamePrefix-methods}
\docType{methods}
\alias{setStyleNamePrefix}
\alias{setStyleNamePrefix-methods}
\alias{setStyleNamePrefix,workbook-method}
\title{Setting the style name prefix for the "name prefix" style action}
\description{
Sets the style name prefix for the "name prefix" style action.
}
\usage{
\S4method{setStyleNamePrefix}{workbook}(object,prefix)
}
\arguments{
\item{object}{The \code{\linkS4class{workbook}} to use}
\item{prefix}{The name prefix}
}
\details{
Sets the \code{prefix} for the "name prefix" style action. See the method \code{\link[=setStyleAction-methods]{setStyleAction}} for more information.
}
\author{
Martin Studer\cr
Mirai Solutions GmbH \url{https://mirai-solutions.ch}
}
\seealso{
\code{\linkS4class{workbook}}, \code{\linkS4class{cellstyle}}, \code{\link[=setStyleAction-methods]{setStyleAction}},
\code{\link[=createCellStyle-methods]{createCellStyle}}
}
\keyword{methods}
\keyword{utilities}
| /man/setStyleNamePrefix-methods.Rd | no_license | miraisolutions/xlconnect | R | false | false | 981 | rd | \name{setStyleNamePrefix-methods}
\docType{methods}
\alias{setStyleNamePrefix}
\alias{setStyleNamePrefix-methods}
\alias{setStyleNamePrefix,workbook-method}
\title{Setting the style name prefix for the "name prefix" style action}
\description{
Sets the style name prefix for the "name prefix" style action.
}
\usage{
\S4method{setStyleNamePrefix}{workbook}(object,prefix)
}
\arguments{
\item{object}{The \code{\linkS4class{workbook}} to use}
\item{prefix}{The name prefix}
}
\details{
Sets the \code{prefix} for the "name prefix" style action. See the method \code{\link[=setStyleAction-methods]{setStyleAction}} for more information.
}
\author{
Martin Studer\cr
Mirai Solutions GmbH \url{https://mirai-solutions.ch}
}
\seealso{
\code{\linkS4class{workbook}}, \code{\linkS4class{cellstyle}}, \code{\link[=setStyleAction-methods]{setStyleAction}},
\code{\link[=createCellStyle-methods]{createCellStyle}}
}
\keyword{methods}
\keyword{utilities}
|
library(dplyr)
library(stringr)# to count N, L and C
# Data import ------------------------------------------------------------------
before_wl <- read.csv("./data/before_wl.csv")
before_co <- read.csv("./data/before_co.csv")
test_co <- read.csv("./data/test_co.csv")
test_wl <- read.csv("./data/test_wl.csv")
after_co <- read.csv("./data/after_co.csv")
after_wl <- read.csv("./data/after_wl.csv")
# Data Cleaning ----------------------------------------------------------------
clean.co<-function(x,time){
tab<-x%>%
group_by(theugid)%>%
mutate(reg_times = sum(reg_success))%>%
mutate(Status=ifelse(reg_times>0,"Create","Lost"))
tab$Phase=time
col=if(time!="Test"){
c("thedevice","firstpage","Status" ,"Phase")
}else{
c("thedevice","Status","firstpage","Phase","themodule")
}
tab=tab[,col]
return(tab)
}
clean.wl<-function(x,time){
# check the status
x$number.of.l <- str_count(x$login_or_create, "L")
x$number.of.c <- str_count(x$login_or_create, "C")
x$number.of.user <-x$eventcount-str_count(x$isloggedin_r, "by-session")
x$creat_s<-ifelse(x$number.of.c>0 & x$number.of.user>0,1,0)
x$creat_f<-ifelse(x$number.of.c>0 & x$number.of.user==0,1,0)
x$return_s <- ifelse(x$number.of.c==0 & x$number.of.l>0 & x$number.of.user>0,1,0)
x$return_f <- ifelse(x$number.of.c==0 & x$number.of.l>0 & x$number.of.user==0,1,0)
# add one column to indicate the status
tbl<-x%>%
group_by(date=as.Date(X_time), theugid)%>%
mutate(cs_times = sum(creat_s),
cf_times = sum(creat_f),
rs_times = sum(return_s),
rf_times = sum(return_f))%>%
mutate(Status=ifelse(cs_times>0,
"Create_S",
ifelse(cf_times>0,
"Create_F",
ifelse(rs_times>0,
"Return_S",
ifelse(rf_times>0,
"Return_F",
"Lost"
)))))
tbl$Phase=time
col=if(time!="Test"){
c("thedevice","firstpage","Status" ,"Phase")
}else{
c("thedevice","Status","firstpage","Phase","themodule")
}
tbl=tbl[,col]
return(tbl)
}
clean.wl.bi<-function(x,time){
tbl=clean.wl(x,time)
tbl=tbl%>%
filter(Status %in% c("Create_S","Create_F"))
return(tbl)
}
clean.combine<-function(x,time1,y,time2,z,time3,function1){
DT1=function1(x,time1)
DT2=function1(y,time2)
DT3=function1(z,time3)
Final=as.data.frame(bind_rows(DT1,DT2,DT3))
Final=as.data.frame(sapply(Final,as.factor)) # sapply won't work????? older version of R
Final$Status<- relevel(Final$Status,
ref = ifelse(as.character(substitute(function1))=="clean.co",
"Create",
"Create_S"))
Final$Phase <- relevel(Final$Phase, ref = "Test")
Final$themodule <- relevel(Final$themodule, ref = "F")
return(Final)
}
co_final=clean.combine(before_co,"Before",test_co,"Test",after_co,"After",clean.co)
wl_final=clean.combine(before_wl,"Before",test_wl,"Test",after_wl,"After",clean.wl)
wl_final_bi=clean.combine(before_wl,"Before",test_wl,"Test",after_wl,"After",clean.wl.bi)
# Data Analysis
library(ggplot2)
# Basic Visualization
#
ggplot(co_final, aes(x = Phase)) +
geom_histogram(stat="count",
aes(fill = Status),
position = 'fill') +
ggtitle("Checkout: \nStatus By Phase")
#
ggplot(wl_final_bi, aes(x = Phase)) +
geom_histogram(stat="count",
aes(fill = Status),
position = 'fill') +
ggtitle("Wishlist: \n Status by Phase")
#
ggplot(co_final, aes(x = themodule)) +
geom_histogram(stat="count",
aes(fill = themodule)) +
ggtitle("Checkout: \n Facebook vs. Google")
#
ggplot(wl_final_bi, aes(x = themodule)) +
geom_histogram(stat="count",
aes(fill = themodule)) +
ggtitle("Wishlist: \n Facebook vs. Google")
# Groupby Summarise to see Numbers
| /ML_in_R/solution_clean.R | no_license | skickham/MachineLearning_practice | R | false | false | 4,118 | r | library(dplyr)
library(stringr)# to count N, L and C
# Data import ------------------------------------------------------------------
before_wl <- read.csv("./data/before_wl.csv")
before_co <- read.csv("./data/before_co.csv")
test_co <- read.csv("./data/test_co.csv")
test_wl <- read.csv("./data/test_wl.csv")
after_co <- read.csv("./data/after_co.csv")
after_wl <- read.csv("./data/after_wl.csv")
# Data Cleaning ----------------------------------------------------------------
clean.co<-function(x,time){
tab<-x%>%
group_by(theugid)%>%
mutate(reg_times = sum(reg_success))%>%
mutate(Status=ifelse(reg_times>0,"Create","Lost"))
tab$Phase=time
col=if(time!="Test"){
c("thedevice","firstpage","Status" ,"Phase")
}else{
c("thedevice","Status","firstpage","Phase","themodule")
}
tab=tab[,col]
return(tab)
}
clean.wl<-function(x,time){
# check the status
x$number.of.l <- str_count(x$login_or_create, "L")
x$number.of.c <- str_count(x$login_or_create, "C")
x$number.of.user <-x$eventcount-str_count(x$isloggedin_r, "by-session")
x$creat_s<-ifelse(x$number.of.c>0 & x$number.of.user>0,1,0)
x$creat_f<-ifelse(x$number.of.c>0 & x$number.of.user==0,1,0)
x$return_s <- ifelse(x$number.of.c==0 & x$number.of.l>0 & x$number.of.user>0,1,0)
x$return_f <- ifelse(x$number.of.c==0 & x$number.of.l>0 & x$number.of.user==0,1,0)
# add one column to indicate the status
tbl<-x%>%
group_by(date=as.Date(X_time), theugid)%>%
mutate(cs_times = sum(creat_s),
cf_times = sum(creat_f),
rs_times = sum(return_s),
rf_times = sum(return_f))%>%
mutate(Status=ifelse(cs_times>0,
"Create_S",
ifelse(cf_times>0,
"Create_F",
ifelse(rs_times>0,
"Return_S",
ifelse(rf_times>0,
"Return_F",
"Lost"
)))))
tbl$Phase=time
col=if(time!="Test"){
c("thedevice","firstpage","Status" ,"Phase")
}else{
c("thedevice","Status","firstpage","Phase","themodule")
}
tbl=tbl[,col]
return(tbl)
}
clean.wl.bi<-function(x,time){
tbl=clean.wl(x,time)
tbl=tbl%>%
filter(Status %in% c("Create_S","Create_F"))
return(tbl)
}
clean.combine<-function(x,time1,y,time2,z,time3,function1){
DT1=function1(x,time1)
DT2=function1(y,time2)
DT3=function1(z,time3)
Final=as.data.frame(bind_rows(DT1,DT2,DT3))
Final=as.data.frame(sapply(Final,as.factor)) # sapply won't work????? older version of R
Final$Status<- relevel(Final$Status,
ref = ifelse(as.character(substitute(function1))=="clean.co",
"Create",
"Create_S"))
Final$Phase <- relevel(Final$Phase, ref = "Test")
Final$themodule <- relevel(Final$themodule, ref = "F")
return(Final)
}
co_final=clean.combine(before_co,"Before",test_co,"Test",after_co,"After",clean.co)
wl_final=clean.combine(before_wl,"Before",test_wl,"Test",after_wl,"After",clean.wl)
wl_final_bi=clean.combine(before_wl,"Before",test_wl,"Test",after_wl,"After",clean.wl.bi)
# Data Analysis
library(ggplot2)
# Basic Visualization
#
ggplot(co_final, aes(x = Phase)) +
geom_histogram(stat="count",
aes(fill = Status),
position = 'fill') +
ggtitle("Checkout: \nStatus By Phase")
#
ggplot(wl_final_bi, aes(x = Phase)) +
geom_histogram(stat="count",
aes(fill = Status),
position = 'fill') +
ggtitle("Wishlist: \n Status by Phase")
#
ggplot(co_final, aes(x = themodule)) +
geom_histogram(stat="count",
aes(fill = themodule)) +
ggtitle("Checkout: \n Facebook vs. Google")
#
ggplot(wl_final_bi, aes(x = themodule)) +
geom_histogram(stat="count",
aes(fill = themodule)) +
ggtitle("Wishlist: \n Facebook vs. Google")
# Groupby Summarise to see Numbers
|
### interactive/rscripts.R ------------------------
# Header
# Filename: rscripts.R
# Description: Contains functions generating various R scripts.
# Author: Nima Ramezani Taghiabadi
# Email : nima.ramezani@cba.com.au
# Start Date: 23 May 2017
# Last Revision: 23 May 2017
# Version: 0.0.1
#
# Version History:
# Version Date Action
# ----------------------------------
# 0.0.1 23 May 2017 Initial issue for D3TableFilter syncing observers
# for a output object of type D3TableFilter, D3TableFilter generates an input
# "<chartID>_edit"
# this observer does a simple input validation and sends a confirm or reject message after each edit.
# Only server to client!
D3TableFilter.observer.column.footer.R = function(itemID){paste0("
nms = c('rownames', colnames(sync$", itemID, "))
for (col in names(sync$", itemID, "_column.footer)){
wch = which(nms == col) - 1
if (inherits(sync$", itemID, "_column.footer[[col]], 'function')){val = sapply(list(sync$", itemID, "[report$", itemID, "_filtered, col]), sync$", itemID, "_column.footer[[col]])}
else {val = sync$", itemID, "_column.footer[[col]] %>% as.character}
for (cn in wch){if(!is.empty(val)){setFootCellValue(session, tbl = '", itemID, "', row = 1, col = cn, value = val)}}
}
")}
# server to client
D3TableFilter.observer.column.editable.R = function(itemID){paste0("
#debug(check)
#check(x = sync$", itemID, "_column.editable)
enacols = sync$", itemID, "_column.editable %>% unlist %>% coerce('logical') %>% which %>% names %>% intersect(c('rownames', colnames(sync$", itemID, ")))
discols = c('rownames', colnames(sync$", itemID, ")) %-% enacols
for(col in enacols){
if (col == 'rownames'){
enableEdit(session, '", itemID, "', 'col_0')
} else {
w = which(names(sync$", itemID, ") == col)
enableEdit(session, '", itemID, "', 'col_' %++% w);
}
}
for(col in discols){
if (col == 'rownames'){
disableEdit(session, '", itemID, "', 'col_0')
} else {
w = which(names(sync$", itemID, ") == col)
disableEdit(session, '", itemID, "', 'col_' %++% w);
}
}
")
}
# client to server:
D3TableFilter.observer.edit.R = function(itemID) {paste0("
if(is.null(input$", itemID, "_edit)) return(NULL);
edit <- input$", itemID, "_edit;
isolate({
# need isolate, otherwise this observer would run twice
# for each edit
id <- edit$id;
row <- as.integer(edit$row);
col <- as.integer(edit$col);
val <- edit$val;
nms <- colnames(sync$", itemID, ")
if(col == 0) {
oldval <- rownames(sync$", itemID, ")[row];
cellClass = 'character'
fltr = items[['", itemID, "']]$filter[['rownames']]}
else {
oldval <- sync$", itemID, "[row, col];
fltr = items[['", itemID, "']]$filter[[nms[col]]]
cellClass = class(sync$", itemID, "[, col])[1]
}
val0 = val
val = try(coerce(val, cellClass), silent = T)
accept = inherits(val, cellClass) & !is.empty(val)
if(accept & inherits(fltr, 'list') & !is.empty(fltr)){
accept = parse(text = filter2R(fltr)) %>% eval
}
if (accept){
if(col == 0) {
rownames(sync$", itemID, ")[row] <- val;
rownames(report$", itemID, ")[row] <- val;
} else {
shp = items[['", itemID, "']]$config$column.shape[[nms[col]]]
if (!is.null(shp)){
if(shp == 'radioButtons'){
sync$", itemID, "[, col] <- FALSE;
report$", itemID, "[, col] <- FALSE;
}
}
sync$", itemID, "[row, col] <- val;
report$", itemID, "[row, col] <- val;
}
# confirm edits
confirmEdit(session, tbl = '", itemID, "', row = row, col = col, id = id, value = val);
report$", itemID, "_lastEdits['Success', 'Row'] <- row;
report$", itemID, "_lastEdits['Success', 'Column'] <- col;
report$", itemID, "_lastEdits['Success', 'Value'] <- val;
} else {
rejectEdit(session, tbl = '", itemID, "', row = row, col = col, id = id, value = oldval);
report$", itemID, "_lastEdits['Fail', 'Row'] <- row;
report$", itemID, "_lastEdits['Fail', 'Column'] <- col;
report$", itemID, "_lastEdits['Fail', 'Value'] <- val0;
}
})
")}
# Use it later for creating the default footer:
# footer = list('Mean', object[[i]] %>% colMeans %>% as.matrix %>% t) %>% as.data.frame
# names(footer) = c('Rownames', colnames(object[[i]]))
# Client 2 Server: FOB1
D3TableFilter.observer.filter.C2S.R = function(itemID){
paste0("
if(is.null(input$", itemID, "_filter)){return(NULL)}
isolate({
report$", itemID, "_filtered <- unlist(input$", itemID, "_filter$validRows);
sync$", itemID, "_column.filter = list()
nms = c('rownames', colnames(sync$", itemID, "))
# lapply(input$", itemID, "_filter$filterSettings, function(x) )
for(flt in input$", itemID, "_filter$filterSettings){
colnumb = flt$column %>% substr(5, nchar(flt$column)) %>% as.integer
colname = nms[colnumb]
if(!is.na(colname)){sync$", itemID, "_column.filter[[colname]] = chif(is.empty(flt$value), NULL, flt$value)}
# debug(check)
# check('FOB1', colnumb, colname, input$", itemID, "_filter$filterSettings, flt, sync$", itemID, "_column.filter)
}
# report$", itemID, "_column.filter = sync$", itemID, "_column.filter
})
")
}
# Server 2 Client: FOB2
D3TableFilter.observer.filter.S2C.R = function(itemID){
paste0("
if(is.null(sync$", itemID, "_column.filter)){sync$", itemID, "_column.filter = items[['", itemID, "']]$config$column.filter}
isolate({
for(flt in input$", itemID, "_filter$filterSettings){
nms = c('rownames', colnames(sync$", itemID, "))
colnumb = flt$column %>% substr(5, nchar(flt$column)) %>% as.integer
colname = nms[colnumb]
colnumb = colnumb - 1
if (colname %in% names(sync$", itemID, "_column.filter)){
if (!identical(flt$value, sync$", itemID, "_column.filter[[colname]])){
# set filter
setFilter(session, tbl = '", itemID, "', col = 'col_' %++% colnumb, filterString = sync$", itemID, "_column.filter[[colname]], doFilter = TRUE);
}
# else {do nothing}
} else {
setFilter(session, tbl = '", itemID, "', col = 'col_' %++% colnumb, filterString = '', doFilter = TRUE);
}
# debug(check)
# check('FOB2', y = input$", itemID, "_filter$filterSettings, z = colnumb, t = colname, r = flt, s = sync$", itemID, "_column.filter)
# report$", itemID, "_column.filter = sync$", itemID, "_column.filter
}
})
")
}
# client to server: sob1
D3TableFilter.observer.selected.C2S.R = function(itemID){
paste0("
if(is.null(input$", itemID, "_select)){return(NULL)}
isolate({
sync$", itemID, "_selected = input$", itemID, "_select
report$", itemID, "_selected = sync$", itemID, "_selected
})
")
}
# server 2 client: sob2
D3TableFilter.observer.selected.S2C.R = function(itemID){
paste0("
if(is.null(sync$", itemID, "_selected)){sync$", itemID, "_selected = items[['", itemID, "']]$config$selected}
isolate({
if(is.null(report$", itemID, "_selected)){report$", itemID, "_selected = items[['", itemID, "']]$config$selected}
if(is.null(sync$", itemID, "_row.color)){sync$", itemID, "_row.color = items[['", itemID, "']]$config$row.color}
sel = sync$", itemID, "_selected %-% report$", itemID, "_selected
desel = report$", itemID, "_selected %-% sync$", itemID, "_selected
for (i in sel){ setRowClass(session, tbl = '", itemID, "', row = i, class = items['", itemID, "']$config$selection.color)}
for (i in desel){setRowClass(session, tbl = '", itemID, "', row = i, class = chif(sync$", itemID, "_row.color[i] == items['", itemID, "']$config$selection.color, '', items[['", itemID, "']]$config$row.color[i]))}
report$", itemID, "_selected = sync$", itemID, "_selected
})
")
}
# server 2 client: for row color: cob2
D3TableFilter.observer.color.S2C.R = function(itemID){
paste0("
if(is.null(sync$", itemID, "_row.color)){sync$", itemID, "_row.color = items[['", itemID, "']]$config$row.color}
isolate({
# debug(check)
# check(x = 'cob2', y = sync$", itemID, "_row.color, z = report$", itemID, "_row.color, t = sync$", itemID, ")
if(is.null(report$", itemID, "_row.color)){report$", itemID, "_row.color = items[['", itemID, "']]$config$row.color}
w = which(sync$", itemID, "_row.color != report$", itemID, "_row.color)
for (i in w){setRowClass(session, tbl = '", itemID, "', row = i, class = sync$", itemID, "_row.color[i])}
report$", itemID, "_row.color = sync$", itemID, "_row.color
})
")
}
# server to client: for table contents: tob2
D3TableFilter.observer.table.S2C.R = function(itemID){
paste0("
if(is.null(sync$", itemID, ")){sync$", itemID, " = items[['", itemID, "']]$data}
isolate({
if(is.null(report$", itemID, ")){report$", itemID, " = items[['", itemID, "']]$data}
# debug(check)
# check(x = 'tob2', y = report$", itemID, ", z = sync$", itemID, ")
for (i in sequence(ncol(sync$", itemID, "))){
w = which(sync$", itemID, "[,i] != report$", itemID, "[,i])
for (j in w) {
setCellValue(session, tbl = '", itemID, "', row = j, col = i, value = sync$", itemID, "[j,i], feedback = TRUE)
report$", itemID, "[j,i] = sync$", itemID, "[j,i]
}
}
rnew = rownames(sync$", itemID, ")
rold = rownames(report$", itemID, ")
w = which(rnew != rold)
for (j in w) {
setCellValue(session, tbl = '", itemID, "', row = j, col = 0, value = rnew[j], feedback = TRUE)
rownames(report$", itemID, ")[j] = rnew[j]
}
})
")
}
D3TableFilter.service = function(itemID){
paste0("items[['", itemID, "']]$data %>% D3TableFilter.table(config = items[['", itemID, "']]$config, width = items[['", itemID, "']]$width, height = items[['", itemID, "']]$height)")
}
### interactive/jscripts.R ------------------------
#### dimple:
dimple.js = function(field_name = 'group'){
S1 =
'<script>
myChart.axes.filter(function(ax){return ax.position == "x"})[0].titleShape.text(opts.xlab)
myChart.axes.filter(function(ax){return ax.position == "y"})[0].titleShape.text(opts.ylab)
myChart.legends = [];
svg.selectAll("title_text")
.data(["'
S2 = ''
S3 =
'"])
.enter()
.append("text")
.attr("x", 499)
.attr("y", function (d, i) { return 90 + i * 14; })
.style("font-family", "sans-serif")
.style("font-size", "10px")
.style("color", "Black")
.text(function (d) { return d; });
var filterValues = dimple.getUniqueValues(data, "'
S5 = '");
l.shapes.selectAll("rect")
.on("click", function (e) {
var hide = false;
var newFilters = [];
filterValues.forEach(function (f) {
if (f === e.aggField.slice(-1)[0]) {
hide = true;
} else {
newFilters.push(f);
}
});
if (hide) {
d3.select(this).style("opacity", 0.2);
} else {
newFilters.push(e.aggField.slice(-1)[0]);
d3.select(this).style("opacity", 0.8);
}
filterValues = newFilters;
myChart.data = dimple.filterData(data, "'
S6 = '", filterValues);
myChart.draw(800);
myChart.axes.filter(function(ax){return ax.position == "x"})[0].titleShape.text(opts.xlab)
myChart.axes.filter(function(ax){return ax.position == "y"})[0].titleShape.text(opts.ylab)
});
</script>'
return(paste0(S1,S2, S3, field_name, S5, field_name, S6))
}
#### D3TableFilter:
D3TableFilter.color.single.js = function(col){
JS('function colorScale(obj, i){
return "' %++% col %++% '"}')
}
D3TableFilter.color.nominal.js = function(domain, range){
range %<>% vect.extend(length(domain))
dp = paste(domain, range) %>% duplicated
domain = domain[!dp]
range = range[!dp]
ss = 'function colorScale(obj,i){
var color = d3.scale.ordinal().domain([' %++%
paste('"' %++% domain %++% '"', collapse = ',') %++% ']).range([' %++%
paste('"' %++% range %++% '"', collapse = ',') %++% ']);
return color(i);}'
return(JS(ss))
}
D3TableFilter.color.numeric.js = function(domain, range){
N = length(range)
q = domain %>% quantile(probs = (0:(N-1))/(N-1))
ss = 'function colorScale(obj,i){
var color = d3.scale.linear().domain([' %++%
paste(q, collapse = ',') %++% ']).range([' %++%
paste('"' %++% range %++% '"', collapse = ',') %++% ']);
return color(i);}'
return(JS(ss))
}
D3TableFilter.shape.bar.js = function(format = '.1f'){
JS(paste0('function makeGraph(selection){
// find out wich table and column
var regex = /(col_\\d+)/;
var col = regex.exec(this[0][0].className)[0];
var regex = /tbl_(\\S+)/;
var tbl = regex.exec(this[0][0].className)[1];
var innerWidth = 117;
var innerHeight = 14;
// create a scaling function
var max = colMax(tbl, col);
var min = colMin(tbl, col);
var wScale = d3.scale.linear()
.domain([0, max])
.range([0, innerWidth]);
// text formatting function
var textformat = d3.format("', format, '");
// column has been initialized before, update function
if(tbl + "_" + col + "_init" in window) {
var sel = selection.selectAll("svg")
.selectAll("rect")
.transition().duration(500)
.attr("width", function(d) { return wScale(d.value)});
var txt = selection
.selectAll("text")
.text(function(d) { return textformat(d.value); });
return(null);
}
// can remove padding here, but still cant position text and box independently
this.style("padding", "5px 5px 5px 5px");
// remove text. will be added back later
selection.text(null);
var svg = selection.append("svg")
.style("position", "absolute")
.attr("width", innerWidth)
.attr("height", innerHeight);
var box = svg.append("rect")
.style("fill", "lightblue")
.attr("stroke","none")
.attr("height", innerHeight)
.attr("width", min)
.transition().duration(500)
.attr("width", function(d) { return wScale(d.value); });
// format number and add text back
var textdiv = selection.append("div");
textdiv.style("position", "relative")
.attr("align", "right");
textdiv.append("text")
.text(function(d) { return textformat(d.value); });
window[tbl + "_" + col + "_init"] = true;
}'))
}
D3TableFilter.shape.bubble.js = function(){
JS(paste0('function makeGraph(selection){
// find out wich table and column
var regex = /(col_\\d+)/;
var col = regex.exec(this[0][0].className)[0];
var regex = /tbl_(\\S+)/;
var tbl = regex.exec(this[0][0].className)[1];
// create a scaling function
var domain = colExtent(tbl, col);
var rScale = d3.scale.sqrt()
.domain(domain)
.range([8, 14]);
// column has been initialized before, update function
if(tbl + "_" + col + "_init" in window) {
var sel = selection.selectAll("svg")
.selectAll("circle")
.transition().duration(500)
.attr("r", function(d) { return rScale(d.value)});
return(null);
}
// remove text. will be added later within the svg
selection.text(null)
// create svg element
var svg = selection.append("svg")
.attr("width", 28)
.attr("height", 28);
// create a circle with a radius ("r") scaled to the
// value of the cell ("d.value")
var circle = svg.append("g")
.append("circle").attr("class", "circle")
.attr("cx", 14)
.attr("cy", 14)
.style("fill", "orange")
.attr("stroke","none")
.attr("r", domain[0])
.transition().duration(400)
.attr("r", function(d) { return rScale(d.value); });
// place the text within the circle
var text = svg.append("g")
.append("text").attr("class", "text")
.style("fill", "black")
.attr("x", 14)
.attr("y", 14)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function (d) { return d.value; });
window[tbl + "_" + col + "_init"] = true;
}'))
}
D3TableFilter.font.bold.js = JS('function makeGraph(selection){selection.style("font-weight", "bold")}')
D3TableFilter.font.js = function(weight = 'bold', side = 'right', format = '.1f'){
sidestr = chif(is.null(side) , '', paste0('.classed("text-', side, '", true)'))
weightstr = chif(is.null(weight), '', paste0('.style("font-weight", "', weight ,'")'))
formatstr2 = chif(is.null(format), '', paste0('.text(function(d) { return textformat(d.value); })'))
formatstr1 = chif(is.null(format), '', paste0('var textformat = d3.format("', format, '");'))
JS(paste0('function makeGraph(selection){', formatstr1, 'selection', sidestr , weightstr, formatstr2, ';}'))
}
| /script/visualization/htmlwidgets/D3TableFilter/interactive/rscripts.R | no_license | genpack/tutorials | R | false | false | 23,145 | r |
### interactive/rscripts.R ------------------------
# Header
# Filename: rscripts.R
# Description: Contains functions generating various R scripts.
# Author: Nima Ramezani Taghiabadi
# Email : nima.ramezani@cba.com.au
# Start Date: 23 May 2017
# Last Revision: 23 May 2017
# Version: 0.0.1
#
# Version History:
# Version Date Action
# ----------------------------------
# 0.0.1 23 May 2017 Initial issue for D3TableFilter syncing observers
# for a output object of type D3TableFilter, D3TableFilter generates an input
# "<chartID>_edit"
# this observer does a simple input validation and sends a confirm or reject message after each edit.
# Only server to client!
D3TableFilter.observer.column.footer.R = function(itemID){paste0("
nms = c('rownames', colnames(sync$", itemID, "))
for (col in names(sync$", itemID, "_column.footer)){
wch = which(nms == col) - 1
if (inherits(sync$", itemID, "_column.footer[[col]], 'function')){val = sapply(list(sync$", itemID, "[report$", itemID, "_filtered, col]), sync$", itemID, "_column.footer[[col]])}
else {val = sync$", itemID, "_column.footer[[col]] %>% as.character}
for (cn in wch){if(!is.empty(val)){setFootCellValue(session, tbl = '", itemID, "', row = 1, col = cn, value = val)}}
}
")}
# server to client
D3TableFilter.observer.column.editable.R = function(itemID){paste0("
#debug(check)
#check(x = sync$", itemID, "_column.editable)
enacols = sync$", itemID, "_column.editable %>% unlist %>% coerce('logical') %>% which %>% names %>% intersect(c('rownames', colnames(sync$", itemID, ")))
discols = c('rownames', colnames(sync$", itemID, ")) %-% enacols
for(col in enacols){
if (col == 'rownames'){
enableEdit(session, '", itemID, "', 'col_0')
} else {
w = which(names(sync$", itemID, ") == col)
enableEdit(session, '", itemID, "', 'col_' %++% w);
}
}
for(col in discols){
if (col == 'rownames'){
disableEdit(session, '", itemID, "', 'col_0')
} else {
w = which(names(sync$", itemID, ") == col)
disableEdit(session, '", itemID, "', 'col_' %++% w);
}
}
")
}
# client to server:
D3TableFilter.observer.edit.R = function(itemID) {paste0("
if(is.null(input$", itemID, "_edit)) return(NULL);
edit <- input$", itemID, "_edit;
isolate({
# need isolate, otherwise this observer would run twice
# for each edit
id <- edit$id;
row <- as.integer(edit$row);
col <- as.integer(edit$col);
val <- edit$val;
nms <- colnames(sync$", itemID, ")
if(col == 0) {
oldval <- rownames(sync$", itemID, ")[row];
cellClass = 'character'
fltr = items[['", itemID, "']]$filter[['rownames']]}
else {
oldval <- sync$", itemID, "[row, col];
fltr = items[['", itemID, "']]$filter[[nms[col]]]
cellClass = class(sync$", itemID, "[, col])[1]
}
val0 = val
val = try(coerce(val, cellClass), silent = T)
accept = inherits(val, cellClass) & !is.empty(val)
if(accept & inherits(fltr, 'list') & !is.empty(fltr)){
accept = parse(text = filter2R(fltr)) %>% eval
}
if (accept){
if(col == 0) {
rownames(sync$", itemID, ")[row] <- val;
rownames(report$", itemID, ")[row] <- val;
} else {
shp = items[['", itemID, "']]$config$column.shape[[nms[col]]]
if (!is.null(shp)){
if(shp == 'radioButtons'){
sync$", itemID, "[, col] <- FALSE;
report$", itemID, "[, col] <- FALSE;
}
}
sync$", itemID, "[row, col] <- val;
report$", itemID, "[row, col] <- val;
}
# confirm edits
confirmEdit(session, tbl = '", itemID, "', row = row, col = col, id = id, value = val);
report$", itemID, "_lastEdits['Success', 'Row'] <- row;
report$", itemID, "_lastEdits['Success', 'Column'] <- col;
report$", itemID, "_lastEdits['Success', 'Value'] <- val;
} else {
rejectEdit(session, tbl = '", itemID, "', row = row, col = col, id = id, value = oldval);
report$", itemID, "_lastEdits['Fail', 'Row'] <- row;
report$", itemID, "_lastEdits['Fail', 'Column'] <- col;
report$", itemID, "_lastEdits['Fail', 'Value'] <- val0;
}
})
")}
# Use it later for creating the default footer:
# footer = list('Mean', object[[i]] %>% colMeans %>% as.matrix %>% t) %>% as.data.frame
# names(footer) = c('Rownames', colnames(object[[i]]))
# Client 2 Server: FOB1
D3TableFilter.observer.filter.C2S.R = function(itemID){
paste0("
if(is.null(input$", itemID, "_filter)){return(NULL)}
isolate({
report$", itemID, "_filtered <- unlist(input$", itemID, "_filter$validRows);
sync$", itemID, "_column.filter = list()
nms = c('rownames', colnames(sync$", itemID, "))
# lapply(input$", itemID, "_filter$filterSettings, function(x) )
for(flt in input$", itemID, "_filter$filterSettings){
colnumb = flt$column %>% substr(5, nchar(flt$column)) %>% as.integer
colname = nms[colnumb]
if(!is.na(colname)){sync$", itemID, "_column.filter[[colname]] = chif(is.empty(flt$value), NULL, flt$value)}
# debug(check)
# check('FOB1', colnumb, colname, input$", itemID, "_filter$filterSettings, flt, sync$", itemID, "_column.filter)
}
# report$", itemID, "_column.filter = sync$", itemID, "_column.filter
})
")
}
# Server 2 Client: FOB2
D3TableFilter.observer.filter.S2C.R = function(itemID){
paste0("
if(is.null(sync$", itemID, "_column.filter)){sync$", itemID, "_column.filter = items[['", itemID, "']]$config$column.filter}
isolate({
for(flt in input$", itemID, "_filter$filterSettings){
nms = c('rownames', colnames(sync$", itemID, "))
colnumb = flt$column %>% substr(5, nchar(flt$column)) %>% as.integer
colname = nms[colnumb]
colnumb = colnumb - 1
if (colname %in% names(sync$", itemID, "_column.filter)){
if (!identical(flt$value, sync$", itemID, "_column.filter[[colname]])){
# set filter
setFilter(session, tbl = '", itemID, "', col = 'col_' %++% colnumb, filterString = sync$", itemID, "_column.filter[[colname]], doFilter = TRUE);
}
# else {do nothing}
} else {
setFilter(session, tbl = '", itemID, "', col = 'col_' %++% colnumb, filterString = '', doFilter = TRUE);
}
# debug(check)
# check('FOB2', y = input$", itemID, "_filter$filterSettings, z = colnumb, t = colname, r = flt, s = sync$", itemID, "_column.filter)
# report$", itemID, "_column.filter = sync$", itemID, "_column.filter
}
})
")
}
# client to server: sob1
D3TableFilter.observer.selected.C2S.R = function(itemID){
paste0("
if(is.null(input$", itemID, "_select)){return(NULL)}
isolate({
sync$", itemID, "_selected = input$", itemID, "_select
report$", itemID, "_selected = sync$", itemID, "_selected
})
")
}
# server 2 client: sob2
D3TableFilter.observer.selected.S2C.R = function(itemID){
paste0("
if(is.null(sync$", itemID, "_selected)){sync$", itemID, "_selected = items[['", itemID, "']]$config$selected}
isolate({
if(is.null(report$", itemID, "_selected)){report$", itemID, "_selected = items[['", itemID, "']]$config$selected}
if(is.null(sync$", itemID, "_row.color)){sync$", itemID, "_row.color = items[['", itemID, "']]$config$row.color}
sel = sync$", itemID, "_selected %-% report$", itemID, "_selected
desel = report$", itemID, "_selected %-% sync$", itemID, "_selected
for (i in sel){ setRowClass(session, tbl = '", itemID, "', row = i, class = items['", itemID, "']$config$selection.color)}
for (i in desel){setRowClass(session, tbl = '", itemID, "', row = i, class = chif(sync$", itemID, "_row.color[i] == items['", itemID, "']$config$selection.color, '', items[['", itemID, "']]$config$row.color[i]))}
report$", itemID, "_selected = sync$", itemID, "_selected
})
")
}
# server 2 client: for row color: cob2
D3TableFilter.observer.color.S2C.R = function(itemID){
paste0("
if(is.null(sync$", itemID, "_row.color)){sync$", itemID, "_row.color = items[['", itemID, "']]$config$row.color}
isolate({
# debug(check)
# check(x = 'cob2', y = sync$", itemID, "_row.color, z = report$", itemID, "_row.color, t = sync$", itemID, ")
if(is.null(report$", itemID, "_row.color)){report$", itemID, "_row.color = items[['", itemID, "']]$config$row.color}
w = which(sync$", itemID, "_row.color != report$", itemID, "_row.color)
for (i in w){setRowClass(session, tbl = '", itemID, "', row = i, class = sync$", itemID, "_row.color[i])}
report$", itemID, "_row.color = sync$", itemID, "_row.color
})
")
}
# server to client: for table contents: tob2
D3TableFilter.observer.table.S2C.R = function(itemID){
paste0("
if(is.null(sync$", itemID, ")){sync$", itemID, " = items[['", itemID, "']]$data}
isolate({
if(is.null(report$", itemID, ")){report$", itemID, " = items[['", itemID, "']]$data}
# debug(check)
# check(x = 'tob2', y = report$", itemID, ", z = sync$", itemID, ")
for (i in sequence(ncol(sync$", itemID, "))){
w = which(sync$", itemID, "[,i] != report$", itemID, "[,i])
for (j in w) {
setCellValue(session, tbl = '", itemID, "', row = j, col = i, value = sync$", itemID, "[j,i], feedback = TRUE)
report$", itemID, "[j,i] = sync$", itemID, "[j,i]
}
}
rnew = rownames(sync$", itemID, ")
rold = rownames(report$", itemID, ")
w = which(rnew != rold)
for (j in w) {
setCellValue(session, tbl = '", itemID, "', row = j, col = 0, value = rnew[j], feedback = TRUE)
rownames(report$", itemID, ")[j] = rnew[j]
}
})
")
}
D3TableFilter.service = function(itemID){
paste0("items[['", itemID, "']]$data %>% D3TableFilter.table(config = items[['", itemID, "']]$config, width = items[['", itemID, "']]$width, height = items[['", itemID, "']]$height)")
}
### interactive/jscripts.R ------------------------
#### dimple:
dimple.js = function(field_name = 'group'){
S1 =
'<script>
myChart.axes.filter(function(ax){return ax.position == "x"})[0].titleShape.text(opts.xlab)
myChart.axes.filter(function(ax){return ax.position == "y"})[0].titleShape.text(opts.ylab)
myChart.legends = [];
svg.selectAll("title_text")
.data(["'
S2 = ''
S3 =
'"])
.enter()
.append("text")
.attr("x", 499)
.attr("y", function (d, i) { return 90 + i * 14; })
.style("font-family", "sans-serif")
.style("font-size", "10px")
.style("color", "Black")
.text(function (d) { return d; });
var filterValues = dimple.getUniqueValues(data, "'
S5 = '");
l.shapes.selectAll("rect")
.on("click", function (e) {
var hide = false;
var newFilters = [];
filterValues.forEach(function (f) {
if (f === e.aggField.slice(-1)[0]) {
hide = true;
} else {
newFilters.push(f);
}
});
if (hide) {
d3.select(this).style("opacity", 0.2);
} else {
newFilters.push(e.aggField.slice(-1)[0]);
d3.select(this).style("opacity", 0.8);
}
filterValues = newFilters;
myChart.data = dimple.filterData(data, "'
S6 = '", filterValues);
myChart.draw(800);
myChart.axes.filter(function(ax){return ax.position == "x"})[0].titleShape.text(opts.xlab)
myChart.axes.filter(function(ax){return ax.position == "y"})[0].titleShape.text(opts.ylab)
});
</script>'
return(paste0(S1,S2, S3, field_name, S5, field_name, S6))
}
#### D3TableFilter:
D3TableFilter.color.single.js = function(col){
JS('function colorScale(obj, i){
return "' %++% col %++% '"}')
}
D3TableFilter.color.nominal.js = function(domain, range){
range %<>% vect.extend(length(domain))
dp = paste(domain, range) %>% duplicated
domain = domain[!dp]
range = range[!dp]
ss = 'function colorScale(obj,i){
var color = d3.scale.ordinal().domain([' %++%
paste('"' %++% domain %++% '"', collapse = ',') %++% ']).range([' %++%
paste('"' %++% range %++% '"', collapse = ',') %++% ']);
return color(i);}'
return(JS(ss))
}
D3TableFilter.color.numeric.js = function(domain, range){
N = length(range)
q = domain %>% quantile(probs = (0:(N-1))/(N-1))
ss = 'function colorScale(obj,i){
var color = d3.scale.linear().domain([' %++%
paste(q, collapse = ',') %++% ']).range([' %++%
paste('"' %++% range %++% '"', collapse = ',') %++% ']);
return color(i);}'
return(JS(ss))
}
D3TableFilter.shape.bar.js = function(format = '.1f'){
JS(paste0('function makeGraph(selection){
// find out wich table and column
var regex = /(col_\\d+)/;
var col = regex.exec(this[0][0].className)[0];
var regex = /tbl_(\\S+)/;
var tbl = regex.exec(this[0][0].className)[1];
var innerWidth = 117;
var innerHeight = 14;
// create a scaling function
var max = colMax(tbl, col);
var min = colMin(tbl, col);
var wScale = d3.scale.linear()
.domain([0, max])
.range([0, innerWidth]);
// text formatting function
var textformat = d3.format("', format, '");
// column has been initialized before, update function
if(tbl + "_" + col + "_init" in window) {
var sel = selection.selectAll("svg")
.selectAll("rect")
.transition().duration(500)
.attr("width", function(d) { return wScale(d.value)});
var txt = selection
.selectAll("text")
.text(function(d) { return textformat(d.value); });
return(null);
}
// can remove padding here, but still cant position text and box independently
this.style("padding", "5px 5px 5px 5px");
// remove text. will be added back later
selection.text(null);
var svg = selection.append("svg")
.style("position", "absolute")
.attr("width", innerWidth)
.attr("height", innerHeight);
var box = svg.append("rect")
.style("fill", "lightblue")
.attr("stroke","none")
.attr("height", innerHeight)
.attr("width", min)
.transition().duration(500)
.attr("width", function(d) { return wScale(d.value); });
// format number and add text back
var textdiv = selection.append("div");
textdiv.style("position", "relative")
.attr("align", "right");
textdiv.append("text")
.text(function(d) { return textformat(d.value); });
window[tbl + "_" + col + "_init"] = true;
}'))
}
D3TableFilter.shape.bubble.js = function(){
JS(paste0('function makeGraph(selection){
// find out wich table and column
var regex = /(col_\\d+)/;
var col = regex.exec(this[0][0].className)[0];
var regex = /tbl_(\\S+)/;
var tbl = regex.exec(this[0][0].className)[1];
// create a scaling function
var domain = colExtent(tbl, col);
var rScale = d3.scale.sqrt()
.domain(domain)
.range([8, 14]);
// column has been initialized before, update function
if(tbl + "_" + col + "_init" in window) {
var sel = selection.selectAll("svg")
.selectAll("circle")
.transition().duration(500)
.attr("r", function(d) { return rScale(d.value)});
return(null);
}
// remove text. will be added later within the svg
selection.text(null)
// create svg element
var svg = selection.append("svg")
.attr("width", 28)
.attr("height", 28);
// create a circle with a radius ("r") scaled to the
// value of the cell ("d.value")
var circle = svg.append("g")
.append("circle").attr("class", "circle")
.attr("cx", 14)
.attr("cy", 14)
.style("fill", "orange")
.attr("stroke","none")
.attr("r", domain[0])
.transition().duration(400)
.attr("r", function(d) { return rScale(d.value); });
// place the text within the circle
var text = svg.append("g")
.append("text").attr("class", "text")
.style("fill", "black")
.attr("x", 14)
.attr("y", 14)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function (d) { return d.value; });
window[tbl + "_" + col + "_init"] = true;
}'))
}
D3TableFilter.font.bold.js = JS('function makeGraph(selection){selection.style("font-weight", "bold")}')
D3TableFilter.font.js = function(weight = 'bold', side = 'right', format = '.1f'){
sidestr = chif(is.null(side) , '', paste0('.classed("text-', side, '", true)'))
weightstr = chif(is.null(weight), '', paste0('.style("font-weight", "', weight ,'")'))
formatstr2 = chif(is.null(format), '', paste0('.text(function(d) { return textformat(d.value); })'))
formatstr1 = chif(is.null(format), '', paste0('var textformat = d3.format("', format, '");'))
JS(paste0('function makeGraph(selection){', formatstr1, 'selection', sidestr , weightstr, formatstr2, ';}'))
}
|
#' Create the package.json file for npm
#'
#' @param app_name name of your app. This is what end-users will see/call an app
#' @param description short description of app
#' @param app_root_path app_root_path to where package.json will be written
#' @param repository purely for info- does the shiny app live in a repository (e.g. GitHub)
#' @param author author of the app
#' @param license license of the App. Not the full license, only the title (e.g. MIT, or GPLv3)
#' @param semantic_version semantic version of app see https://semver.org/ for more information on versioning
#' @param copyright_year year of copyright
#' @param copyright_name copyright-holder's name
#' @param deps is to allow testing with testthat
#' @param website website of app or company
#'
#' @return outputs package.json file with user-input modifications
#' @export
#'
create_package_json <- function(app_name = "MyApp",
description = "description",
semantic_version = "0.0.0",
app_root_path = NULL,
repository = "",
author = "",
copyright_year = "",
copyright_name = "",
website = "",
license = "",
deps = NULL){
# null is to allow for testing
if (is.null(deps)) {
# get package.json dependencies
# [-1] remove open { necessary for automated dependency checker
deps <- readLines(system.file("template/package.json", package = "electricShine"))[-1]
deps <- paste0(deps, collapse = "\n")
}
file <- glue::glue(
'
{
"name": "<<app_name>>",
"productName": "<<app_name>>",
"description": "<<description>>",
"version": "<<semantic_version>>",
"private": true,
"author": "<<author>>",
"copyright": "<<copyright_year>> <<copyright_name>>",
"license": "<<license>>",
"homepage": "<<website>>",
"main": "app/background.js",
"build": {
"appId": "com.<<app_name>>",
"files": [
"app/**/*",
"node_modules/**/*",
"package.json"
],
"directories": {
"buildResources": "resources"
},
"publish": null,
"asar": false
},
"scripts": {
"postinstall": "electron-builder install-app-deps",
"preunit": "webpack --config=build/webpack.unit.config.js --env=test --display=none",
"unit": "electron-mocha temp/specs.js --renderer --require source-map-support/register",
"pree2e": "webpack --config=build/webpack.app.config.js --env=test --display=none && webpack --config=build/webpack.e2e.config.js --env=test --display=none",
"e2e": "mocha temp/e2e.js --require source-map-support/register",
"test": "npm run unit && npm run e2e",
"start": "node build/start.js",
"release": "npm test && webpack --config=build/webpack.app.config.js --env=production && electron-builder"
},
<<deps>>
', .open = "<<", .close = ">>")
electricShine::write_text(text = file,
filename = "package.json",
path = app_root_path)
}
| /R/create_package_json.R | permissive | chasemc/electricShine | R | false | false | 3,128 | r |
#' Create the package.json file for npm
#'
#' @param app_name name of your app. This is what end-users will see/call an app
#' @param description short description of app
#' @param app_root_path app_root_path to where package.json will be written
#' @param repository purely for info- does the shiny app live in a repository (e.g. GitHub)
#' @param author author of the app
#' @param license license of the App. Not the full license, only the title (e.g. MIT, or GPLv3)
#' @param semantic_version semantic version of app see https://semver.org/ for more information on versioning
#' @param copyright_year year of copyright
#' @param copyright_name copyright-holder's name
#' @param deps is to allow testing with testthat
#' @param website website of app or company
#'
#' @return outputs package.json file with user-input modifications
#' @export
#'
create_package_json <- function(app_name = "MyApp",
description = "description",
semantic_version = "0.0.0",
app_root_path = NULL,
repository = "",
author = "",
copyright_year = "",
copyright_name = "",
website = "",
license = "",
deps = NULL){
# null is to allow for testing
if (is.null(deps)) {
# get package.json dependencies
# [-1] remove open { necessary for automated dependency checker
deps <- readLines(system.file("template/package.json", package = "electricShine"))[-1]
deps <- paste0(deps, collapse = "\n")
}
file <- glue::glue(
'
{
"name": "<<app_name>>",
"productName": "<<app_name>>",
"description": "<<description>>",
"version": "<<semantic_version>>",
"private": true,
"author": "<<author>>",
"copyright": "<<copyright_year>> <<copyright_name>>",
"license": "<<license>>",
"homepage": "<<website>>",
"main": "app/background.js",
"build": {
"appId": "com.<<app_name>>",
"files": [
"app/**/*",
"node_modules/**/*",
"package.json"
],
"directories": {
"buildResources": "resources"
},
"publish": null,
"asar": false
},
"scripts": {
"postinstall": "electron-builder install-app-deps",
"preunit": "webpack --config=build/webpack.unit.config.js --env=test --display=none",
"unit": "electron-mocha temp/specs.js --renderer --require source-map-support/register",
"pree2e": "webpack --config=build/webpack.app.config.js --env=test --display=none && webpack --config=build/webpack.e2e.config.js --env=test --display=none",
"e2e": "mocha temp/e2e.js --require source-map-support/register",
"test": "npm run unit && npm run e2e",
"start": "node build/start.js",
"release": "npm test && webpack --config=build/webpack.app.config.js --env=production && electron-builder"
},
<<deps>>
', .open = "<<", .close = ">>")
electricShine::write_text(text = file,
filename = "package.json",
path = app_root_path)
}
|
#' The application server-side
#'
#' @param input,output,session Internal parameters for {shiny}.
#' DO NOT REMOVE.
#' @import shiny
#' @noRd
app_server <- function( input, output, session ) {
observeEvent(input$dev, {
browser()
})
# Set up ====
main.env <- setMainEnv()
# Gauges =====
# * money ----
output$money_gauge <- renderUI({
div(
class = "filled_gauge",
style = paste0(
"background: linear-gradient(95deg, gold ",
(10+main.env$resources$money)/1.1,
"%, white ",
(10+main.env$resources$money)/1.1,
"%);"
)
)
})
# * quality ----
output$quality_gauge <- renderUI({
div(
class = "filled_gauge",
style = paste0(
"background: linear-gradient(95deg, steelblue ",
(10+main.env$resources$quality)/1.1,
"%, white ",
(10+main.env$resources$quality)/1.1,
"%);"
)
)
})
# * administration ----
output$administration_gauge <- renderUI({
div(
class = "filled_gauge",
style = paste0(
"background: linear-gradient(95deg, blueviolet",
(10+main.env$resources$administration)/1.1,
"%, white ",
(10+main.env$resources$administration)/1.1,
"%);"
)
)
})
# Run game ====
# * Tuto ----
showModal(
ui = modalDialog(
title = "Bienvenue dans SeaClone !",
tagList(
tags$p("Vous voici dans la peau d'un chercheur pour un an. Mois après
mois, vous devrez effectuer les choix nécessaires au bon déroulé
des missions qui sont les vôtres: évaluer les évolutions de la
biodiversité d'une espèce de la faune marine et identifier les
potentielles causes de son altération."),
tags$p("Vous êtes basé à la", tags$b("Station de Biologie Marine de
Concarneau"), icon("microscope"), ". Vous pouvez effectuer vos
observations au large de ", tags$b("l'archipel des Glénans"),
icon("water"), ". En cas de besoin, vous pourrez engager un bureau
d'études à ", tags$b("Port-la-Forêt"), icon("credit-card"), " ou
même financer le stage d'un étudiant de ", tags$b("Quimper"),
icon("graduate-user"), ". Une autre méthode consistera à faire
appel aux plaisanciers de passage à ", tags$b("Bénodet"), icon("anchor"),
" afin de récolter des données dites 'opportunistes'. Enfin, il
ne faut pas hésiter à faire appel à la ", tags$b("bibliographie"),
icon("book-open"), " accumulée sur le sujet qui vous intéresse: ",
tags$b(tags$i("Scomber scombrus"), ", ou maquereau commun."))
),
footer = modalButton("C'est parti !")
)
)
# * Time ----
# browser()
# Event
output$event <- renderText(
"Météo favorable pour la saison."
)
# Months display
# sapply(main.env$time$MONTHS, function(mon) {
# output[[mon]] <- renderUI({
# mon.ind <- match(mon, isolate(main.env$time$MONTHS))
# cur.ind <- match(isolate(main.env$time$month), isolate(main.env$time$MONTHS))
# if(mon.ind < cur.ind)
# return(
# tagList(
# tags$img(src = "/stamp.png", width = "750px", height = "750px")
# )
# )
# else
# return(tagList())
# })
# })
# Time pass
observeEvent(input$`next`, {
})
# Interactions ====
# * Stagiaire ----
observeEvent(input$university, {
showModal(
modalDialog(
title = "Stages",
tagList(
tags$p("Un stage étudiant est l'occasion parfaite pour mutualiser
productivité et formation. Vous vous libérerez du temps et
pourrez vous consacrer davantage à certaines tâches. En
contrepartie, votre ligne budgétaire pourra être durablement
impactée."),
actionButton("recruit_intern", "Stagiaire", icon("plus")),
span(
span(icon("euro-sign"), icon("minus"), style = "color: red"),
span(icon("flask"), icon("plus"), style = "color:green")
)
),
footer = modalButton("Fermer")
)
)
})
# * Plaisanciers ----
observeEvent(input$opportunist_data, {
showModal(
modalDialog(
title = "Plaisanciers",
tagList(
tags$p("De nombreux plaisanciers prendront part à des activités
scientifiques au milieu de leur temps libre. Vous
pouvez également démarcher les pêcheurs en dehors des
saisons touristiques. Cependant, l'assiduité et la rigueur
de chacun est variable."),
actionButton("recruit_tourist", "Plaisancier", icon("plus")),
span(
span(icon("flask"), icon("question"), style = "color:blue")
)
),
footer = modalButton("Fermer")
)
)
})
# * Bureau étude ----
observeEvent(input$private_actor, {
showModal(
modalDialog(
title = "Bureau d'études",
tagList(
tags$p("Les bureaux d'étude de Fouesnant sauront vous apporter une forte
contribution dans vos travaux. Professionnels qualifiés, ils
suivront à la lettre les protocoles que vous leur fournirez et
réaliseront leurs tâches rapidement. Néanmoins, une telle aide
a un coût et n'est pas du goût de tous ..."),
actionButton("recruit_private", "Bureau d'étude", icon("plus")),
span(
span(icon("euro-sign"), icon("minus"), icon("minus"), style = "color: red"),
span(icon("flask"), icon("plus"), icon("plus"), style = "color:green"),
span(icon("landmark"), icon("minus"), icon("minus"), style = "color: red")
)
),
footer = modalButton("Fermer")
)
)
})
# * SBM ----
observeEvent(input$sbm, {
showModal(
modalDialog(
title = "Station de Biologie Marine",
tagList(
tags$p("Voici vos bureaux. Vous pourrez prendre du temps ici afin
d'exploiter les données collectées lors de vos différentes
plongées."),
helpText("Pas d'option disponible tant que vous n'avez pas collecté
de donnée.")
),
footer = modalButton("Fermer")
)
)
})
# * Glenans ----
observeEvent(input$dive_1, {
showModal(
modalDialog(
title = "Site de plongée G8",
size = "l",
tagList(
HTML('<iframe width="560" height="315"
src="https://www.youtube.com/embed/QXFHTW2sxBc?autoplay=1&loop=1"
frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope;
picture-in-picture" allowfullscreen></iframe>')
),
footer = modalButton("Fermer")
)
)
})
observeEvent(input$dive_2, {
showModal(
modalDialog(
title = "Site de plongée I8",
size = "l",
tagList(
HTML('<iframe width="560" height="315"
src="https://www.youtube.com/embed/WDdUWBVd-cE?autoplay=1&loop=1"
frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope;
picture-in-picture" allowfullscreen></iframe>')
),
footer = modalButton("Fermer")
)
)
})
# * Bibliography ----
observeEvent(input$bibliography, {
showModal(
ui = modalDialog(
title = "Bibliographie",
main.env$tree.bibliography,
size = "l",
footer = modalButton("Fermer", icon("book"))
)
)
})
}
| /SeaCloneR/R/server.R | no_license | yvanlebras/OceanHackathonJeumeauNumerique | R | false | false | 7,786 | r | #' The application server-side
#'
#' @param input,output,session Internal parameters for {shiny}.
#' DO NOT REMOVE.
#' @import shiny
#' @noRd
app_server <- function( input, output, session ) {
observeEvent(input$dev, {
browser()
})
# Set up ====
main.env <- setMainEnv()
# Gauges =====
# * money ----
output$money_gauge <- renderUI({
div(
class = "filled_gauge",
style = paste0(
"background: linear-gradient(95deg, gold ",
(10+main.env$resources$money)/1.1,
"%, white ",
(10+main.env$resources$money)/1.1,
"%);"
)
)
})
# * quality ----
output$quality_gauge <- renderUI({
div(
class = "filled_gauge",
style = paste0(
"background: linear-gradient(95deg, steelblue ",
(10+main.env$resources$quality)/1.1,
"%, white ",
(10+main.env$resources$quality)/1.1,
"%);"
)
)
})
# * administration ----
output$administration_gauge <- renderUI({
div(
class = "filled_gauge",
style = paste0(
"background: linear-gradient(95deg, blueviolet",
(10+main.env$resources$administration)/1.1,
"%, white ",
(10+main.env$resources$administration)/1.1,
"%);"
)
)
})
# Run game ====
# * Tuto ----
showModal(
ui = modalDialog(
title = "Bienvenue dans SeaClone !",
tagList(
tags$p("Vous voici dans la peau d'un chercheur pour un an. Mois après
mois, vous devrez effectuer les choix nécessaires au bon déroulé
des missions qui sont les vôtres: évaluer les évolutions de la
biodiversité d'une espèce de la faune marine et identifier les
potentielles causes de son altération."),
tags$p("Vous êtes basé à la", tags$b("Station de Biologie Marine de
Concarneau"), icon("microscope"), ". Vous pouvez effectuer vos
observations au large de ", tags$b("l'archipel des Glénans"),
icon("water"), ". En cas de besoin, vous pourrez engager un bureau
d'études à ", tags$b("Port-la-Forêt"), icon("credit-card"), " ou
même financer le stage d'un étudiant de ", tags$b("Quimper"),
icon("graduate-user"), ". Une autre méthode consistera à faire
appel aux plaisanciers de passage à ", tags$b("Bénodet"), icon("anchor"),
" afin de récolter des données dites 'opportunistes'. Enfin, il
ne faut pas hésiter à faire appel à la ", tags$b("bibliographie"),
icon("book-open"), " accumulée sur le sujet qui vous intéresse: ",
tags$b(tags$i("Scomber scombrus"), ", ou maquereau commun."))
),
footer = modalButton("C'est parti !")
)
)
# * Time ----
# browser()
# Event
output$event <- renderText(
"Météo favorable pour la saison."
)
# Months display
# sapply(main.env$time$MONTHS, function(mon) {
# output[[mon]] <- renderUI({
# mon.ind <- match(mon, isolate(main.env$time$MONTHS))
# cur.ind <- match(isolate(main.env$time$month), isolate(main.env$time$MONTHS))
# if(mon.ind < cur.ind)
# return(
# tagList(
# tags$img(src = "/stamp.png", width = "750px", height = "750px")
# )
# )
# else
# return(tagList())
# })
# })
# Time pass
observeEvent(input$`next`, {
})
# Interactions ====
# * Stagiaire ----
observeEvent(input$university, {
showModal(
modalDialog(
title = "Stages",
tagList(
tags$p("Un stage étudiant est l'occasion parfaite pour mutualiser
productivité et formation. Vous vous libérerez du temps et
pourrez vous consacrer davantage à certaines tâches. En
contrepartie, votre ligne budgétaire pourra être durablement
impactée."),
actionButton("recruit_intern", "Stagiaire", icon("plus")),
span(
span(icon("euro-sign"), icon("minus"), style = "color: red"),
span(icon("flask"), icon("plus"), style = "color:green")
)
),
footer = modalButton("Fermer")
)
)
})
# * Plaisanciers ----
observeEvent(input$opportunist_data, {
showModal(
modalDialog(
title = "Plaisanciers",
tagList(
tags$p("De nombreux plaisanciers prendront part à des activités
scientifiques au milieu de leur temps libre. Vous
pouvez également démarcher les pêcheurs en dehors des
saisons touristiques. Cependant, l'assiduité et la rigueur
de chacun est variable."),
actionButton("recruit_tourist", "Plaisancier", icon("plus")),
span(
span(icon("flask"), icon("question"), style = "color:blue")
)
),
footer = modalButton("Fermer")
)
)
})
# * Bureau étude ----
observeEvent(input$private_actor, {
showModal(
modalDialog(
title = "Bureau d'études",
tagList(
tags$p("Les bureaux d'étude de Fouesnant sauront vous apporter une forte
contribution dans vos travaux. Professionnels qualifiés, ils
suivront à la lettre les protocoles que vous leur fournirez et
réaliseront leurs tâches rapidement. Néanmoins, une telle aide
a un coût et n'est pas du goût de tous ..."),
actionButton("recruit_private", "Bureau d'étude", icon("plus")),
span(
span(icon("euro-sign"), icon("minus"), icon("minus"), style = "color: red"),
span(icon("flask"), icon("plus"), icon("plus"), style = "color:green"),
span(icon("landmark"), icon("minus"), icon("minus"), style = "color: red")
)
),
footer = modalButton("Fermer")
)
)
})
# * SBM ----
observeEvent(input$sbm, {
showModal(
modalDialog(
title = "Station de Biologie Marine",
tagList(
tags$p("Voici vos bureaux. Vous pourrez prendre du temps ici afin
d'exploiter les données collectées lors de vos différentes
plongées."),
helpText("Pas d'option disponible tant que vous n'avez pas collecté
de donnée.")
),
footer = modalButton("Fermer")
)
)
})
# * Glenans ----
observeEvent(input$dive_1, {
showModal(
modalDialog(
title = "Site de plongée G8",
size = "l",
tagList(
HTML('<iframe width="560" height="315"
src="https://www.youtube.com/embed/QXFHTW2sxBc?autoplay=1&loop=1"
frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope;
picture-in-picture" allowfullscreen></iframe>')
),
footer = modalButton("Fermer")
)
)
})
observeEvent(input$dive_2, {
showModal(
modalDialog(
title = "Site de plongée I8",
size = "l",
tagList(
HTML('<iframe width="560" height="315"
src="https://www.youtube.com/embed/WDdUWBVd-cE?autoplay=1&loop=1"
frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope;
picture-in-picture" allowfullscreen></iframe>')
),
footer = modalButton("Fermer")
)
)
})
# * Bibliography ----
observeEvent(input$bibliography, {
showModal(
ui = modalDialog(
title = "Bibliographie",
main.env$tree.bibliography,
size = "l",
footer = modalButton("Fermer", icon("book"))
)
)
})
}
|
/1_Behavioral_barriers_preparation_Sample1.R | no_license | fkeusch01/smartphone_usage_behavior | R | false | false | 17,934 | r | ||
corr <- function(directory, threshold = 0) {
monitors <- complete(directory, 1:332)
ids <- monitors[monitors$nobs > threshold, 1]
return(sapply(
ids,
function(f) {
df <- read.csv(paste(directory, sprintf("%03d.csv", f), sep="/"))
cor(df$sulfate, df$nitrate, use="complete")
}
))
} | /R Programming/Assignment 1/corr.R | no_license | gdmachado/datasciencecoursera | R | false | false | 312 | r | corr <- function(directory, threshold = 0) {
monitors <- complete(directory, 1:332)
ids <- monitors[monitors$nobs > threshold, 1]
return(sapply(
ids,
function(f) {
df <- read.csv(paste(directory, sprintf("%03d.csv", f), sep="/"))
cor(df$sulfate, df$nitrate, use="complete")
}
))
} |
#1)
# Loading the dataset.. I have putted it into a folder called "datasets"
dataset <- read.csv('http://www.mghassany.com/MLcourse/datasets/Social_Network_Ads.csv')
# Describing and Exploring the dataset
str(dataset) # to show the structure of the dataset.
summary(dataset) # will show some statistics of every column.
# Remark what it shows when the column is a numerical or categorical variable.
# Remark that it has no sense for the variable User.ID
boxplot(Age ~ Purchased, data=dataset, col = "blue", main="Boxplot Age ~ Purchased")
# You know what is a boxplot right? I will let you interpret it.
boxplot(EstimatedSalary ~ Purchased, data=dataset,col = "red",
main="Boxplot EstimatedSalary ~ Purchased")
# Another boxplot
aov(EstimatedSalary ~Purchased, data=dataset)
# Anova test, but we need to show the summary of
# it in order to see the p-value and to interpret.
summary(aov(EstimatedSalary ~Purchased, data=dataset))
# What do you conclude ?
# Now another anova test for the variable Age
summary(aov(Age ~Purchased, data=dataset))
# There is a categorical variable in the dataset, which is Gender.
# Of course we cannot show a boxplot of Gender and Purchased.
# But we can show a table, or a mosaic plot, both tell the same thing.
table(dataset$Gender,dataset$Purchased)
# Remark for the function table(), that
# in lines we have the first argument, and in columns we have the second argument.
# Don't forget this when you use table() to show a confusion matrix!
mosaicplot(~ Purchased + Gender, data=dataset,
main = "MosaicPlot of two categorical variables: Puchased & Gender",
color = 2:3, las = 1)
# since these 2 variables are categorical, we can apply
# a Chi-square test. The null hypothesis is the independance between
# these variables. You will notice that p-value = 0.4562 which is higher than 0.5
# so we cannot reject the null hypothesis.
# conclusion: there is no dependance between Gender and Purchased (who
# said that women buy more than men? hah!)
chisq.test(dataset$Purchased, dataset$Gender)
# Let's say we want to remove the first two columns as we are not going to use them.
# But, we can in fact use a categorical variable as a predictor in logistic regression.
# It will treat it the same way as in regression. Check Appendix C.
# Try it by yourself if you would like to.
dataset = dataset[3:5]
str(dataset) # show the new structure of dataset
# splitting the dataset into training and testing sets
library(caTools)
set.seed(123) # CHANGE THE VALUE OF SEED. PUT YOUR STUDENT'S NUMBER INSTEAD OF 123.
split = sample.split(dataset$Purchased, SplitRatio = 0.75)
training_set = subset(dataset, split == TRUE)
test_set = subset(dataset, split == FALSE)
# scaling
# So here, we have two continuous predictors, Age and EstimatedSalary.
# There is a very big difference in their scales (units).
# That's why we scale them. But it is not always necessary.
training_set[-3] <- scale(training_set[-3]) #only first two columns
test_set[-3] <- scale(test_set[-3])
# Note that, we replace the columns of Age and EstimatedSalary in the training and
# test sets but their scaled versions. I noticed in a lot of reports that you scaled
# but you did not do the replacing.
# Note too that if you do it column by column you will have a problem because
# it will replace the column by a matrix, you need to retransform it to a vector then.
# Last note, to call the columns Age and EstimatedSalary we can it like I did or
# training_set[c(1,2)] or training_set[,c(1,2)] or training_set[,c("Age","EstimatedSalary")]
# logistic regression
classifier.logreg <- glm(Purchased ~ Age + EstimatedSalary , family = binomial, data=training_set)
classifier.logreg
summary(classifier.logreg)
# prediction
pred.glm = predict(classifier.logreg, newdata = test_set[,-3], type="response")
# Do not forget to put type response.
# By the way, you know what you get when you do not put it, right?
# Now let's assign observations to classes with respect to the probabilities
pred.glm_0_1 = ifelse(pred.glm >= 0.5, 1,0)
# I created a new vector, because we need the probabilities later for the ROC curve.
# show some values of the vectors
head(pred.glm)
head(pred.glm_0_1)
# confusion matrix
cm = table(test_set[,3], pred.glm_0_1)
cm
# First line to store it into cm, second line to show the matrix!
# You remember my note about table() function and the order of the arguments?
cm = table(pred.glm_0_1, test_set[,3])
cm
# You can show the confusion matrix in a mosaic plot by the way
mosaicplot(cm,col=sample(1:8,2)) # colors are random between 8 colors.
# ROC
require(ROCR)
score <- prediction(pred.glm,test_set[,3]) # we use the predicted probabilities not the 0 or 1
performance(score,"auc") # y.values
plot(performance(score,"tpr","fpr"),col="green")
abline(0,1,lty=8)
#2)
plot(test_set$EstimatedSalary, test_set$Age)
abline | /Machine Learning (R)/TD4 machine learning.R | no_license | DamienALOUGES/Cours | R | false | false | 5,006 | r | #1)
# Loading the dataset.. I have putted it into a folder called "datasets"
dataset <- read.csv('http://www.mghassany.com/MLcourse/datasets/Social_Network_Ads.csv')
# Describing and Exploring the dataset
str(dataset) # to show the structure of the dataset.
summary(dataset) # will show some statistics of every column.
# Remark what it shows when the column is a numerical or categorical variable.
# Remark that it has no sense for the variable User.ID
boxplot(Age ~ Purchased, data=dataset, col = "blue", main="Boxplot Age ~ Purchased")
# You know what is a boxplot right? I will let you interpret it.
boxplot(EstimatedSalary ~ Purchased, data=dataset,col = "red",
main="Boxplot EstimatedSalary ~ Purchased")
# Another boxplot
aov(EstimatedSalary ~Purchased, data=dataset)
# Anova test, but we need to show the summary of
# it in order to see the p-value and to interpret.
summary(aov(EstimatedSalary ~Purchased, data=dataset))
# What do you conclude ?
# Now another anova test for the variable Age
summary(aov(Age ~Purchased, data=dataset))
# There is a categorical variable in the dataset, which is Gender.
# Of course we cannot show a boxplot of Gender and Purchased.
# But we can show a table, or a mosaic plot, both tell the same thing.
table(dataset$Gender,dataset$Purchased)
# Remark for the function table(), that
# in lines we have the first argument, and in columns we have the second argument.
# Don't forget this when you use table() to show a confusion matrix!
mosaicplot(~ Purchased + Gender, data=dataset,
main = "MosaicPlot of two categorical variables: Puchased & Gender",
color = 2:3, las = 1)
# since these 2 variables are categorical, we can apply
# a Chi-square test. The null hypothesis is the independance between
# these variables. You will notice that p-value = 0.4562 which is higher than 0.5
# so we cannot reject the null hypothesis.
# conclusion: there is no dependance between Gender and Purchased (who
# said that women buy more than men? hah!)
chisq.test(dataset$Purchased, dataset$Gender)
# Let's say we want to remove the first two columns as we are not going to use them.
# But, we can in fact use a categorical variable as a predictor in logistic regression.
# It will treat it the same way as in regression. Check Appendix C.
# Try it by yourself if you would like to.
dataset = dataset[3:5]
str(dataset) # show the new structure of dataset
# splitting the dataset into training and testing sets
library(caTools)
set.seed(123) # CHANGE THE VALUE OF SEED. PUT YOUR STUDENT'S NUMBER INSTEAD OF 123.
split = sample.split(dataset$Purchased, SplitRatio = 0.75)
training_set = subset(dataset, split == TRUE)
test_set = subset(dataset, split == FALSE)
# scaling
# So here, we have two continuous predictors, Age and EstimatedSalary.
# There is a very big difference in their scales (units).
# That's why we scale them. But it is not always necessary.
training_set[-3] <- scale(training_set[-3]) #only first two columns
test_set[-3] <- scale(test_set[-3])
# Note that, we replace the columns of Age and EstimatedSalary in the training and
# test sets but their scaled versions. I noticed in a lot of reports that you scaled
# but you did not do the replacing.
# Note too that if you do it column by column you will have a problem because
# it will replace the column by a matrix, you need to retransform it to a vector then.
# Last note, to call the columns Age and EstimatedSalary we can it like I did or
# training_set[c(1,2)] or training_set[,c(1,2)] or training_set[,c("Age","EstimatedSalary")]
# logistic regression
classifier.logreg <- glm(Purchased ~ Age + EstimatedSalary , family = binomial, data=training_set)
classifier.logreg
summary(classifier.logreg)
# prediction
pred.glm = predict(classifier.logreg, newdata = test_set[,-3], type="response")
# Do not forget to put type response.
# By the way, you know what you get when you do not put it, right?
# Now let's assign observations to classes with respect to the probabilities
pred.glm_0_1 = ifelse(pred.glm >= 0.5, 1,0)
# I created a new vector, because we need the probabilities later for the ROC curve.
# show some values of the vectors
head(pred.glm)
head(pred.glm_0_1)
# confusion matrix
cm = table(test_set[,3], pred.glm_0_1)
cm
# First line to store it into cm, second line to show the matrix!
# You remember my note about table() function and the order of the arguments?
cm = table(pred.glm_0_1, test_set[,3])
cm
# You can show the confusion matrix in a mosaic plot by the way
mosaicplot(cm,col=sample(1:8,2)) # colors are random between 8 colors.
# ROC
require(ROCR)
score <- prediction(pred.glm,test_set[,3]) # we use the predicted probabilities not the 0 or 1
performance(score,"auc") # y.values
plot(performance(score,"tpr","fpr"),col="green")
abline(0,1,lty=8)
#2)
plot(test_set$EstimatedSalary, test_set$Age)
abline |
##' survspatNS function
##'
##' A function to perform maximun likelihood inference for non-spatial survival data.
##'
##' @param formula the model formula in a format compatible with the function flexsurvreg from the flexsurv package
##' @param data a SpatialPointsDataFrame object containing the survival data as one of the columns
##' @param dist choice of distribution function for baseline hazard. Current options are: exponentialHaz, weibullHaz, gompertzHaz, makehamHaz, tpowHaz
##' @param control additional control parameters, see ?inference.control
##' @return an object inheriting class 'mcmcspatsurv' for which there exist methods for printing, summarising and making inference from.
##' @seealso \link{tpowHaz}, \link{exponentialHaz}, \link{gompertzHaz}, \link{makehamHaz}, \link{weibullHaz},
##' \link{covmodel}, link{ExponentialCovFct}, \code{SpikedExponentialCovFct},
##' \link{mcmcpars}, \link{mcmcPriors}, \link{inference.control}
##' @references
##' \enumerate{
##' \item Benjamin M. Taylor. Auxiliary Variable Markov Chain Monte Carlo for Spatial Survival and Geostatistical Models. Benjamin M. Taylor. Submitted. \url{http://arxiv.org/abs/1501.01665}
##' }
##' @export
survspatNS <- function( formula,
data,
dist,
control=inference.control()){
control$hessian <- TRUE
responsename <- as.character(formula[[2]])
survivaldata <- data[[responsename]]
checkSurvivalData(survivaldata)
# start timing,
start <- Sys.time()
control$dist <- dist
##########
# This chunk of code borrowed from flexsurvreg
##########
call <- match.call()
indx <- match(c("formula", "data"), names(call), nomatch = 0)
if (indx[1] == 0){
stop("A \"formula\" argument is required")
}
temp <- call[c(1, indx)]
temp[[1]] <- as.name("model.frame")
m <- eval(temp, parent.frame())
Terms <- attr(m, "terms")
X <- model.matrix(Terms, m)
##########
# End of borrowed code
##########
X <- X[, -1, drop = FALSE]
info <- distinfo(dist)()
control$omegatrans <- info$trans
control$omegaitrans <- info$itrans
control$omegajacobian <- info$jacobian # used in computing the derivative of the log posterior with respect to the transformed omega (since it is easier to compute with respect to omega)
control$omegahessian <- info$hessian
control$censoringtype <- attr(survivaldata,"type")
if(control$censoringtype=="left" | control$censoringtype=="right"){
control$censored <- survivaldata[,"status"]==0
control$notcensored <- !control$censored
control$Ctest <- any(control$censored)
control$Utest <- any(control$notcensored)
}
else{
control$rightcensored <- survivaldata[,"status"] == 0
control$notcensored <- survivaldata[,"status"] == 1
control$leftcensored <- survivaldata[,"status"] == 2
control$intervalcensored <- survivaldata[,"status"] == 3
control$Rtest <- any(control$rightcensored)
control$Utest <- any(control$notcensored)
control$Ltest <- any(control$leftcensored)
control$Itest <- any(control$intervalcensored)
}
#######
cat("\n","Maximum likelihood using BFGS ...","\n")
mlmod <- maxlikparamPHsurv(surv=survivaldata,X=X,control=control)
estim <- mlmod$par
print(mlmod)
cat("Done.\n")
end <- Sys.time()
#browser()
retlist <- list()
retlist$formula <- formula
retlist$dist <- dist
retlist$control <- control
retlist$terms <- Terms
retlist$mlmod <- mlmod
# construct artificial samples from which the baseline hazard can be obtained with confidence intervals
ch <- t(chol(solve(mlmod$hessian)))
samp <- t(mlmod$par+ch%*%matrix(rnorm(1000*ncol(ch)),ncol(ch),1000))
betasamp <- samp[,1:ncol(X),drop=FALSE]
####
# Back transform for output
####
omegasamp <- samp[,(ncol(X)+1):ncol(samp),drop=FALSE]
if(ncol(omegasamp)>1){
omegasamp <- t(apply(omegasamp,1,control$omegaitrans))
}
else{
omegasamp <- t(t(apply(omegasamp,1,control$omegaitrans)))
}
colnames(omegasamp) <- info$parnames
colnames(betasamp) <- colnames(model.matrix(formula,data))[-1] #attr(Terms,"term.labels")
retlist$betasamp <- betasamp
retlist$omegasamp <- omegasamp
retlist$Ysamp <- matrix(0,1000,nrow(X))
#retlist$loglik <- loglik
retlist$X <- X
retlist$survivaldata <- survivaldata
retlist$gridded <- control$gridded
retlist$omegatrans <- control$omegatrans
retlist$omegaitrans <- control$omegaitrans
retlist$control <- control
retlist$censoringtype <- attr(survivaldata,"type")
retlist$time.taken <- Sys.time() - start
cat("Time taken:",retlist$time.taken,"\n")
class(retlist) <- c("list","mlspatsurv")
return(retlist)
}
| /R/survspatNS.R | no_license | bentaylor1/spatsurv | R | false | false | 5,185 | r | ##' survspatNS function
##'
##' A function to perform maximun likelihood inference for non-spatial survival data.
##'
##' @param formula the model formula in a format compatible with the function flexsurvreg from the flexsurv package
##' @param data a SpatialPointsDataFrame object containing the survival data as one of the columns
##' @param dist choice of distribution function for baseline hazard. Current options are: exponentialHaz, weibullHaz, gompertzHaz, makehamHaz, tpowHaz
##' @param control additional control parameters, see ?inference.control
##' @return an object inheriting class 'mcmcspatsurv' for which there exist methods for printing, summarising and making inference from.
##' @seealso \link{tpowHaz}, \link{exponentialHaz}, \link{gompertzHaz}, \link{makehamHaz}, \link{weibullHaz},
##' \link{covmodel}, link{ExponentialCovFct}, \code{SpikedExponentialCovFct},
##' \link{mcmcpars}, \link{mcmcPriors}, \link{inference.control}
##' @references
##' \enumerate{
##' \item Benjamin M. Taylor. Auxiliary Variable Markov Chain Monte Carlo for Spatial Survival and Geostatistical Models. Benjamin M. Taylor. Submitted. \url{http://arxiv.org/abs/1501.01665}
##' }
##' @export
survspatNS <- function( formula,
data,
dist,
control=inference.control()){
control$hessian <- TRUE
responsename <- as.character(formula[[2]])
survivaldata <- data[[responsename]]
checkSurvivalData(survivaldata)
# start timing,
start <- Sys.time()
control$dist <- dist
##########
# This chunk of code borrowed from flexsurvreg
##########
call <- match.call()
indx <- match(c("formula", "data"), names(call), nomatch = 0)
if (indx[1] == 0){
stop("A \"formula\" argument is required")
}
temp <- call[c(1, indx)]
temp[[1]] <- as.name("model.frame")
m <- eval(temp, parent.frame())
Terms <- attr(m, "terms")
X <- model.matrix(Terms, m)
##########
# End of borrowed code
##########
X <- X[, -1, drop = FALSE]
info <- distinfo(dist)()
control$omegatrans <- info$trans
control$omegaitrans <- info$itrans
control$omegajacobian <- info$jacobian # used in computing the derivative of the log posterior with respect to the transformed omega (since it is easier to compute with respect to omega)
control$omegahessian <- info$hessian
control$censoringtype <- attr(survivaldata,"type")
if(control$censoringtype=="left" | control$censoringtype=="right"){
control$censored <- survivaldata[,"status"]==0
control$notcensored <- !control$censored
control$Ctest <- any(control$censored)
control$Utest <- any(control$notcensored)
}
else{
control$rightcensored <- survivaldata[,"status"] == 0
control$notcensored <- survivaldata[,"status"] == 1
control$leftcensored <- survivaldata[,"status"] == 2
control$intervalcensored <- survivaldata[,"status"] == 3
control$Rtest <- any(control$rightcensored)
control$Utest <- any(control$notcensored)
control$Ltest <- any(control$leftcensored)
control$Itest <- any(control$intervalcensored)
}
#######
cat("\n","Maximum likelihood using BFGS ...","\n")
mlmod <- maxlikparamPHsurv(surv=survivaldata,X=X,control=control)
estim <- mlmod$par
print(mlmod)
cat("Done.\n")
end <- Sys.time()
#browser()
retlist <- list()
retlist$formula <- formula
retlist$dist <- dist
retlist$control <- control
retlist$terms <- Terms
retlist$mlmod <- mlmod
# construct artificial samples from which the baseline hazard can be obtained with confidence intervals
ch <- t(chol(solve(mlmod$hessian)))
samp <- t(mlmod$par+ch%*%matrix(rnorm(1000*ncol(ch)),ncol(ch),1000))
betasamp <- samp[,1:ncol(X),drop=FALSE]
####
# Back transform for output
####
omegasamp <- samp[,(ncol(X)+1):ncol(samp),drop=FALSE]
if(ncol(omegasamp)>1){
omegasamp <- t(apply(omegasamp,1,control$omegaitrans))
}
else{
omegasamp <- t(t(apply(omegasamp,1,control$omegaitrans)))
}
colnames(omegasamp) <- info$parnames
colnames(betasamp) <- colnames(model.matrix(formula,data))[-1] #attr(Terms,"term.labels")
retlist$betasamp <- betasamp
retlist$omegasamp <- omegasamp
retlist$Ysamp <- matrix(0,1000,nrow(X))
#retlist$loglik <- loglik
retlist$X <- X
retlist$survivaldata <- survivaldata
retlist$gridded <- control$gridded
retlist$omegatrans <- control$omegatrans
retlist$omegaitrans <- control$omegaitrans
retlist$control <- control
retlist$censoringtype <- attr(survivaldata,"type")
retlist$time.taken <- Sys.time() - start
cat("Time taken:",retlist$time.taken,"\n")
class(retlist) <- c("list","mlspatsurv")
return(retlist)
}
|
source("main.R")
DT <- get.data()
png("plot3.png", width=400, height=400)
plot(DT$DateTime,DT$Sub_metering_1,type="l", xlab="",ylab="Energy sub metering")
lines(DT$DateTime,DT$Sub_metering_2, col="red")
lines(DT$DateTime,DT$Sub_metering_3, col="blue")
legend("topright", col=c("black", "red", "blue"), c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),lty=1)
dev.off()
| /plot3.R | no_license | bwarfson/ExData_Plotting1 | R | false | false | 376 | r | source("main.R")
DT <- get.data()
png("plot3.png", width=400, height=400)
plot(DT$DateTime,DT$Sub_metering_1,type="l", xlab="",ylab="Energy sub metering")
lines(DT$DateTime,DT$Sub_metering_2, col="red")
lines(DT$DateTime,DT$Sub_metering_3, col="blue")
legend("topright", col=c("black", "red", "blue"), c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),lty=1)
dev.off()
|
##### Import Packages ####
library(rvest)
library(tidyverse)
library(chron)
### Possible Improvements ###
# 1. none
# responsible: Wei
### Staatlicher Hofkeller Würzburg ####
# crawl data
url <- "https://shop.hofkeller.de/veranstaltungen"
url %>%
read_html() -> raw_read
raw_read %>%
html_nodes(".product-name a") %>%
html_text(trim = T) -> raw_title
raw_read %>%
html_nodes("#products-list .std") %>%
html_text(trim = T) -> description
title = str_extract(raw_title, "[[:alpha:]].*")
date_start = str_extract(raw_title, "[0-9]{2}\\.[0-9]{2}\\.[0-9]{4}")
time_start = str_extract_all(description, "[0-9]{2}\\.[0-9]{2}", simplify = T)[,1]
time_end = str_extract_all(description, "[0-9]{2}\\.[0-9]{2}", simplify = T)[,2]
time_start = paste(gsub("\\.", ":", time_start) , ":00", sep = "")
time_start = gsub("^:00", "", time_start)
time_end = paste(gsub("\\.", ":", time_end) , ":00", sep = "")
time_end = gsub("^:00", "", time_end)
raw_read %>%
html_nodes(".price") %>%
html_text(trim = T) -> price
raw_read %>%
html_nodes(".link-learn") %>%
html_attr("href") -> link
# fixed data setup
organizer = "Staatlicher Hofkeller Würzburg"
url = "https://www.hofkeller.de/"
category= rep("Rund um den Wein", length(title))
lat = rep(49.793936, length(title))
lng = rep(9.9361123, length(title))
street = rep("Residenzplatz 3", length(title))
zip = rep(97070, length(title))
city = rep("Würzburg", length(title))
# data type conversion
date_start <- as.Date(date_start, "%d.%m.%Y")
date_end = as.Date(NA, "%d.%m.%Y")
time_start <- chron(times = time_start)
time_end <- chron(times = time_end)
# build table
crawled_df <- data.frame(
category = category,
title = title,
date_start = date_start,
date_end = date_end,
time_start = time_start,
time_end = time_end,
price = price,
description = description,
lat = lat,
lng = lng,
street = street,
zip = zip,
city = city,
link = link)
#add metadf idlocation
idlocation = 403099
meta_df = data.frame(organizer, url, idlocation)
names(meta_df)[names(meta_df) == 'url'] <- 'url_crawler'
meta_df["idcrawler"] = 25
meta_df["id_category"] = 10586
#write to database
write_dataframes_to_database(crawled_df, meta_df, conn)
| /new_crawlers/Staatlicher_Hofkeller_Wuerzburg Kopie.R | no_license | Adrian398/crawler | R | false | false | 2,471 | r | ##### Import Packages ####
library(rvest)
library(tidyverse)
library(chron)
### Possible Improvements ###
# 1. none
# responsible: Wei
### Staatlicher Hofkeller Würzburg ####
# crawl data
url <- "https://shop.hofkeller.de/veranstaltungen"
url %>%
read_html() -> raw_read
raw_read %>%
html_nodes(".product-name a") %>%
html_text(trim = T) -> raw_title
raw_read %>%
html_nodes("#products-list .std") %>%
html_text(trim = T) -> description
title = str_extract(raw_title, "[[:alpha:]].*")
date_start = str_extract(raw_title, "[0-9]{2}\\.[0-9]{2}\\.[0-9]{4}")
time_start = str_extract_all(description, "[0-9]{2}\\.[0-9]{2}", simplify = T)[,1]
time_end = str_extract_all(description, "[0-9]{2}\\.[0-9]{2}", simplify = T)[,2]
time_start = paste(gsub("\\.", ":", time_start) , ":00", sep = "")
time_start = gsub("^:00", "", time_start)
time_end = paste(gsub("\\.", ":", time_end) , ":00", sep = "")
time_end = gsub("^:00", "", time_end)
raw_read %>%
html_nodes(".price") %>%
html_text(trim = T) -> price
raw_read %>%
html_nodes(".link-learn") %>%
html_attr("href") -> link
# fixed data setup
organizer = "Staatlicher Hofkeller Würzburg"
url = "https://www.hofkeller.de/"
category= rep("Rund um den Wein", length(title))
lat = rep(49.793936, length(title))
lng = rep(9.9361123, length(title))
street = rep("Residenzplatz 3", length(title))
zip = rep(97070, length(title))
city = rep("Würzburg", length(title))
# data type conversion
date_start <- as.Date(date_start, "%d.%m.%Y")
date_end = as.Date(NA, "%d.%m.%Y")
time_start <- chron(times = time_start)
time_end <- chron(times = time_end)
# build table
crawled_df <- data.frame(
category = category,
title = title,
date_start = date_start,
date_end = date_end,
time_start = time_start,
time_end = time_end,
price = price,
description = description,
lat = lat,
lng = lng,
street = street,
zip = zip,
city = city,
link = link)
#add metadf idlocation
idlocation = 403099
meta_df = data.frame(organizer, url, idlocation)
names(meta_df)[names(meta_df) == 'url'] <- 'url_crawler'
meta_df["idcrawler"] = 25
meta_df["id_category"] = 10586
#write to database
write_dataframes_to_database(crawled_df, meta_df, conn)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/create_dataset.R
\name{create_dataset}
\alias{create_dataset}
\title{Create a new dataset.}
\usage{
create_dataset(owner_id, create_dataset_req)
}
\arguments{
\item{owner_id}{data.world user name of the dataset owner.}
\item{create_dataset_req}{Request object of
type \code{\link{dataset_create_request}}.}
}
\value{
Object of type \code{\link{create_dataset_response}}.
}
\description{
Create a new dataset.
}
\examples{
request <- dwapi::dataset_create_request(
title='testdataset', visibility = 'OPEN',
description = 'Test Dataset by R-SDK', tags = c('rsdk', 'sdk', 'arr'),
license = 'Public Domain')
request <- dwapi::add_file(request = request, name = 'file4.csv',
url = 'https://data.world/file4.csv')
\dontrun{
dwapi::create_dataset(create_dataset_req = request,
owner_id = 'user')
}
}
| /man/create_dataset.Rd | permissive | datadotworld/dwapi-r | R | false | true | 884 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/create_dataset.R
\name{create_dataset}
\alias{create_dataset}
\title{Create a new dataset.}
\usage{
create_dataset(owner_id, create_dataset_req)
}
\arguments{
\item{owner_id}{data.world user name of the dataset owner.}
\item{create_dataset_req}{Request object of
type \code{\link{dataset_create_request}}.}
}
\value{
Object of type \code{\link{create_dataset_response}}.
}
\description{
Create a new dataset.
}
\examples{
request <- dwapi::dataset_create_request(
title='testdataset', visibility = 'OPEN',
description = 'Test Dataset by R-SDK', tags = c('rsdk', 'sdk', 'arr'),
license = 'Public Domain')
request <- dwapi::add_file(request = request, name = 'file4.csv',
url = 'https://data.world/file4.csv')
\dontrun{
dwapi::create_dataset(create_dataset_req = request,
owner_id = 'user')
}
}
|
test_that("Path to test file to upload is correct", {
expect_true(file.exists("test_upload1.png"))
})
| /tests/testthat/test-file.R | no_license | hafen/osfr | R | false | false | 104 | r | test_that("Path to test file to upload is correct", {
expect_true(file.exists("test_upload1.png"))
})
|
unlink(c(TXTPATH, HTMLPATH, RMD_TEMPLATE))
| /tests/testthat/teardown-files.R | no_license | ColinFay/emayili | R | false | false | 43 | r | unlink(c(TXTPATH, HTMLPATH, RMD_TEMPLATE))
|
############################################
## Title: Educational Attainment Update ##
## Author(s): Valerie Evans ##
## Date Created: 10/19/2017 ##
## Date Modified: ##
############################################
require(dplyr)
require(tidyr)
require(tm)
require(readr)
# set working directory
setwd("ASC Table DP02")
############################################################################################################################
## CLEAN NEW DATASETS ##
############################################################################################################################
# load new datasets
ACS13 <- read.csv("ACS_13_5YR_DP02_with_ann.csv")
ACS14 <- read.csv("ACS_14_5YR_DP02_with_ann.csv")
ACS15 <- read.csv("ACS_15_5YR_DP02_with_ann.csv")
# select relevant columns
edu13 <- select(ACS13, "GEO.display.label", "HC01_VC85", "HC02_VC85", "HC03_VC95", "HC04_VC95", "HC03_VC96", "HC04_VC96", "HC03_VC92", "HC04_VC92")
edu14 <- select(ACS14, "GEO.display.label", "HC01_VC85", "HC02_VC85", "HC03_VC95", "HC04_VC95", "HC03_VC96", "HC04_VC96", "HC03_VC92", "HC04_VC92")
edu15 <- select(ACS15, "GEO.display.label", "HC01_VC85", "HC02_VC85", "HC03_VC95", "HC04_VC95", "HC03_VC96", "HC04_VC96", "HC03_VC92", "HC04_VC92")
# remove first row
edu13 <- edu13[-c(1),]
edu14 <- edu14[-c(1),]
edu15 <- edu15[-c(1),]
# remove rows with 'County subdivisions not defined'
edu13 <- dplyr::filter(edu13, !grepl("County subdivisions not defined", GEO.display.label))
edu14 <- dplyr::filter(edu14, !grepl("County subdivisions not defined", GEO.display.label))
edu15 <- dplyr::filter(edu15, !grepl("County subdivisions not defined", GEO.display.label))
# rename columns
colnames(edu13) <- c("Region", "Pop_25", "Margin_Error_Pop", "HS_Pct", "Margin_Error_HS", "Bachelors_Pct", "Margin_Error_Bach", "Grad_Pct", "Margin_Error_Grad")
colnames(edu14) <- c("Region", "Pop_25", "Margin_Error_Pop", "HS_Pct", "Margin_Error_HS", "Bachelors_Pct", "Margin_Error_Bach", "Grad_Pct", "Margin_Error_Grad")
colnames(edu15) <- c("Region", "Pop_25", "Margin_Error_Pop", "HS_Pct", "Margin_Error_HS", "Bachelors_Pct", "Margin_Error_Bach", "Grad_Pct", "Margin_Error_Grad")
##############################################################################################################################
# split geography column into 4: Municipal, County, State, Region
edu13$Region <- gsub("Massachusetts", "\\MA", edu13$Region)
edu13 <- separate(edu13, "Region", c("Municipal", "County", "State"), ",", remove=FALSE, extra="merge", fill="left")
edu13$Municipal <- removeWords(edu13$Municipal, "town")
edu13$Municipal <- removeWords(edu13$Municipal, "city")
edu13$Municipal <- removeWords(edu13$Municipal, "Town")
edu13$State[edu13$State == "United States"] <- NA
edu13$County[is.na(edu13$County)] <- "NA County"
edu13$Region <- gsub("(.*),.*", "\\1", edu13$Region) # run twice to remove all text after commas
edu13$Region <- removeWords(edu13$Region, "town")
edu13$Region <- removeWords(edu13$Region, "city")
edu13$Region <- removeWords(edu13$Region, "Town")
# add columns with year range
edu13$Five_Year_Range <- rep("2009-2013", nrow(edu13))
# order columns by indexing
edu13 <- edu13[c(2,3,4,1,13,5,6,7,8,9,10,11,12)]
################################################################################################################################
# repeat above column split for each dataset (edu14 and edu15)
edu14$Region <- gsub("Massachusetts", "\\MA", edu14$Region)
edu14 <- separate(edu14, "Region", c("Municipal", "County", "State"), ",", remove=FALSE, extra="merge", fill="left")
edu14$Municipal <- removeWords(edu14$Municipal, "town")
edu14$Municipal <- removeWords(edu14$Municipal, "city")
edu14$Municipal <- removeWords(edu14$Municipal, "Town")
edu14$State[edu14$State == "United States"] <- NA
edu14$County[is.na(edu14$County)] <- "NA County"
edu14$Region <- gsub("(.*),.*", "\\1", edu14$Region) # run twice to remove all text after commas
edu14$Region <- gsub("(.*),.*", "\\1", edu14$Region)
edu14$Region <- removeWords(edu14$Region, "town")
edu14$Region <- removeWords(edu14$Region, "city")
edu14$Region <- removeWords(edu14$Region, "Town")
# add columns with year range
edu14$Five_Year_Range <- rep("2010-2014", nrow(edu14))
# order columns by indexing
edu14 <- edu14[c(2,3,4,1,13,5,6,7,8,9,10,11,12)]
#################################################################################################################################
edu15$Region <- gsub("Massachusetts", "\\MA", edu15$Region)
edu15 <- separate(edu15, "Region", c("Municipal", "County", "State"), ",", remove=FALSE, extra="merge", fill="left")
edu15$Municipal <- removeWords(edu15$Municipal, "town")
edu15$Municipal <- removeWords(edu15$Municipal, "city")
edu15$Municipal <- removeWords(edu15$Municipal, "Town")
edu15$State[edu15$State == "United States"] <- NA
edu15$County[is.na(edu15$County)] <- "NA County"
edu15$Region <- gsub("(.*),.*", "\\1", edu13$Region) # run twice to remove all text after commas
edu15$Region <- gsub("(.*),.*", "\\1", edu13$Region)
edu15$Region <- removeWords(edu15$Region, "town")
edu15$Region <- removeWords(edu15$Region, "city")
edu15$Region <- removeWords(edu15$Region, "Town")
# add columns with year range
edu15$Five_Year_Range <- rep("2011-2015", nrow(edu15))
# order columns by indexing
edu15 <- edu15[c(2,3,4,1,13,5,6,7,8,9,10,11,12)]
#################################################################################################################################
# save new datasets as csv files
write.csv(file="edu13.csv", x=edu13)
write.csv(file="edu14.csv", x=edu14)
write.csv(file="edu15.csv", x=edu15)
##################################################################################################################################
## MERGE DATASETS ##
##################################################################################################################################
# merge new datasets
edu_13_15 <- rbind(edu13, edu14, edu15)
# save new merged dataset
write.csv(file="edu_13_15.csv", x=edu_13_15)
# import old and new datasets
edudata_backup <- read_csv("edudata_backup.csv")
edumerge <- read_csv("edu_13_15.csv")
# delete first columns [X1]
edudata_backup[1] <- NULL
edumerge[1] <- NULL
# merge datasets
edumerge_all <- rbind(edudata_backup, edumerge)
# save new merged dataset
write.csv(file="edumerge_all.csv", x=edumerge_all)
| /education/edudata_update.R | no_license | sEigmA/SEIGMA | R | false | false | 6,450 | r | ############################################
## Title: Educational Attainment Update ##
## Author(s): Valerie Evans ##
## Date Created: 10/19/2017 ##
## Date Modified: ##
############################################
require(dplyr)
require(tidyr)
require(tm)
require(readr)
# set working directory
setwd("ASC Table DP02")
############################################################################################################################
## CLEAN NEW DATASETS ##
############################################################################################################################
# load new datasets
ACS13 <- read.csv("ACS_13_5YR_DP02_with_ann.csv")
ACS14 <- read.csv("ACS_14_5YR_DP02_with_ann.csv")
ACS15 <- read.csv("ACS_15_5YR_DP02_with_ann.csv")
# select relevant columns
edu13 <- select(ACS13, "GEO.display.label", "HC01_VC85", "HC02_VC85", "HC03_VC95", "HC04_VC95", "HC03_VC96", "HC04_VC96", "HC03_VC92", "HC04_VC92")
edu14 <- select(ACS14, "GEO.display.label", "HC01_VC85", "HC02_VC85", "HC03_VC95", "HC04_VC95", "HC03_VC96", "HC04_VC96", "HC03_VC92", "HC04_VC92")
edu15 <- select(ACS15, "GEO.display.label", "HC01_VC85", "HC02_VC85", "HC03_VC95", "HC04_VC95", "HC03_VC96", "HC04_VC96", "HC03_VC92", "HC04_VC92")
# remove first row
edu13 <- edu13[-c(1),]
edu14 <- edu14[-c(1),]
edu15 <- edu15[-c(1),]
# remove rows with 'County subdivisions not defined'
edu13 <- dplyr::filter(edu13, !grepl("County subdivisions not defined", GEO.display.label))
edu14 <- dplyr::filter(edu14, !grepl("County subdivisions not defined", GEO.display.label))
edu15 <- dplyr::filter(edu15, !grepl("County subdivisions not defined", GEO.display.label))
# rename columns
colnames(edu13) <- c("Region", "Pop_25", "Margin_Error_Pop", "HS_Pct", "Margin_Error_HS", "Bachelors_Pct", "Margin_Error_Bach", "Grad_Pct", "Margin_Error_Grad")
colnames(edu14) <- c("Region", "Pop_25", "Margin_Error_Pop", "HS_Pct", "Margin_Error_HS", "Bachelors_Pct", "Margin_Error_Bach", "Grad_Pct", "Margin_Error_Grad")
colnames(edu15) <- c("Region", "Pop_25", "Margin_Error_Pop", "HS_Pct", "Margin_Error_HS", "Bachelors_Pct", "Margin_Error_Bach", "Grad_Pct", "Margin_Error_Grad")
##############################################################################################################################
# split geography column into 4: Municipal, County, State, Region
edu13$Region <- gsub("Massachusetts", "\\MA", edu13$Region)
edu13 <- separate(edu13, "Region", c("Municipal", "County", "State"), ",", remove=FALSE, extra="merge", fill="left")
edu13$Municipal <- removeWords(edu13$Municipal, "town")
edu13$Municipal <- removeWords(edu13$Municipal, "city")
edu13$Municipal <- removeWords(edu13$Municipal, "Town")
edu13$State[edu13$State == "United States"] <- NA
edu13$County[is.na(edu13$County)] <- "NA County"
edu13$Region <- gsub("(.*),.*", "\\1", edu13$Region) # run twice to remove all text after commas
edu13$Region <- removeWords(edu13$Region, "town")
edu13$Region <- removeWords(edu13$Region, "city")
edu13$Region <- removeWords(edu13$Region, "Town")
# add columns with year range
edu13$Five_Year_Range <- rep("2009-2013", nrow(edu13))
# order columns by indexing
edu13 <- edu13[c(2,3,4,1,13,5,6,7,8,9,10,11,12)]
################################################################################################################################
# repeat above column split for each dataset (edu14 and edu15)
edu14$Region <- gsub("Massachusetts", "\\MA", edu14$Region)
edu14 <- separate(edu14, "Region", c("Municipal", "County", "State"), ",", remove=FALSE, extra="merge", fill="left")
edu14$Municipal <- removeWords(edu14$Municipal, "town")
edu14$Municipal <- removeWords(edu14$Municipal, "city")
edu14$Municipal <- removeWords(edu14$Municipal, "Town")
edu14$State[edu14$State == "United States"] <- NA
edu14$County[is.na(edu14$County)] <- "NA County"
edu14$Region <- gsub("(.*),.*", "\\1", edu14$Region) # run twice to remove all text after commas
edu14$Region <- gsub("(.*),.*", "\\1", edu14$Region)
edu14$Region <- removeWords(edu14$Region, "town")
edu14$Region <- removeWords(edu14$Region, "city")
edu14$Region <- removeWords(edu14$Region, "Town")
# add columns with year range
edu14$Five_Year_Range <- rep("2010-2014", nrow(edu14))
# order columns by indexing
edu14 <- edu14[c(2,3,4,1,13,5,6,7,8,9,10,11,12)]
#################################################################################################################################
edu15$Region <- gsub("Massachusetts", "\\MA", edu15$Region)
edu15 <- separate(edu15, "Region", c("Municipal", "County", "State"), ",", remove=FALSE, extra="merge", fill="left")
edu15$Municipal <- removeWords(edu15$Municipal, "town")
edu15$Municipal <- removeWords(edu15$Municipal, "city")
edu15$Municipal <- removeWords(edu15$Municipal, "Town")
edu15$State[edu15$State == "United States"] <- NA
edu15$County[is.na(edu15$County)] <- "NA County"
edu15$Region <- gsub("(.*),.*", "\\1", edu13$Region) # run twice to remove all text after commas
edu15$Region <- gsub("(.*),.*", "\\1", edu13$Region)
edu15$Region <- removeWords(edu15$Region, "town")
edu15$Region <- removeWords(edu15$Region, "city")
edu15$Region <- removeWords(edu15$Region, "Town")
# add columns with year range
edu15$Five_Year_Range <- rep("2011-2015", nrow(edu15))
# order columns by indexing
edu15 <- edu15[c(2,3,4,1,13,5,6,7,8,9,10,11,12)]
#################################################################################################################################
# save new datasets as csv files
write.csv(file="edu13.csv", x=edu13)
write.csv(file="edu14.csv", x=edu14)
write.csv(file="edu15.csv", x=edu15)
##################################################################################################################################
## MERGE DATASETS ##
##################################################################################################################################
# merge new datasets
edu_13_15 <- rbind(edu13, edu14, edu15)
# save new merged dataset
write.csv(file="edu_13_15.csv", x=edu_13_15)
# import old and new datasets
edudata_backup <- read_csv("edudata_backup.csv")
edumerge <- read_csv("edu_13_15.csv")
# delete first columns [X1]
edudata_backup[1] <- NULL
edumerge[1] <- NULL
# merge datasets
edumerge_all <- rbind(edudata_backup, edumerge)
# save new merged dataset
write.csv(file="edumerge_all.csv", x=edumerge_all)
|
install.packages('gbm')
install.packages("MESS") #auc
library(MESS)
library(gbm)
#Read data in R and preparation
setwd("U:/hguan003/MM")
Gene_expression=read.csv("GSE24080UAMSentrezIDlevel.csv",header=T,sep=",",row.names=1)
clinical<-read.csv("globalClinTraining.csv",header=T,sep=",",row.names = 2,stringsAsFactors = FALSE)
a<-c("GSE24080UAMS","EMTAB4032","HOVON65")
clinical<-subset(clinical,Study%in%a)
clinical<-subset(clinical[,c("Study","D_Age","D_PFS","D_PFS_FLAG","D_ISS","HR_FLAG")])
clinical$Patient<-rownames(clinical)
clinical<-clinical[c("D_Age","D_ISS","Study","Patient","D_PFS","D_PFS_FLAG","HR_FLAG")]
clinical$D_Age<-clinical$D_Age/100
clinical$D_ISS<-clinical$D_ISS/10
clinical$D_PFS<-clinical$D_PFS/30.5
clinical_UAMS<-subset(clinical,Study=="GSE24080UAMS")
clinical_UAMS[clinical_UAMS[,"HR_FLAG"]==TRUE,7]=1
clinical_UAMS[clinical_UAMS[,"HR_FLAG"]==FALSE,7]=0
train_data=as.data.frame(t(Gene_expression))
train_data<-as.data.frame(scale(train_data))
train_data<-merge(train_data,clinical_UAMS[,c("D_Age","D_ISS","Study","Patient","D_PFS","D_PFS_FLAG","HR_FLAG")],by="row.names",all.x=TRUE)
row.names(train_data)<-train_data[,1]
train_data<-train_data[-c(1)]
library(unbalanced)
n<-ncol(train_data)
output<-as.factor(train_data[,n])
input<-train_data[,-((n):(n-4))]
data<-ubSMOTE(X=input,Y=output)
newdat<-cbind(data$X,data$Y)
colnames(newdat)[ncol(newdat)]<-'HR_FLAG'
##differential expression with limma package
library(limma)
f<-factor(paste(newdat$HR_FLAG,sep=""))
design<--model.matrix(~f)
colnames(design)<-levels(f)
fit<-lmFit(t(newdat[,1:(ncol(newdat)-3)]),design)
efit<-eBayes(fit)
limma_gene<-toptable(efit,coef=2,number=10000,p.value=0.001)
#write.csv(limma_gene,file="UAMS_limma_gene.csv")
##Based on the selected gene set, get a data set of original samples with survival outcome for survival analysis
limma_data<-train_data[,c(rownames(limma_gene),"D_Age","D_ISS","D_PFS","D_PFS_FLAG")]
##modify Gene entrez ID as "DXXX"
colnames(limma_data)[1:(ncol(limma_data)-4)]<-paste('D',sep='',colnames(limma_data)[1:(ncol(limma_data)-4)])
gene_feature<-function(data){
feature=''
{for (i in 1: nrow(data)) {feature=paste(feature,colnames(data)[i],'+')}}
feature=substr(feature,1,nchar(feature)-1)
return(feature)
}
survival_formula<-formula(paste('Surv(','D_PFS',',','D_PFS_FLAG',') ~',' D_Age + D_ISS +',gene_feature(limma_data[,1:(ncol(limma_data)-4)])))
library(ranger)
library(survival)
survival_model<-ranger(survival_formula,data=limma_data,seed=2234,importance = 'permutation',mtry=2,verbose=T,num.trees=50,write.forest=T)
sort(survival_model$variable.importance)
set.seed(222)
random_splits<-runif(nrow(limma_data))
train_MM<-limma_data[random_splits<0.7,]
test_MM<-limma_data[random_splits>=0.7,]
survival_model<-ranger(survival_formula,
data=train_MM,
seed=2234,
mtry=5,
verbose=T,
num.trees=50,
write.forest=T)
survival_predictions<-predict(survival_model,test_MM[,1:(ncol(limma_data)-2)])
#look at some posibilities of survival
#plot(survival_model$unique.death.times[1:4],survival_model$survival[1,1:4],col='orange',ylim=c(0.4,1))
##In order to align the survival and the classification models, we will focus on the probability of reaching event over the certain time
##We get the basic survival prediction using our test data and then we flip the probability of the period of choice and get the AUC score
limma<-train_data[,c(rownames(limma_gene),"D_Age","D_ISS","HR_FLAG")]
colnames(limma)[1:(ncol(limma)-3)]<-paste('D',sep='',colnames(limma)[1:(ncol(limma)-3)])
limma$HR_FLAG[363]=0
#GBM: Generalized Boosted Regression Model for classification
GBM_formula<-formula(paste("HR_FLAG~",' D_Age + D_ISS +',gene_feature(limma[,1:(ncol(limma)-3)])))
set.seed(1234)
gbm_model=gbm(GBM_formula,
data=limma,
distribution='bernoulli',
n.trees=4000, ##suggests between 3000 and 10000
interaction.depth = 3,
shrinkage=0.01, ##suggests small shirinkage, such between 0.01 and 0.001
bag.fraction=0.5,
keep.data=TURE,
cv.folds=5)
nTrees<-gbm.perf(gbm_model)
validate_predictions<-predict(gbm_model,newdata=test_MM,type='response',n.trees=nTrees)
#install.packages('pROC')
library(pROC)
roc(response=test_MM$HR_FLAG,predictor=test_MM[,1:144])
##NOw that both models can predict the same period and probablity of reaching the event, we ensemble both Survival and classification models
##Split to training/testing set
library(h2o)
h2o.init(nthreads=-1,max_mem_size = "16G",enable_assertions = FALSE)
total.hex<-as.h2o(train_data[,2:(ncol(train_data)-4)])
total.hex$label<-as.h2o(train_data[,(ncol(train_data)-1)])
splits<-h2o.splitFrame(total.hex,c(0.6,0.2),destination_frames=c("train","valid","test"),seed=1234)
train<-h2o.assign(splits[[1]],"train.hex")#60%
valid<-h2o.assign(splits[[2]],"valid.hex")#20%
test<-h2o.assign(splits[[3]],"test.hex")#20%
total_label<-as.vector(total.hex[,ncol(total.hex)])
train_label<-as.vector(train[,ncol(train)])
train[,ncol(train)]<-NULL
valid_label<-as.vector(valid[,ncol(valid)])
valid[,ncol(valid)]<-NULL
test_label<-as.vector(test[,ncol(test)])
test[,ncol(test)]<-NULL
total.hex[,ncol(total.hex)]<-NULL
hyper_params_ae<-list(
hidden=list(c(1000,100,1000),c(500)))
ae_grid<-h2o.grid(
algorithm="deeplearning",
grid_id = "ae_grid_id",
training_frame=total.hex,
epochs=10,
export_weights_and_biases = T,
ignore_const_cols = F,
autoencoder = T,
activation=c("Tanh"),
l1=1e-5,
l2=1e-5,
max_w2=10,
variable_importances = T,
hyper_params = hyper_params_ae
)
summary(ae_grid)
nmodel<-nrow(ae_grid@summary_table)
##create a dataframe to store prediction score for different model
ae_predict<-setNames(as.data.frame(matrix(ncol=9,nrow = 0)),c("model","AUC","PRAUC","Accuracy","F1_score","MCC","sensitivity","specific","classloss"))
Risk_Score<-as.data.frame(matrix(ncol=nrow(test)+1,nrow = 0))
class_result<-as.data.frame(matrix(ncol=nrow(test)+1,nrow = 0))
#function change label to 0 and 1 for calculate MMC
adjustmcc<-function(truth,predict,cutoff=1){
{for (i in 1:length(predict)) {if (predict[i]==-1 ){{predict[i]=0}}}}
{for (i in 1:length(truth)) {if (truth[i]==-1 ){{truth[i]=0}}}}
return(mcc(truth,predict,cutoff=1))
}
for (i in 1:nmodel) {
model<-h2o.getModel(ae_grid@model_ids[[i]])
fealayer<-(length(model@parameters$hidden)+1)/2
nfea<-model@parameters$hidden[fealayer]
deep.fea<-as.data.frame(h2o.deepfeatures( model,total.hex,layer=fealayer))
deep.fea$label<-as.character(total_label)
deep.fea.train<-as.data.frame(h2o.deepfeatures( model,train,layer=fealayer))
deep.fea.train$label<-as.character(train_label)
deep.fea.valid<-as.data.frame(h2o.deepfeatures(model,valid,layer=fealayer))
deep.fea.valid$label<-as.character(valid_label)
deep.fea.test<-as.data.frame(h2o.deepfeatures(model,test,layer=fealayer))
deep.fea.test$label<-as.character(test_label)
##SVM
library(e1071)
tc<-tune.control(cross=5)
svmtrain<-rbind(deep.fea.train,deep.fea.valid)
svmfit<-svm(svmtrain[,1:nfea],as.factor(svmtrain$label),tune.control=tc)
pred<-predict(svmfit,deep.fea.test[,1:nfea])
pred<-as.vector(pred)
deep.fea.test$label<-as.vector(deep.fea.test$label)
SVM_AUC<-MLmetrics::AUC(as.numeric(pred),as.numeric(deep.fea.test$label))
SVM_PRAUC<-PRAUC(as.numeric(pred),as.numeric(deep.fea.test$label))
SVM_accuracy<-Accuracy(pred,deep.fea.test$label)
SVM_F1<-F1_Score(as.numeric(deep.fea.test$label),as.numeric(pred))
SVM_MCC<-adjustmcc(as.numeric(deep.fea.test$label),as.numeric(pred),cutoff=1)
SVM_sensitivity<-Sensitivity(deep.fea.test$label,pred)
SVM_specific<-Specificity(deep.fea.test$label,pred)
SVM_classloss<-ZeroOneLoss(deep.fea.test$label,pred)
#add model svm prediction score to class_result and ae_predict
asvm<-as.data.frame(t(c(SVM_AUC,SVM_PRAUC,SVM_accuracy,SVM_F1,SVM_MCC,SVM_sensitivity,SVM_specific,SVM_classloss)))
asvm<-as.data.frame(round(asvm,4))
asvm.model<-paste(ae_grid@summary_table[i,1],"SVM",sep="")
asvm<-cbind(asvm.model,asvm)
colnames(asvm)<-colnames(ae_predict)
ae_predict<-rbind(ae_predict,asvm)
pred.model<-paste(ae_grid@summary_table[i,1],"SVM",sep="")
pred_class<-cbind(pred.model,t(pred))
colnames(pred_class)<-colnames(class_result)
class_result<-rbind(class_result,pred_class)
##random forest
library(ranger)
fitcontrol<-trainControl(method="repeatedcv",number=10,repeats=2)
RFtrain<-rbind(deep.fea.train,deep.fea.valid)
rffit<-caret:::train(label~.,
RFtrain,
method="ranger",
tuneGrid=expand.grid(
.mtry=2),
metric="Accuracy",
trControl=fitcontrol)
pred_rf<-predict(rffit,deep.fea.test)
pred_rf<-as.vector(pred_rf)
deep.fea.test$label<-as.vector(deep.fea.test$label)
rf_AUC<-AUC(as.numeric(pred_rf),as.numeric(deep.fea.test$label))
rf_accuracy<-Accuracy(pred_rf,deep.fea.test$label)
rf_F1<-F1_Score(as.numeric(deep.fea.test$label),as.numeric(pred_rf))
rf_PRAUC<-PRAUC(as.numeric(pred_rf),as.numeric(deep.fea.test$label))
rf_MCC<-adjustmcc(as.numeric(deep.fea.test$label),as.numeric(pred_rf),cutoff=1)
rf_sensitivity<-Sensitivity(deep.fea.test$label,pred_rf)
rf_specific<-Specificity(deep.fea.test$label,pred_rf)
rf_classloss<-ZeroOneLoss(deep.fea.test$label,pred_rf)
#add model rf prediction score to class_result and ae_predict
arf<-as.data.frame(t(c(rf_AUC,rf_PRAUC,rf_accuracy,rf_F1,rf_MCC,rf_sensitivity,rf_specific,rf_classloss)))
arf<-as.data.frame(round(arf,4))
arf.model<-paste(ae_grid@summary_table[i,1],"RF",sep="")
arf<-cbind(arf.model,arf)
colnames(arf)<-colnames(ae_predict)
ae_predict<-rbind(ae_predict,arf)
pred_rf.model<-paste(ae_grid@summary_table[i,1],"RF",sep="")
pred_rf_class<-cbind(pred_rf.model,t(pred_rf))
colnames(pred_rf_class)<-colnames(class_result)
class_result<-rbind(class_result,pred_rf_class)
##K nearest neighbor
knnfit<-caret::train(label~.,
RFtrain,
method="knn",
tuneGrid=expand.grid(
.k=5),
trControl=fitcontrol)
pred_knn<-predict(knnfit,deep.fea.test)
pred_knn<-as.vector(pred_knn)
deep.fea.test$label<-as.vector(deep.fea.test$label)
knn_accuracy<-Accuracy(pred_knn,deep.fea.test$label)
knn_AUC<-AUC(as.numeric(pred_knn),as.numeric(deep.fea.test$label))
knn_F1<-F1_Score(as.numeric(deep.fea.test$label),as.numeric(pred_knn))
knn_PRAUC<-PRAUC(as.numeric(pred_knn),as.numeric(deep.fea.test$label))
knn_MCC<-adjustmcc(as.numeric(deep.fea.test$label),as.numeric(pred_knn),cutoff=1)
knn_sensitivity<-Sensitivity(deep.fea.test$label,pred_knn)
knn_specific<-Specificity(deep.fea.test$label,pred_knn)
knn_classloss<-ZeroOneLoss(deep.fea.test$label,pred_knn)
#add model rf prediction score to class_result and ae_predict
aknn<-as.data.frame(t(c(knn_AUC,knn_PRAUC,knn_accuracy,knn_F1,knn_MCC,knn_sensitivity,knn_specific,knn_classloss)))
aknn<-as.data.frame(round(aknn,4))
aknn.model<-paste(ae_grid@summary_table[i,1],"KNN",sep="")
aknn<-cbind(aknn.model,aknn)
colnames(aknn)<-colnames(ae_predict)
ae_predict<-rbind(ae_predict,aknn)
pred_knn.model<-paste(ae_grid@summary_table[i,1],"KNN",sep="")
pred_knn_class<-cbind(pred_knn.model,t(pred_knn))
colnames(pred_knn_class)<-colnames(class_result)
class_result<-rbind(class_result,pred_knn_class)
#Multiple Paerceptron Network by Stachastic Gradient Descent
nn_Grid<-expand.grid(
.size=c(50,10,5),
.decay=0.00147)
nn_fit<-caret::train(label~.,
RFtrain,
method="nnet",
metric="Accuracy",
tuneGrid=nn_Grid,
MaxNWts=10000,
maxit=100,
trControl=fitcontrol,
trace=FALSE)
pred_nn<-predict(nn_fit,deep.fea.test)
pred_nn<-as.vector(pred_nn)
deep.fea.test$label<-as.vector(deep.fea.test$label)
nn_accuracy<-Accuracy(pred_nn,deep.fea.test$label)
nn_AUC<-AUC(as.numeric(pred_nn),as.numeric(deep.fea.test$label))
nn_F1<-F1_Score(as.numeric(deep.fea.test$label),as.numeric(pred_nn))
nn_PRAUC<-PRAUC(as.numeric(pred_nn),as.numeric(deep.fea.test$label))
nn_MCC<-adjustmcc(as.numeric(deep.fea.test$label),as.numeric(pred_nn),cutoff=1)
nn_sensitivity<-Sensitivity(deep.fea.test$label,pred_nn)
nn_specific<-Specificity(deep.fea.test$label,pred_nn)
nn_classloss<-ZeroOneLoss(deep.fea.test$label,pred_nn)
#add model rf prediction score to class_result and ae_predict
a_nn<-as.data.frame(t(c(nn_AUC,nn_PRAUC,nn_accuracy,nn_F1,nn_MCC,nn_sensitivity,nn_specific,nn_classloss)))
a_nn<-as.data.frame(round(a_nn,4))
a_nn.model<-paste(ae_grid@summary_table[i,1],"ANN",sep="")
a_nn<-cbind(a_nn.model,a_nn)
colnames(a_nn)<-colnames(ae_predict)
ae_predict<-rbind(ae_predict,a_nn)
pred_nn.model<-paste(ae_grid@summary_table[i,1],"ANN",sep="")
pred_nn_class<-cbind(pred_nn.model,t(pred_nn))
colnames(pred_nn_class)<-colnames(class_result)
class_result<-rbind(class_result,pred_nn_class)
##Stacked model
#combine all the predictions of above classifiers
combo<-data.frame(pred,pred_rf,pred_knn,pred_nn,label=deep.fea.test$label)
fit_stacked<-caret::train(as.factor(label)~.,
combo,
method="ranger",
metric="Accuracy")
pred_stacked<-predict(fit_stacked,deep.fea.test$label)
pred_stacked<-as.vector(pred_stacked)
deep.fea.test$label<-as.vector(deep.fea.test$label)
stacked_accuracy<-Accuracy(pred_stacked,deep.fea.test$label)
stacked_AUC<-AUC(as.numeric(pred_stacked),as.numeric(deep.fea.test$label))
stacked_F1<-F1_Score(as.numeric(deep.fea.test$label),as.numeric(pred_stacked))
stacked_PRAUC<-PRAUC(as.numeric(pred_stacked),as.numeric(deep.fea.test$label))
stacked_MCC<-adjustmcc(as.numeric(deep.fea.test$label),as.numeric(pred_stacked),cutoff=1)
stacked_sensitivity<-Sensitivity(deep.fea.test$label,pred_stacked)
stacked_specific<-Specificity(deep.fea.test$label,pred_stacked)
stacked_classloss<-ZeroOneLoss(deep.fea.test$label,pred_stacked)
#add model rf prediction score to class_result and ae_predict
a_stacked<-as.data.frame(t(c(stacked_AUC,stacked_PRAUC,stacked_accuracy,stacked_F1,stacked_MCC,stacked_sensitivity,stacked_specific,stacked_classloss)))
a_stacked<-as.data.frame(round(a_stacked,4))
a_stacked.model<-paste(ae_grid@summary_table[i,1],"stacked_model",sep="")
a_stacked<-cbind(a_stacked.model,a_stacked)
colnames(a_stacked)<-colnames(ae_predict)
ae_predict<-rbind(ae_predict,a_stacked)
pred_stacked.model<-paste(ae_grid@summary_table[i,1],"stacked_model",sep="")
pred_stacked<-cbind(pred_stacked.model,t(pred_stacked))
colnames(pred_stacked)<-colnames(class_result)
class_result<-rbind(class_result,pred_stacked)
}
write.csv(class_result,file="HR_FLAG.csv")
write.csv(ae_predict,file="model_predict_score.csv")
| /UAMS_SURVIVAL.R | no_license | guanhaibin/MM-challenge | R | false | false | 15,571 | r | install.packages('gbm')
install.packages("MESS") #auc
library(MESS)
library(gbm)
#Read data in R and preparation
setwd("U:/hguan003/MM")
Gene_expression=read.csv("GSE24080UAMSentrezIDlevel.csv",header=T,sep=",",row.names=1)
clinical<-read.csv("globalClinTraining.csv",header=T,sep=",",row.names = 2,stringsAsFactors = FALSE)
a<-c("GSE24080UAMS","EMTAB4032","HOVON65")
clinical<-subset(clinical,Study%in%a)
clinical<-subset(clinical[,c("Study","D_Age","D_PFS","D_PFS_FLAG","D_ISS","HR_FLAG")])
clinical$Patient<-rownames(clinical)
clinical<-clinical[c("D_Age","D_ISS","Study","Patient","D_PFS","D_PFS_FLAG","HR_FLAG")]
clinical$D_Age<-clinical$D_Age/100
clinical$D_ISS<-clinical$D_ISS/10
clinical$D_PFS<-clinical$D_PFS/30.5
clinical_UAMS<-subset(clinical,Study=="GSE24080UAMS")
clinical_UAMS[clinical_UAMS[,"HR_FLAG"]==TRUE,7]=1
clinical_UAMS[clinical_UAMS[,"HR_FLAG"]==FALSE,7]=0
train_data=as.data.frame(t(Gene_expression))
train_data<-as.data.frame(scale(train_data))
train_data<-merge(train_data,clinical_UAMS[,c("D_Age","D_ISS","Study","Patient","D_PFS","D_PFS_FLAG","HR_FLAG")],by="row.names",all.x=TRUE)
row.names(train_data)<-train_data[,1]
train_data<-train_data[-c(1)]
library(unbalanced)
n<-ncol(train_data)
output<-as.factor(train_data[,n])
input<-train_data[,-((n):(n-4))]
data<-ubSMOTE(X=input,Y=output)
newdat<-cbind(data$X,data$Y)
colnames(newdat)[ncol(newdat)]<-'HR_FLAG'
##differential expression with limma package
library(limma)
f<-factor(paste(newdat$HR_FLAG,sep=""))
design<--model.matrix(~f)
colnames(design)<-levels(f)
fit<-lmFit(t(newdat[,1:(ncol(newdat)-3)]),design)
efit<-eBayes(fit)
limma_gene<-toptable(efit,coef=2,number=10000,p.value=0.001)
#write.csv(limma_gene,file="UAMS_limma_gene.csv")
##Based on the selected gene set, get a data set of original samples with survival outcome for survival analysis
limma_data<-train_data[,c(rownames(limma_gene),"D_Age","D_ISS","D_PFS","D_PFS_FLAG")]
##modify Gene entrez ID as "DXXX"
colnames(limma_data)[1:(ncol(limma_data)-4)]<-paste('D',sep='',colnames(limma_data)[1:(ncol(limma_data)-4)])
gene_feature<-function(data){
feature=''
{for (i in 1: nrow(data)) {feature=paste(feature,colnames(data)[i],'+')}}
feature=substr(feature,1,nchar(feature)-1)
return(feature)
}
survival_formula<-formula(paste('Surv(','D_PFS',',','D_PFS_FLAG',') ~',' D_Age + D_ISS +',gene_feature(limma_data[,1:(ncol(limma_data)-4)])))
library(ranger)
library(survival)
survival_model<-ranger(survival_formula,data=limma_data,seed=2234,importance = 'permutation',mtry=2,verbose=T,num.trees=50,write.forest=T)
sort(survival_model$variable.importance)
set.seed(222)
random_splits<-runif(nrow(limma_data))
train_MM<-limma_data[random_splits<0.7,]
test_MM<-limma_data[random_splits>=0.7,]
survival_model<-ranger(survival_formula,
data=train_MM,
seed=2234,
mtry=5,
verbose=T,
num.trees=50,
write.forest=T)
survival_predictions<-predict(survival_model,test_MM[,1:(ncol(limma_data)-2)])
#look at some posibilities of survival
#plot(survival_model$unique.death.times[1:4],survival_model$survival[1,1:4],col='orange',ylim=c(0.4,1))
##In order to align the survival and the classification models, we will focus on the probability of reaching event over the certain time
##We get the basic survival prediction using our test data and then we flip the probability of the period of choice and get the AUC score
limma<-train_data[,c(rownames(limma_gene),"D_Age","D_ISS","HR_FLAG")]
colnames(limma)[1:(ncol(limma)-3)]<-paste('D',sep='',colnames(limma)[1:(ncol(limma)-3)])
limma$HR_FLAG[363]=0
#GBM: Generalized Boosted Regression Model for classification
GBM_formula<-formula(paste("HR_FLAG~",' D_Age + D_ISS +',gene_feature(limma[,1:(ncol(limma)-3)])))
set.seed(1234)
gbm_model=gbm(GBM_formula,
data=limma,
distribution='bernoulli',
n.trees=4000, ##suggests between 3000 and 10000
interaction.depth = 3,
shrinkage=0.01, ##suggests small shirinkage, such between 0.01 and 0.001
bag.fraction=0.5,
keep.data=TURE,
cv.folds=5)
nTrees<-gbm.perf(gbm_model)
validate_predictions<-predict(gbm_model,newdata=test_MM,type='response',n.trees=nTrees)
#install.packages('pROC')
library(pROC)
roc(response=test_MM$HR_FLAG,predictor=test_MM[,1:144])
##NOw that both models can predict the same period and probablity of reaching the event, we ensemble both Survival and classification models
##Split to training/testing set
library(h2o)
h2o.init(nthreads=-1,max_mem_size = "16G",enable_assertions = FALSE)
total.hex<-as.h2o(train_data[,2:(ncol(train_data)-4)])
total.hex$label<-as.h2o(train_data[,(ncol(train_data)-1)])
splits<-h2o.splitFrame(total.hex,c(0.6,0.2),destination_frames=c("train","valid","test"),seed=1234)
train<-h2o.assign(splits[[1]],"train.hex")#60%
valid<-h2o.assign(splits[[2]],"valid.hex")#20%
test<-h2o.assign(splits[[3]],"test.hex")#20%
total_label<-as.vector(total.hex[,ncol(total.hex)])
train_label<-as.vector(train[,ncol(train)])
train[,ncol(train)]<-NULL
valid_label<-as.vector(valid[,ncol(valid)])
valid[,ncol(valid)]<-NULL
test_label<-as.vector(test[,ncol(test)])
test[,ncol(test)]<-NULL
total.hex[,ncol(total.hex)]<-NULL
hyper_params_ae<-list(
hidden=list(c(1000,100,1000),c(500)))
ae_grid<-h2o.grid(
algorithm="deeplearning",
grid_id = "ae_grid_id",
training_frame=total.hex,
epochs=10,
export_weights_and_biases = T,
ignore_const_cols = F,
autoencoder = T,
activation=c("Tanh"),
l1=1e-5,
l2=1e-5,
max_w2=10,
variable_importances = T,
hyper_params = hyper_params_ae
)
summary(ae_grid)
nmodel<-nrow(ae_grid@summary_table)
##create a dataframe to store prediction score for different model
ae_predict<-setNames(as.data.frame(matrix(ncol=9,nrow = 0)),c("model","AUC","PRAUC","Accuracy","F1_score","MCC","sensitivity","specific","classloss"))
Risk_Score<-as.data.frame(matrix(ncol=nrow(test)+1,nrow = 0))
class_result<-as.data.frame(matrix(ncol=nrow(test)+1,nrow = 0))
#function change label to 0 and 1 for calculate MMC
adjustmcc<-function(truth,predict,cutoff=1){
{for (i in 1:length(predict)) {if (predict[i]==-1 ){{predict[i]=0}}}}
{for (i in 1:length(truth)) {if (truth[i]==-1 ){{truth[i]=0}}}}
return(mcc(truth,predict,cutoff=1))
}
for (i in 1:nmodel) {
model<-h2o.getModel(ae_grid@model_ids[[i]])
fealayer<-(length(model@parameters$hidden)+1)/2
nfea<-model@parameters$hidden[fealayer]
deep.fea<-as.data.frame(h2o.deepfeatures( model,total.hex,layer=fealayer))
deep.fea$label<-as.character(total_label)
deep.fea.train<-as.data.frame(h2o.deepfeatures( model,train,layer=fealayer))
deep.fea.train$label<-as.character(train_label)
deep.fea.valid<-as.data.frame(h2o.deepfeatures(model,valid,layer=fealayer))
deep.fea.valid$label<-as.character(valid_label)
deep.fea.test<-as.data.frame(h2o.deepfeatures(model,test,layer=fealayer))
deep.fea.test$label<-as.character(test_label)
##SVM
library(e1071)
tc<-tune.control(cross=5)
svmtrain<-rbind(deep.fea.train,deep.fea.valid)
svmfit<-svm(svmtrain[,1:nfea],as.factor(svmtrain$label),tune.control=tc)
pred<-predict(svmfit,deep.fea.test[,1:nfea])
pred<-as.vector(pred)
deep.fea.test$label<-as.vector(deep.fea.test$label)
SVM_AUC<-MLmetrics::AUC(as.numeric(pred),as.numeric(deep.fea.test$label))
SVM_PRAUC<-PRAUC(as.numeric(pred),as.numeric(deep.fea.test$label))
SVM_accuracy<-Accuracy(pred,deep.fea.test$label)
SVM_F1<-F1_Score(as.numeric(deep.fea.test$label),as.numeric(pred))
SVM_MCC<-adjustmcc(as.numeric(deep.fea.test$label),as.numeric(pred),cutoff=1)
SVM_sensitivity<-Sensitivity(deep.fea.test$label,pred)
SVM_specific<-Specificity(deep.fea.test$label,pred)
SVM_classloss<-ZeroOneLoss(deep.fea.test$label,pred)
#add model svm prediction score to class_result and ae_predict
asvm<-as.data.frame(t(c(SVM_AUC,SVM_PRAUC,SVM_accuracy,SVM_F1,SVM_MCC,SVM_sensitivity,SVM_specific,SVM_classloss)))
asvm<-as.data.frame(round(asvm,4))
asvm.model<-paste(ae_grid@summary_table[i,1],"SVM",sep="")
asvm<-cbind(asvm.model,asvm)
colnames(asvm)<-colnames(ae_predict)
ae_predict<-rbind(ae_predict,asvm)
pred.model<-paste(ae_grid@summary_table[i,1],"SVM",sep="")
pred_class<-cbind(pred.model,t(pred))
colnames(pred_class)<-colnames(class_result)
class_result<-rbind(class_result,pred_class)
##random forest
library(ranger)
fitcontrol<-trainControl(method="repeatedcv",number=10,repeats=2)
RFtrain<-rbind(deep.fea.train,deep.fea.valid)
rffit<-caret:::train(label~.,
RFtrain,
method="ranger",
tuneGrid=expand.grid(
.mtry=2),
metric="Accuracy",
trControl=fitcontrol)
pred_rf<-predict(rffit,deep.fea.test)
pred_rf<-as.vector(pred_rf)
deep.fea.test$label<-as.vector(deep.fea.test$label)
rf_AUC<-AUC(as.numeric(pred_rf),as.numeric(deep.fea.test$label))
rf_accuracy<-Accuracy(pred_rf,deep.fea.test$label)
rf_F1<-F1_Score(as.numeric(deep.fea.test$label),as.numeric(pred_rf))
rf_PRAUC<-PRAUC(as.numeric(pred_rf),as.numeric(deep.fea.test$label))
rf_MCC<-adjustmcc(as.numeric(deep.fea.test$label),as.numeric(pred_rf),cutoff=1)
rf_sensitivity<-Sensitivity(deep.fea.test$label,pred_rf)
rf_specific<-Specificity(deep.fea.test$label,pred_rf)
rf_classloss<-ZeroOneLoss(deep.fea.test$label,pred_rf)
#add model rf prediction score to class_result and ae_predict
arf<-as.data.frame(t(c(rf_AUC,rf_PRAUC,rf_accuracy,rf_F1,rf_MCC,rf_sensitivity,rf_specific,rf_classloss)))
arf<-as.data.frame(round(arf,4))
arf.model<-paste(ae_grid@summary_table[i,1],"RF",sep="")
arf<-cbind(arf.model,arf)
colnames(arf)<-colnames(ae_predict)
ae_predict<-rbind(ae_predict,arf)
pred_rf.model<-paste(ae_grid@summary_table[i,1],"RF",sep="")
pred_rf_class<-cbind(pred_rf.model,t(pred_rf))
colnames(pred_rf_class)<-colnames(class_result)
class_result<-rbind(class_result,pred_rf_class)
##K nearest neighbor
knnfit<-caret::train(label~.,
RFtrain,
method="knn",
tuneGrid=expand.grid(
.k=5),
trControl=fitcontrol)
pred_knn<-predict(knnfit,deep.fea.test)
pred_knn<-as.vector(pred_knn)
deep.fea.test$label<-as.vector(deep.fea.test$label)
knn_accuracy<-Accuracy(pred_knn,deep.fea.test$label)
knn_AUC<-AUC(as.numeric(pred_knn),as.numeric(deep.fea.test$label))
knn_F1<-F1_Score(as.numeric(deep.fea.test$label),as.numeric(pred_knn))
knn_PRAUC<-PRAUC(as.numeric(pred_knn),as.numeric(deep.fea.test$label))
knn_MCC<-adjustmcc(as.numeric(deep.fea.test$label),as.numeric(pred_knn),cutoff=1)
knn_sensitivity<-Sensitivity(deep.fea.test$label,pred_knn)
knn_specific<-Specificity(deep.fea.test$label,pred_knn)
knn_classloss<-ZeroOneLoss(deep.fea.test$label,pred_knn)
#add model rf prediction score to class_result and ae_predict
aknn<-as.data.frame(t(c(knn_AUC,knn_PRAUC,knn_accuracy,knn_F1,knn_MCC,knn_sensitivity,knn_specific,knn_classloss)))
aknn<-as.data.frame(round(aknn,4))
aknn.model<-paste(ae_grid@summary_table[i,1],"KNN",sep="")
aknn<-cbind(aknn.model,aknn)
colnames(aknn)<-colnames(ae_predict)
ae_predict<-rbind(ae_predict,aknn)
pred_knn.model<-paste(ae_grid@summary_table[i,1],"KNN",sep="")
pred_knn_class<-cbind(pred_knn.model,t(pred_knn))
colnames(pred_knn_class)<-colnames(class_result)
class_result<-rbind(class_result,pred_knn_class)
#Multiple Paerceptron Network by Stachastic Gradient Descent
nn_Grid<-expand.grid(
.size=c(50,10,5),
.decay=0.00147)
nn_fit<-caret::train(label~.,
RFtrain,
method="nnet",
metric="Accuracy",
tuneGrid=nn_Grid,
MaxNWts=10000,
maxit=100,
trControl=fitcontrol,
trace=FALSE)
pred_nn<-predict(nn_fit,deep.fea.test)
pred_nn<-as.vector(pred_nn)
deep.fea.test$label<-as.vector(deep.fea.test$label)
nn_accuracy<-Accuracy(pred_nn,deep.fea.test$label)
nn_AUC<-AUC(as.numeric(pred_nn),as.numeric(deep.fea.test$label))
nn_F1<-F1_Score(as.numeric(deep.fea.test$label),as.numeric(pred_nn))
nn_PRAUC<-PRAUC(as.numeric(pred_nn),as.numeric(deep.fea.test$label))
nn_MCC<-adjustmcc(as.numeric(deep.fea.test$label),as.numeric(pred_nn),cutoff=1)
nn_sensitivity<-Sensitivity(deep.fea.test$label,pred_nn)
nn_specific<-Specificity(deep.fea.test$label,pred_nn)
nn_classloss<-ZeroOneLoss(deep.fea.test$label,pred_nn)
#add model rf prediction score to class_result and ae_predict
a_nn<-as.data.frame(t(c(nn_AUC,nn_PRAUC,nn_accuracy,nn_F1,nn_MCC,nn_sensitivity,nn_specific,nn_classloss)))
a_nn<-as.data.frame(round(a_nn,4))
a_nn.model<-paste(ae_grid@summary_table[i,1],"ANN",sep="")
a_nn<-cbind(a_nn.model,a_nn)
colnames(a_nn)<-colnames(ae_predict)
ae_predict<-rbind(ae_predict,a_nn)
pred_nn.model<-paste(ae_grid@summary_table[i,1],"ANN",sep="")
pred_nn_class<-cbind(pred_nn.model,t(pred_nn))
colnames(pred_nn_class)<-colnames(class_result)
class_result<-rbind(class_result,pred_nn_class)
##Stacked model
#combine all the predictions of above classifiers
combo<-data.frame(pred,pred_rf,pred_knn,pred_nn,label=deep.fea.test$label)
fit_stacked<-caret::train(as.factor(label)~.,
combo,
method="ranger",
metric="Accuracy")
pred_stacked<-predict(fit_stacked,deep.fea.test$label)
pred_stacked<-as.vector(pred_stacked)
deep.fea.test$label<-as.vector(deep.fea.test$label)
stacked_accuracy<-Accuracy(pred_stacked,deep.fea.test$label)
stacked_AUC<-AUC(as.numeric(pred_stacked),as.numeric(deep.fea.test$label))
stacked_F1<-F1_Score(as.numeric(deep.fea.test$label),as.numeric(pred_stacked))
stacked_PRAUC<-PRAUC(as.numeric(pred_stacked),as.numeric(deep.fea.test$label))
stacked_MCC<-adjustmcc(as.numeric(deep.fea.test$label),as.numeric(pred_stacked),cutoff=1)
stacked_sensitivity<-Sensitivity(deep.fea.test$label,pred_stacked)
stacked_specific<-Specificity(deep.fea.test$label,pred_stacked)
stacked_classloss<-ZeroOneLoss(deep.fea.test$label,pred_stacked)
#add model rf prediction score to class_result and ae_predict
a_stacked<-as.data.frame(t(c(stacked_AUC,stacked_PRAUC,stacked_accuracy,stacked_F1,stacked_MCC,stacked_sensitivity,stacked_specific,stacked_classloss)))
a_stacked<-as.data.frame(round(a_stacked,4))
a_stacked.model<-paste(ae_grid@summary_table[i,1],"stacked_model",sep="")
a_stacked<-cbind(a_stacked.model,a_stacked)
colnames(a_stacked)<-colnames(ae_predict)
ae_predict<-rbind(ae_predict,a_stacked)
pred_stacked.model<-paste(ae_grid@summary_table[i,1],"stacked_model",sep="")
pred_stacked<-cbind(pred_stacked.model,t(pred_stacked))
colnames(pred_stacked)<-colnames(class_result)
class_result<-rbind(class_result,pred_stacked)
}
write.csv(class_result,file="HR_FLAG.csv")
write.csv(ae_predict,file="model_predict_score.csv")
|
\name{news}
\title{Release information for wgaim}
\section{Changes in version 1.4-x}{
\subsection{README}{
\itemize{
\item Since this is the first documented NEWS release on the wgaim package
it contains new features that have been included over several
versions. In contrast the documented bug fixes are only recent.
}
}
\subsection{NEW FEATURES}{
\itemize{
\item{The argument \code{flanking} has been added to the QTL
plotting functions ro ensure that only flanking markers or
linked markers are plotted and highlighted on the linkage map}
\item The forward selection algorithm has been accelerated further
by smart matrix decomposition of the relationship matrix. Users
can expect around a 35\% reduction in computation time.
\item Outlier statistics and BLUPs can now be returned for any
iteration of the algorithm regardless of whether a
significant QTL is detected. This now allows easy access to
outlier statistics annd BLUPs for the first iteration when no QTL
are detected (see the \code{breakout} argument of \code{wgaim.asreml}.
\item The package now includes a PDF reference manual that is accessible by
navigating to the \code{"doc"} directory of the package. This can
be found on any operating system using the command
\code{> system.file("doc", package = "wgaim")}
The reference manual contains WGAIM theory and two thorough examples that show the
features of the package. It also contains a "casual walk through"
the package providing the user with a series of 5 steps to a successful wgaim
analysis.
\item The package now includes three fully documented phenotypic
and genotypic data sets for users to explore. Two of these three
have been used in the manual and scripts that follow the
examples in the manual are available under the "doc" directory of the package.
\item The package now provides very efficient whole genome QTL analysis of high
dimensional genetic marker data. All genetic marker data is passed
into \code{wgaim.asreml()} through the \code{"intervalObj"}
argument. Merging of genotypic and phenotypic data occurs within
\code{wgaim.asreml()}.
\item \code{wgaim.asreml()} has several new arguments related
to selection of QTL. The \code{"gen.type"} argument allows the user to
choose a whole genome marker analysis or whole genome mid-point
interval analysis from Verbyla et. al (2007). The \code{"method"} argument gives you the choice of placing
QTL in the fixed part of the linear mixed model as in Verbyla et.al
(2007) or the random part of model as in Verbyla et. al
(2012). Finally, the \code{"selection"} argument allows you to choose whether QTL selection
is based on whole genome interval outlier statistics or a two stage process of
using chromosome outlier statistics and then interval outlier
statistics.
\item A \code{"breakout"} argument is now also provided which allows
the user to breakout of the forward selection algorithm at any
stage. The current model along with any calculated QTL components are
all available for inspection.
\item All linkage map plotting functions can be subsetted by
predefined distances. This includes a list of distances as long as the
number of linkage groups plotted.
}
}
\subsection{BUG FIXES}{
\itemize{
\item Fixed a bug that caused \code{wgaim.asreml()} to bomb out if
the number of markers was less than the number of genotypes.
\item Fixed a bug that outputted warning messages regarding a
\code{NaN} calculation from \code{sqrt(vatilde)} in \code{qtl.pick()}.
\item Fixed a bug that caused wgaim to crash if \code{method =
"random"} was used with the new version of asreml.
\item Fixed a bug that caused wgaim to crash with very recent
versions of asreml (04/05/2015).
\item \code{cross2int()} now accepts R/qtl objects with cross type
\code{"bc","dh","riself"}.
\item Fixed an issue with the internal function \code{fix.map()} that
allowed some co-located sets of markers to appear in the final
reduced linkage map.
\item Fixed a long standing scoping issue with different versions of ASReml-R.
\item Fixed an elusive problem that causes wgaim models to increase the size
of your .RData upon saving. This is actually an inherent problem with
using model formula within a function a returning the subsequent
model. There is now a function at the very tail of
\code{wgaim.asreml()} that quietly destroys the useless environments
that these formula contain.
\item Fixed bug that caused \code{wgaim.asreml()} to crash when no QTL
were found.
\item Fixed bug that caused \code{summary.wgaim()} to crash when one
QTL was found using \code{method = "random"}.
}
}
}
| /inst/NEWS.Rd | no_license | alexwhan/wgaim | R | false | false | 4,959 | rd | \name{news}
\title{Release information for wgaim}
\section{Changes in version 1.4-x}{
\subsection{README}{
\itemize{
\item Since this is the first documented NEWS release on the wgaim package
it contains new features that have been included over several
versions. In contrast the documented bug fixes are only recent.
}
}
\subsection{NEW FEATURES}{
\itemize{
\item{The argument \code{flanking} has been added to the QTL
plotting functions ro ensure that only flanking markers or
linked markers are plotted and highlighted on the linkage map}
\item The forward selection algorithm has been accelerated further
by smart matrix decomposition of the relationship matrix. Users
can expect around a 35\% reduction in computation time.
\item Outlier statistics and BLUPs can now be returned for any
iteration of the algorithm regardless of whether a
significant QTL is detected. This now allows easy access to
outlier statistics annd BLUPs for the first iteration when no QTL
are detected (see the \code{breakout} argument of \code{wgaim.asreml}.
\item The package now includes a PDF reference manual that is accessible by
navigating to the \code{"doc"} directory of the package. This can
be found on any operating system using the command
\code{> system.file("doc", package = "wgaim")}
The reference manual contains WGAIM theory and two thorough examples that show the
features of the package. It also contains a "casual walk through"
the package providing the user with a series of 5 steps to a successful wgaim
analysis.
\item The package now includes three fully documented phenotypic
and genotypic data sets for users to explore. Two of these three
have been used in the manual and scripts that follow the
examples in the manual are available under the "doc" directory of the package.
\item The package now provides very efficient whole genome QTL analysis of high
dimensional genetic marker data. All genetic marker data is passed
into \code{wgaim.asreml()} through the \code{"intervalObj"}
argument. Merging of genotypic and phenotypic data occurs within
\code{wgaim.asreml()}.
\item \code{wgaim.asreml()} has several new arguments related
to selection of QTL. The \code{"gen.type"} argument allows the user to
choose a whole genome marker analysis or whole genome mid-point
interval analysis from Verbyla et. al (2007). The \code{"method"} argument gives you the choice of placing
QTL in the fixed part of the linear mixed model as in Verbyla et.al
(2007) or the random part of model as in Verbyla et. al
(2012). Finally, the \code{"selection"} argument allows you to choose whether QTL selection
is based on whole genome interval outlier statistics or a two stage process of
using chromosome outlier statistics and then interval outlier
statistics.
\item A \code{"breakout"} argument is now also provided which allows
the user to breakout of the forward selection algorithm at any
stage. The current model along with any calculated QTL components are
all available for inspection.
\item All linkage map plotting functions can be subsetted by
predefined distances. This includes a list of distances as long as the
number of linkage groups plotted.
}
}
\subsection{BUG FIXES}{
\itemize{
\item Fixed a bug that caused \code{wgaim.asreml()} to bomb out if
the number of markers was less than the number of genotypes.
\item Fixed a bug that outputted warning messages regarding a
\code{NaN} calculation from \code{sqrt(vatilde)} in \code{qtl.pick()}.
\item Fixed a bug that caused wgaim to crash if \code{method =
"random"} was used with the new version of asreml.
\item Fixed a bug that caused wgaim to crash with very recent
versions of asreml (04/05/2015).
\item \code{cross2int()} now accepts R/qtl objects with cross type
\code{"bc","dh","riself"}.
\item Fixed an issue with the internal function \code{fix.map()} that
allowed some co-located sets of markers to appear in the final
reduced linkage map.
\item Fixed a long standing scoping issue with different versions of ASReml-R.
\item Fixed an elusive problem that causes wgaim models to increase the size
of your .RData upon saving. This is actually an inherent problem with
using model formula within a function a returning the subsequent
model. There is now a function at the very tail of
\code{wgaim.asreml()} that quietly destroys the useless environments
that these formula contain.
\item Fixed bug that caused \code{wgaim.asreml()} to crash when no QTL
were found.
\item Fixed bug that caused \code{summary.wgaim()} to crash when one
QTL was found using \code{method = "random"}.
}
}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/numeric.summary.R
\name{numeric.summary}
\alias{numeric.summary}
\title{Numeric Summaries}
\usage{
numeric.summary(x, na.rm)
}
\arguments{
\item{x}{a numeric vector containing the values to summarize.}
\item{na.rm}{A logical indicating whether missing values should be removed.}
}
\value{
This function returns a \code{data.frame} including columns:
\itemize{
\item min
\item q1
\item mean
\item median
\item q3
\item iqr
\item stdev
\item max
\item skewness
\item skew
}
}
\description{
Summarises numeric data and returns a data frame containing the basic summary values.
}
\examples{
numeric.summary(iris$Sepal.Length)
numeric.summary(airquality$Wind, na.rm = FALSE)
}
\seealso{
\code{\link[base]{summary}}
}
\author{
Eva Szin Takacs, \email{szin.takacs.eva@gmail.com}
}
| /man/numeric.summary.Rd | no_license | szintakacseva/mlhelper | R | false | true | 904 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/numeric.summary.R
\name{numeric.summary}
\alias{numeric.summary}
\title{Numeric Summaries}
\usage{
numeric.summary(x, na.rm)
}
\arguments{
\item{x}{a numeric vector containing the values to summarize.}
\item{na.rm}{A logical indicating whether missing values should be removed.}
}
\value{
This function returns a \code{data.frame} including columns:
\itemize{
\item min
\item q1
\item mean
\item median
\item q3
\item iqr
\item stdev
\item max
\item skewness
\item skew
}
}
\description{
Summarises numeric data and returns a data frame containing the basic summary values.
}
\examples{
numeric.summary(iris$Sepal.Length)
numeric.summary(airquality$Wind, na.rm = FALSE)
}
\seealso{
\code{\link[base]{summary}}
}
\author{
Eva Szin Takacs, \email{szin.takacs.eva@gmail.com}
}
|
# bin phylo groups for Delgado
#clear environment, source paths, packages and functions.
rm(list=ls())
source('paths.r')
source('NEFI_functions/common_group_quantification.r')
library(data.table)
#set output paths.----
#output.path <- bahram_16S_common_phylo_fg_abun.path
output.path <- paste0(scc_gen_16S_dir,"prior_abundance_mapping/Delgado/delgado_16S_common_phylo_fg_abun.rds")
#load data.----
map <- read.csv(paste0(scc_gen_16S_dir,"prior_abundance_mapping/Delgado/delgado_metadata.csv"))
otu <- read.csv(paste0(scc_gen_16S_dir,"prior_abundance_mapping/Delgado/delgado_dominant_abundances.csv"))
tax <- read.csv(paste0(scc_gen_16S_dir,"prior_abundance_mapping/Delgado/delgado_tax.csv"))
tax_fun <- readRDS(paste0(pecan_gen_16S_dir, "reference_data/bacteria_tax_to_function.rds"))
# format tax table
rownames(tax) <- tax$Taxa
tax <- tax[,c(3:8)]
#colnames(tax) <- tolower(colnames(tax))
setnames(tax, "Phyla", "Phylum")
# format OTU table
colnames(otu) <- gsub("X", "site", colnames(otu))
rownames(otu) <- otu$Dominant_taxa_ID.ID_Environmental
otu$Dominant_taxa_ID.ID_Environmental <- NULL
otu <- as.data.frame(t(otu))
otu$other <- 10000 - rowSums(otu)
# create "other" column to get relative abundances right
tax <- rbind(tax, data.frame(Phylum = "other", Class = "other", Order = "other", Family = "other", Genus = "other", Species = "other"))
rownames(tax) <- c(rownames(tax[1:511,]), "other")
# assign function to taxonomy
pathway_names <- colnames(tax_fun)[3:15]
tax[, pathway_names] <- "other"
# taxon assignments
for (i in 1:length(pathway_names)) {
p <- pathway_names[i]
# Classifications from literature search (multiple taxon levels)
# I'm so sorry for anyone observing this nested for-loop in the future
has_pathway <- tax_fun[tax_fun[,p] == 1,]
levels <- c("Phylum", "Class", "Order", "Family", "Genus", "Species")
# levels <- c("phylum", "class", "order", "family", "genus", "species")
for (j in 1:length(levels)) {
taxon_level <- levels[j]
has_pathway_taxon_level <- has_pathway[has_pathway$Taxonomic.level==taxon_level,]
if (taxon_level == "Species") {
if(nrow(tax[which(paste(tax$Genus, tax$Species) %in% has_pathway_taxon_level$Taxon),]) > 0) {
tax[which(paste(tax$Genus, tax$Species) %in% has_pathway_taxon_level$Taxon),][,p] <- p
}
} else {
if (nrow(tax[tax[[taxon_level]] %in% has_pathway_taxon_level$Taxon,]) > 0){
tax[tax[[taxon_level]] %in% has_pathway_taxon_level$Taxon,][,p] <- p
}
}
}
}
#get each level of taxonomy output.----
of_interest <- colnames(tax)
all_taxa_out <- list()
for(i in 1:length(of_interest)){
all_taxa_out[[i]] <- common_group_quantification(otu,
tax,
unique(tax[,colnames(tax) == of_interest[i]]),
of_interest[i],
samp_freq = .95)
}
names(all_taxa_out) <- of_interest
#save output.----
saveRDS(all_taxa_out,output.path)
| /16S/data_construction/delgado/04._rarefy_bin_groups.r | permissive | saracg-forks/NEFI_microbe | R | false | false | 3,057 | r | # bin phylo groups for Delgado
#clear environment, source paths, packages and functions.
rm(list=ls())
source('paths.r')
source('NEFI_functions/common_group_quantification.r')
library(data.table)
#set output paths.----
#output.path <- bahram_16S_common_phylo_fg_abun.path
output.path <- paste0(scc_gen_16S_dir,"prior_abundance_mapping/Delgado/delgado_16S_common_phylo_fg_abun.rds")
#load data.----
map <- read.csv(paste0(scc_gen_16S_dir,"prior_abundance_mapping/Delgado/delgado_metadata.csv"))
otu <- read.csv(paste0(scc_gen_16S_dir,"prior_abundance_mapping/Delgado/delgado_dominant_abundances.csv"))
tax <- read.csv(paste0(scc_gen_16S_dir,"prior_abundance_mapping/Delgado/delgado_tax.csv"))
tax_fun <- readRDS(paste0(pecan_gen_16S_dir, "reference_data/bacteria_tax_to_function.rds"))
# format tax table
rownames(tax) <- tax$Taxa
tax <- tax[,c(3:8)]
#colnames(tax) <- tolower(colnames(tax))
setnames(tax, "Phyla", "Phylum")
# format OTU table
colnames(otu) <- gsub("X", "site", colnames(otu))
rownames(otu) <- otu$Dominant_taxa_ID.ID_Environmental
otu$Dominant_taxa_ID.ID_Environmental <- NULL
otu <- as.data.frame(t(otu))
otu$other <- 10000 - rowSums(otu)
# create "other" column to get relative abundances right
tax <- rbind(tax, data.frame(Phylum = "other", Class = "other", Order = "other", Family = "other", Genus = "other", Species = "other"))
rownames(tax) <- c(rownames(tax[1:511,]), "other")
# assign function to taxonomy
pathway_names <- colnames(tax_fun)[3:15]
tax[, pathway_names] <- "other"
# taxon assignments
for (i in 1:length(pathway_names)) {
p <- pathway_names[i]
# Classifications from literature search (multiple taxon levels)
# I'm so sorry for anyone observing this nested for-loop in the future
has_pathway <- tax_fun[tax_fun[,p] == 1,]
levels <- c("Phylum", "Class", "Order", "Family", "Genus", "Species")
# levels <- c("phylum", "class", "order", "family", "genus", "species")
for (j in 1:length(levels)) {
taxon_level <- levels[j]
has_pathway_taxon_level <- has_pathway[has_pathway$Taxonomic.level==taxon_level,]
if (taxon_level == "Species") {
if(nrow(tax[which(paste(tax$Genus, tax$Species) %in% has_pathway_taxon_level$Taxon),]) > 0) {
tax[which(paste(tax$Genus, tax$Species) %in% has_pathway_taxon_level$Taxon),][,p] <- p
}
} else {
if (nrow(tax[tax[[taxon_level]] %in% has_pathway_taxon_level$Taxon,]) > 0){
tax[tax[[taxon_level]] %in% has_pathway_taxon_level$Taxon,][,p] <- p
}
}
}
}
#get each level of taxonomy output.----
of_interest <- colnames(tax)
all_taxa_out <- list()
for(i in 1:length(of_interest)){
all_taxa_out[[i]] <- common_group_quantification(otu,
tax,
unique(tax[,colnames(tax) == of_interest[i]]),
of_interest[i],
samp_freq = .95)
}
names(all_taxa_out) <- of_interest
#save output.----
saveRDS(all_taxa_out,output.path)
|
# MAKE PLOTS OF DMS AND DMSP VS. PHYTO COUNTS AND ADDITIONAL Z VARIABLES
library(RColorBrewer)
library(dplyr)
library(tidyverse)
library(ggplot2)
# Load data
genpath <- '~/Desktop/GreenEdge/GCMS/'
pdir <- 'plots_pigments_vs_DMS_zColorScale/'
surf <- read.csv(file = paste0(genpath,'GE2016.casts.ALLSURF.csv'), header = T)
prof <- read.csv(file = paste0(genpath,'GE2016.profiles.ALL.OK.csv'), header = T)
# Exporting image?
exportimg <- T
opath <- "~/Desktop/GreenEdge/MS_DMS_GE16_Elementa/Fig_OWD_ARCvsATL/"
# ---------------------
pal <- colorRampPalette(brewer.pal(9, "Spectral")) # Color palette (Consistent with Matlab plots)
col <- pal(n = 21)[c(21,18,5)]
plotres <- 600 # resolution dpi
# ---------------------
# Replace NaN by NA
surf[is.nan(as.matrix(surf))] <- NA
# Remove data where no DMS or DMSPt are available
surf <- surf[!is.na(surf$dms) | !is.na(surf$dmspt),]
# Add MIZ classification by OWD
surf$OWD_zone = cut(surf$OWD, breaks = c(-35,-3.5,3.5,35), labels = c("ICE","MIZ","OW"))
# Add horizontal domain classification by clustering coefficient
surf$Domain = cut(surf$AW_ArW_clustering_coefficient, breaks = c(0,0.4,1), labels = c("Arctic","Atlantic"))
# Remove data with unknown Domain
surf <- surf[!is.na(surf$Domain),]
# # Hide data from stn 400
# surf[surf$stn<=400,] <- NA
# Decide if using 3-day or day SIC and wind speed (NOW USING DAILY MEAN DATA). Select flux variable
surf$wsp <- surf$wsp24
surf$SIC <- surf$SICday
fvar <- "fdmsW97c24"
# CORRECT FDMS FOR SIC
surf$fdms <- surf[,fvar] * (1 - surf$SIC)
# Remove rows where surface sulfur variables are not available
surf <- surf[!is.na(surf$dms) & !is.na(surf$fdms),] # !is.na(surf$idms_z60) & !is.na(surf$idmspt_z60) &
# Change units of vertical integrals
surf$idms_z60 <- surf$idms_z60 / 1000
surf$idmspt_z60 <- surf$idmspt_z60 / 1000
# --------------------------------------------------
# Calculate vertical integrals for putative Phaeocystis diagnostic pigments
# Exception for diagnostic pigments and ratios: replace NAs with zeros (= take into account, and plot, values below DL)
diapigs <- c("chlc3","but","hex","but19_like")
set2zero <- is.na(prof[,diapigs])
prof[,diapigs][set2zero] <- 0
# Repeat TChla integral from same station and different cast if not available for sulfur cast
for (cc in surf$stn) {
tmp <- surf[surf$stn==cc,"iTchla_z60"]
tmp[is.na(tmp)] <- mean(tmp, na.rm = T)
surf[surf$stn==cc,"iTchla_z60"] <- tmp
}
# View(surf[,c("stn","cast","iTchla_z60")]) # debug
for (vv in diapigs) {
newVar <- paste0("i",vv,"_z60")
surf[,newVar] <- NA
for (cc in surf$stn) {
xy <- prof[prof$stn==cc, c("depth",vv)]
xy <- xy[!duplicated(xy[,"depth"]),]
# if (cc == 512 & vv == "but19_like") { # debug
# print(xy)
# View(prof[,c("stn","cast","depth",vv)])
# }
if ( sum(!is.na(xy[ xy$depth<=60 , vv ])) >= 4 ) {
xy <- rbind(xy,c(100,0))
xyout <- approx(x = xy$depth, y = xy[,vv], xout = seq(0.5,99.5,1),
method = "linear", rule = 2, ties = mean)
surf[surf$stn==cc, newVar] <- sum(xyout$y[1:60], na.rm = T)
}
# if (cc == 512 & vv == "but19_like") { # debug
# print(sum(xyout$y[1:60], na.rm = T))
# }
}
# Add ratios: Phaeocystis proxies?
surf[,paste0("i",vv,"_2_tchla_z60")] <- surf[,newVar] / surf$iTchla_z60
}
# --------------------------------------------------
# FINAL PLOTTING FOR PAPER
# NOTE: I tried to put 4 variables into a single column and converting variable names to factors to be able to
# use facet_wrap to make the 4x4 plot matrix. It didn't work because all variables share the same y axis limits
# toplot <- list()
# for (svar in names(svarS)) {
# toplot[[svar]] <- data.frame(station=surf$station, OWD_zone=surf$OWD_zone, Domain=surf$Domain, OWD=surf$OWD, yvar=surf[[svar]], groupvar=svar)
# }
# toplot <- data.table::rbindlist(toplot, use.names = F, fill = F) # Nearly equivalent: toplot <- do.call("rbind", toplot)
# ...facet_wrap(vars(groupvar), labeller = labeller(yvariable = svarS))
yvarS <- list(icp_z60 = expression(paste(sum(c[p]),' (',m^-1,' m)')),
iTchla_z60 = expression(paste(sum(TChl),' ',italic(a),' (mg ',m^-2,')')),
idmspt_z60 = expression(paste(sum(DMSP[t]),' (mmol ',m^-2,')')),
idms_z60 = expression(paste(sum(DMS),' (mmol ',m^-2,')')),
dms = expression('<DMS> (nM)'), # BEFORE WAS: expression('<DMS>'[0-5]*' (nM)')
fdms = expression('F'[DMS]*' (µmol m'^-2*' d'^-1*')'),
# ichlc3_z60 = expression(paste(sum(Chlc3[0-60]),' (mg ',m^-2,')')),
# ibut_z60 = expression(paste(sum(But[0-60]),' (mg ',m^-2,')')),
# ihex_z60 = expression(paste(sum(Hex[0-60]),' (mg ',m^-2,')')),
# ibut19_like_z60 = expression(paste(sum(But-like[0-60]),' (mg ',m^-2,')')),
# ichlc3_2_tchla_z60 = expression(paste(sum(Chl_c3/TChl_a[0-60]),' (-)')),
# ibut_2_tchla_z60 = expression(paste(sum(But/TChl_a[0-60]),' (-)')),
# ihex_2_tchla_z60 = expression(paste(sum(Hex/TChl_a[0-60]),' (-)')),
ibut19_like_2_tchla_z60 = expression(paste(sum(But-like/TChl_a[0-60]),' (-)')))
surf$station <- as.character(surf$station)
for (yvar in names(yvarS)) {
par(mar = c(3,5,1,1))
toplot <- data.frame(station=surf$station, OWD_zone=surf$OWD_zone, Domain=surf$Domain, OWD=surf$OWD, yvar=surf[[yvar]])
# Remove duplicated rows
toplot <- toplot[!duplicated(toplot$station) & !duplicated(toplot$yvar) & !is.na(toplot$yvar),]
# Remove labels for selected y variables and conditions
if (yvar %in% c("icp_z60","iTchla_z60","idmspt_z60","idms_z60","dms","fdms")) {
toplot$station <- ifelse(toplot$yvar > quantile(toplot$yvar, 0.35, na.rm = T), # Max labels is quantile 0.2 just for FDMS
as.character(toplot$station), "")
}
p <- ggplot(toplot, aes(x=OWD, y=yvar, shape=Domain, colour=OWD_zone))
p + geom_point(size = 3) +
geom_text(aes(label=station), hjust=-0.3, vjust=0.2, show.legend = F, size = 12/4, check_overlap = T, color = "gray50") + # Setting size to x/4 is to maintain proportion with default ggplot of 15/4
scale_color_manual(values = col) +
scale_shape_manual(values = c(16,17)) +
xlim(c(-23,37)) +
xlab("Open water days") +
ylab(yvarS[[yvar]]) +
ylim(c(0, 1.05*max(toplot$yvar, na.rm = T))) +
theme_bw()
if (exportimg) {
ggsave(
filename = paste0(yvar,"_v2.png"),
plot = last_plot(),
device = NULL,
path = opath,
scale = 1.6,
width = 6.5,
height = 4,
units = "cm",
dpi = plotres
)
}
}
| /MS_DMS_GE16_Elementa/Fig_OWD_ARCvsATL/plot_owd_ARCvsATL.R | no_license | mgali/GreenEdge | R | false | false | 6,713 | r | # MAKE PLOTS OF DMS AND DMSP VS. PHYTO COUNTS AND ADDITIONAL Z VARIABLES
library(RColorBrewer)
library(dplyr)
library(tidyverse)
library(ggplot2)
# Load data
genpath <- '~/Desktop/GreenEdge/GCMS/'
pdir <- 'plots_pigments_vs_DMS_zColorScale/'
surf <- read.csv(file = paste0(genpath,'GE2016.casts.ALLSURF.csv'), header = T)
prof <- read.csv(file = paste0(genpath,'GE2016.profiles.ALL.OK.csv'), header = T)
# Exporting image?
exportimg <- T
opath <- "~/Desktop/GreenEdge/MS_DMS_GE16_Elementa/Fig_OWD_ARCvsATL/"
# ---------------------
pal <- colorRampPalette(brewer.pal(9, "Spectral")) # Color palette (Consistent with Matlab plots)
col <- pal(n = 21)[c(21,18,5)]
plotres <- 600 # resolution dpi
# ---------------------
# Replace NaN by NA
surf[is.nan(as.matrix(surf))] <- NA
# Remove data where no DMS or DMSPt are available
surf <- surf[!is.na(surf$dms) | !is.na(surf$dmspt),]
# Add MIZ classification by OWD
surf$OWD_zone = cut(surf$OWD, breaks = c(-35,-3.5,3.5,35), labels = c("ICE","MIZ","OW"))
# Add horizontal domain classification by clustering coefficient
surf$Domain = cut(surf$AW_ArW_clustering_coefficient, breaks = c(0,0.4,1), labels = c("Arctic","Atlantic"))
# Remove data with unknown Domain
surf <- surf[!is.na(surf$Domain),]
# # Hide data from stn 400
# surf[surf$stn<=400,] <- NA
# Decide if using 3-day or day SIC and wind speed (NOW USING DAILY MEAN DATA). Select flux variable
surf$wsp <- surf$wsp24
surf$SIC <- surf$SICday
fvar <- "fdmsW97c24"
# CORRECT FDMS FOR SIC
surf$fdms <- surf[,fvar] * (1 - surf$SIC)
# Remove rows where surface sulfur variables are not available
surf <- surf[!is.na(surf$dms) & !is.na(surf$fdms),] # !is.na(surf$idms_z60) & !is.na(surf$idmspt_z60) &
# Change units of vertical integrals
surf$idms_z60 <- surf$idms_z60 / 1000
surf$idmspt_z60 <- surf$idmspt_z60 / 1000
# --------------------------------------------------
# Calculate vertical integrals for putative Phaeocystis diagnostic pigments
# Exception for diagnostic pigments and ratios: replace NAs with zeros (= take into account, and plot, values below DL)
diapigs <- c("chlc3","but","hex","but19_like")
set2zero <- is.na(prof[,diapigs])
prof[,diapigs][set2zero] <- 0
# Repeat TChla integral from same station and different cast if not available for sulfur cast
for (cc in surf$stn) {
tmp <- surf[surf$stn==cc,"iTchla_z60"]
tmp[is.na(tmp)] <- mean(tmp, na.rm = T)
surf[surf$stn==cc,"iTchla_z60"] <- tmp
}
# View(surf[,c("stn","cast","iTchla_z60")]) # debug
for (vv in diapigs) {
newVar <- paste0("i",vv,"_z60")
surf[,newVar] <- NA
for (cc in surf$stn) {
xy <- prof[prof$stn==cc, c("depth",vv)]
xy <- xy[!duplicated(xy[,"depth"]),]
# if (cc == 512 & vv == "but19_like") { # debug
# print(xy)
# View(prof[,c("stn","cast","depth",vv)])
# }
if ( sum(!is.na(xy[ xy$depth<=60 , vv ])) >= 4 ) {
xy <- rbind(xy,c(100,0))
xyout <- approx(x = xy$depth, y = xy[,vv], xout = seq(0.5,99.5,1),
method = "linear", rule = 2, ties = mean)
surf[surf$stn==cc, newVar] <- sum(xyout$y[1:60], na.rm = T)
}
# if (cc == 512 & vv == "but19_like") { # debug
# print(sum(xyout$y[1:60], na.rm = T))
# }
}
# Add ratios: Phaeocystis proxies?
surf[,paste0("i",vv,"_2_tchla_z60")] <- surf[,newVar] / surf$iTchla_z60
}
# --------------------------------------------------
# FINAL PLOTTING FOR PAPER
# NOTE: I tried to put 4 variables into a single column and converting variable names to factors to be able to
# use facet_wrap to make the 4x4 plot matrix. It didn't work because all variables share the same y axis limits
# toplot <- list()
# for (svar in names(svarS)) {
# toplot[[svar]] <- data.frame(station=surf$station, OWD_zone=surf$OWD_zone, Domain=surf$Domain, OWD=surf$OWD, yvar=surf[[svar]], groupvar=svar)
# }
# toplot <- data.table::rbindlist(toplot, use.names = F, fill = F) # Nearly equivalent: toplot <- do.call("rbind", toplot)
# ...facet_wrap(vars(groupvar), labeller = labeller(yvariable = svarS))
yvarS <- list(icp_z60 = expression(paste(sum(c[p]),' (',m^-1,' m)')),
iTchla_z60 = expression(paste(sum(TChl),' ',italic(a),' (mg ',m^-2,')')),
idmspt_z60 = expression(paste(sum(DMSP[t]),' (mmol ',m^-2,')')),
idms_z60 = expression(paste(sum(DMS),' (mmol ',m^-2,')')),
dms = expression('<DMS> (nM)'), # BEFORE WAS: expression('<DMS>'[0-5]*' (nM)')
fdms = expression('F'[DMS]*' (µmol m'^-2*' d'^-1*')'),
# ichlc3_z60 = expression(paste(sum(Chlc3[0-60]),' (mg ',m^-2,')')),
# ibut_z60 = expression(paste(sum(But[0-60]),' (mg ',m^-2,')')),
# ihex_z60 = expression(paste(sum(Hex[0-60]),' (mg ',m^-2,')')),
# ibut19_like_z60 = expression(paste(sum(But-like[0-60]),' (mg ',m^-2,')')),
# ichlc3_2_tchla_z60 = expression(paste(sum(Chl_c3/TChl_a[0-60]),' (-)')),
# ibut_2_tchla_z60 = expression(paste(sum(But/TChl_a[0-60]),' (-)')),
# ihex_2_tchla_z60 = expression(paste(sum(Hex/TChl_a[0-60]),' (-)')),
ibut19_like_2_tchla_z60 = expression(paste(sum(But-like/TChl_a[0-60]),' (-)')))
surf$station <- as.character(surf$station)
for (yvar in names(yvarS)) {
par(mar = c(3,5,1,1))
toplot <- data.frame(station=surf$station, OWD_zone=surf$OWD_zone, Domain=surf$Domain, OWD=surf$OWD, yvar=surf[[yvar]])
# Remove duplicated rows
toplot <- toplot[!duplicated(toplot$station) & !duplicated(toplot$yvar) & !is.na(toplot$yvar),]
# Remove labels for selected y variables and conditions
if (yvar %in% c("icp_z60","iTchla_z60","idmspt_z60","idms_z60","dms","fdms")) {
toplot$station <- ifelse(toplot$yvar > quantile(toplot$yvar, 0.35, na.rm = T), # Max labels is quantile 0.2 just for FDMS
as.character(toplot$station), "")
}
p <- ggplot(toplot, aes(x=OWD, y=yvar, shape=Domain, colour=OWD_zone))
p + geom_point(size = 3) +
geom_text(aes(label=station), hjust=-0.3, vjust=0.2, show.legend = F, size = 12/4, check_overlap = T, color = "gray50") + # Setting size to x/4 is to maintain proportion with default ggplot of 15/4
scale_color_manual(values = col) +
scale_shape_manual(values = c(16,17)) +
xlim(c(-23,37)) +
xlab("Open water days") +
ylab(yvarS[[yvar]]) +
ylim(c(0, 1.05*max(toplot$yvar, na.rm = T))) +
theme_bw()
if (exportimg) {
ggsave(
filename = paste0(yvar,"_v2.png"),
plot = last_plot(),
device = NULL,
path = opath,
scale = 1.6,
width = 6.5,
height = 4,
units = "cm",
dpi = plotres
)
}
}
|
########################################
# Purpose: Runing a wavelet anaylsis
# Data: TreeHugger raw data: object called x with at least Date, Time, mm, Ch2 and Ch4 columns
# Date: 8/7/2017
# Author: Valentine Herrmann, HerrmannV@si.edu
# Reference paper : Herrmann et al. 2016. Tree Circumference Dynamics in Four Forests Characterized Using Automated Dendrometer Bands. PlosOne
#########################################
# Load libraries ####
library(WaveletComp)
library(circular)
# Load raw data ####
load("data_example.RData")
# Create TimeStamp ####
x$TimeStamp <- as.POSIXct(paste(x$Date, x$Time, sep = " "), format = "%d.%m.%Y %H:%M:%S")
x$Date <- as.Date(as.character(x$Date), format = "%d.%m.%Y")
# Calculate Band Temperature (NB: In our paper we used an aggregated temerature record, using measurements from all TreeHuggers at one site)
x$Band.Temp <- (1 / 298.15+( 1 / 3974 ) * log((x$Ch2*10000/(x$Ch4-x$Ch2)) / 10000 ))^ (-1) -273.15
# Calculate Spline and Residuals ####
lin.int <- as.data.frame(approx(x = x$TimeStamp, y = x$mm, xout = x$TimeStamp, rule = 2, method = "linear"))
colnames(lin.int) <- c("TimeStamp", "mm.int")
smoo <- smooth.spline(x = lin.int$TimeStamp, y = lin.int$mm.int, df = length(unique(x$Date)))
x$Spline <- ifelse(is.na(x$mm), NA, predict(smoo, as.numeric(x$TimeStamp))$y)
x$Residuals <- x$mm - x$Spline
# Wavelet analysis ####
## NB: In our paper, we removed rainy days for the wavelet analysis.
## On all days ####
x <- x[x$Date %in% unique(x$Date)[tapply(x$Residuals, x$Date, function(x) sum(!is.na(x)) == 96)],] # Filter for complete days
if (any(!is.na(x$Residuals))){
ts.x <- ts(x$Residuals, star = 1, frequency = (24 * 60/15)) # 96 measurements per day, 1 unit = 1 day
ts.y <- ts(x$Band.Temp, star = 1, frequency = (24 * 60/15)) # 96 measurements per day, 1 unit = 1 day but NA every 30 minutes because really we have one measurement per half-hour.
my.date = x$TimeStamp
my.data = data.frame(date = my.date, x = as.numeric(ts.x), y = as.numeric(ts.y))
my.wc = analyze.coherency(my.data, my.pair = c("x","y"),
loess.span = 1,
dt = 1/(24 * 60/15), # dj = 1/20,
lowerPeriod = 24/24,
upperPeriod = 25/24,
make.pval = T, n.sim = 100)
Period <- which((my.wc$Period - 1) == min(my.wc$Period - 1))
Coherence <- my.wc$Coherence[Period,]
Angle <- my.wc$Angle[Period,]
Coherence.70 <- Coherence > 0.70
Mean.Phase.Angle <- mean.circular(mean.circular(as.circular(Angle[Coherence.70], type= "angles", units = "radians", modulo = 'asis', zero = 0, rotation = 'counter', template = 'none')))
Mean.Coherence <- mean(Coherence)
Proportion.days.coh.70 <- sum(tapply(Coherence, x$Date, mean) > 0.70) / length(unique(x$Date))
}
Mean.Phase.Angle <- as.circular(Mean.Phase.Angle, type= "angles", units = "radians", modulo = 'asis', zero = 0, rotation = 'counter', template = 'none')
### circular plot
par(oma = c(0,0,0,0), mar = c(0,0,0,0))
res <- rose.diag(circular(0), bins = 4, prop = 0.75, col = "indianred1", cex = 1.8, shrink = 1.1)
res <- rose.diag(circular(pi/2), bins = 4, prop = 0.75, col = "indianred3", add = T, axes = F)
res <- rose.diag(circular(pi), bins = 4, prop = 0.75, col = "palegreen2", add = T, axes = F)
res <- rose.diag(circular(3*pi/2), bins = 4, prop = 0.75, col = "palegreen3", add = T, axes = F)
text(0.3,0.3, "In phase\ntree leading", cex = 1.5)
text(-0.3,-0.3, "Out of phase\ntree leading", cex = 1.5)
text(-0.3,0.3, "Out of phase\ntree lagging", cex = 1.5)
text(0.3,-0.3, "In phase\ntree lagging", cex = 1.5)
points.circular(plot.info = res, Mean.Phase.Angle, stack=FALSE, col = "chocolate", pch = 20, cex = 2)
## looking at each day separately ####
x <- x[x$Date %in% unique(x$Date)[tapply(x$Residuals,x$Date, function(x) sum(!is.na(x)) >= 72)],] #Filter for 75% complete days
if(nrow(x) >0){
m <- data.frame(Date = as.character(unique(x$Date)), Mean.Phase.Angle = NA, Mean.Coherence = NA, Proportion.coh.70 = NA)
for(d in as.character(unique(x$Date))){
print(d)
x1 <- x[x$Date == d,]
if (any(!is.na(x$Residuals))){
ts.x <- ts(x1$Residuals, star = 1, frequency = (24 * 60/15)) # 96 measurements per day, 1 unit = 1 day
ts.y <- ts(x1$Band.Temp, star = 1, frequency = (24 * 60/15)) # 96 measurements per day, 1 unit = 1 day but NA every 30 minutes because really we have one measurement per half-hour.
my.date = x1$TimeStamp
my.data = data.frame(date = my.date, x = as.numeric(ts.x), y = as.numeric(ts.y))
my.wc = analyze.coherency(my.data, my.pair = c("x","y"),
loess.span = 1,
dt = 1/(24 * 60/15), # dj = 1/20,
lowerPeriod = 24/24,
upperPeriod = 25/24,
make.pval = T, n.sim = 100)
# my.wc$Angle " This equals the difference of individual phases, Phase.x Phase.y, when converted to an angle in the interval [-pi; pi]. An absolute value less (larger) than =2 indicates that the two series move in phase (anti-phase, respectively) referring to the instantaneous time as time origin and at the frequency (or period) in question, while the sign of the phase difference shows which series is the leading one in this relationship. Figure 2 (in the style of a diagram by Aguiar-Conraria and Soares [2]) illustrates the range of possible phase differences and their interpretation. In line with this style, phase differences are displayed as arrows in the image plot of cross-wavelet power."
Period <- which((my.wc$Period - 1) == min(my.wc$Period - 1))
Coherence <- my.wc$Coherence[Period,]
Angle <- my.wc$Angle[Period,]
Coherence.70 <- all(Coherence > 0.70)
Mean.Phase.Angle <- ifelse(Coherence.70, mean.circular(mean.circular(as.circular(Angle, type= "angles", units = "radians", modulo = 'asis', zero = 0, rotation = 'counter', template = 'none'))), NA)
Mean.Coherence <- mean(Coherence)
Proportion.coh.70 <- sum(Coherence > 0.70) / length(Coherence)
m[m$Date == d, ]$Mean.Phase.Angle <- Mean.Phase.Angle
m[m$Date == d, ]$Mean.Coherence <- Mean.Coherence
m[m$Date == d, ]$Proportion.coh.70 <- Proportion.coh.70
}else{
m[m$Date == d, ]$Mean.Phase.Angle <- NA
m[m$Date == d, ]$Mean.Coherence <- NA
m[m$Date == d, ]$Proportion.coh.70 <- NA
}
}
}
m$Mean.Phase.Angle <- as.circular(m$Mean.Phase.Angle, type= "angles", units = "radians", modulo = 'asis', zero = 0, rotation = 'counter', template = 'none')
### circular histogram
plot(m$Mean.Phase.Angle, stack = FALSE, pch = 19, axes = F, ticks = F, bins = 9, cex = 2)
rose.diag(m$Mean.Phase.Angle, bins = 9, tcl.text = .3, cex = 1.5, prop = .9, ticks = F, add = T)
legend("topleft", paste("n =", sum(!is.na(m$Mean.Phase.Angle)), "days"), bty = "n")
| /R code/wavelet analysis/Wavelet_analysis_example_1_tree.R | no_license | EcoClimLab/AutoDendroBands | R | false | false | 7,278 | r | ########################################
# Purpose: Runing a wavelet anaylsis
# Data: TreeHugger raw data: object called x with at least Date, Time, mm, Ch2 and Ch4 columns
# Date: 8/7/2017
# Author: Valentine Herrmann, HerrmannV@si.edu
# Reference paper : Herrmann et al. 2016. Tree Circumference Dynamics in Four Forests Characterized Using Automated Dendrometer Bands. PlosOne
#########################################
# Load libraries ####
library(WaveletComp)
library(circular)
# Load raw data ####
load("data_example.RData")
# Create TimeStamp ####
x$TimeStamp <- as.POSIXct(paste(x$Date, x$Time, sep = " "), format = "%d.%m.%Y %H:%M:%S")
x$Date <- as.Date(as.character(x$Date), format = "%d.%m.%Y")
# Calculate Band Temperature (NB: In our paper we used an aggregated temerature record, using measurements from all TreeHuggers at one site)
x$Band.Temp <- (1 / 298.15+( 1 / 3974 ) * log((x$Ch2*10000/(x$Ch4-x$Ch2)) / 10000 ))^ (-1) -273.15
# Calculate Spline and Residuals ####
lin.int <- as.data.frame(approx(x = x$TimeStamp, y = x$mm, xout = x$TimeStamp, rule = 2, method = "linear"))
colnames(lin.int) <- c("TimeStamp", "mm.int")
smoo <- smooth.spline(x = lin.int$TimeStamp, y = lin.int$mm.int, df = length(unique(x$Date)))
x$Spline <- ifelse(is.na(x$mm), NA, predict(smoo, as.numeric(x$TimeStamp))$y)
x$Residuals <- x$mm - x$Spline
# Wavelet analysis ####
## NB: In our paper, we removed rainy days for the wavelet analysis.
## On all days ####
x <- x[x$Date %in% unique(x$Date)[tapply(x$Residuals, x$Date, function(x) sum(!is.na(x)) == 96)],] # Filter for complete days
if (any(!is.na(x$Residuals))){
ts.x <- ts(x$Residuals, star = 1, frequency = (24 * 60/15)) # 96 measurements per day, 1 unit = 1 day
ts.y <- ts(x$Band.Temp, star = 1, frequency = (24 * 60/15)) # 96 measurements per day, 1 unit = 1 day but NA every 30 minutes because really we have one measurement per half-hour.
my.date = x$TimeStamp
my.data = data.frame(date = my.date, x = as.numeric(ts.x), y = as.numeric(ts.y))
my.wc = analyze.coherency(my.data, my.pair = c("x","y"),
loess.span = 1,
dt = 1/(24 * 60/15), # dj = 1/20,
lowerPeriod = 24/24,
upperPeriod = 25/24,
make.pval = T, n.sim = 100)
Period <- which((my.wc$Period - 1) == min(my.wc$Period - 1))
Coherence <- my.wc$Coherence[Period,]
Angle <- my.wc$Angle[Period,]
Coherence.70 <- Coherence > 0.70
Mean.Phase.Angle <- mean.circular(mean.circular(as.circular(Angle[Coherence.70], type= "angles", units = "radians", modulo = 'asis', zero = 0, rotation = 'counter', template = 'none')))
Mean.Coherence <- mean(Coherence)
Proportion.days.coh.70 <- sum(tapply(Coherence, x$Date, mean) > 0.70) / length(unique(x$Date))
}
Mean.Phase.Angle <- as.circular(Mean.Phase.Angle, type= "angles", units = "radians", modulo = 'asis', zero = 0, rotation = 'counter', template = 'none')
### circular plot
par(oma = c(0,0,0,0), mar = c(0,0,0,0))
res <- rose.diag(circular(0), bins = 4, prop = 0.75, col = "indianred1", cex = 1.8, shrink = 1.1)
res <- rose.diag(circular(pi/2), bins = 4, prop = 0.75, col = "indianred3", add = T, axes = F)
res <- rose.diag(circular(pi), bins = 4, prop = 0.75, col = "palegreen2", add = T, axes = F)
res <- rose.diag(circular(3*pi/2), bins = 4, prop = 0.75, col = "palegreen3", add = T, axes = F)
text(0.3,0.3, "In phase\ntree leading", cex = 1.5)
text(-0.3,-0.3, "Out of phase\ntree leading", cex = 1.5)
text(-0.3,0.3, "Out of phase\ntree lagging", cex = 1.5)
text(0.3,-0.3, "In phase\ntree lagging", cex = 1.5)
points.circular(plot.info = res, Mean.Phase.Angle, stack=FALSE, col = "chocolate", pch = 20, cex = 2)
## looking at each day separately ####
x <- x[x$Date %in% unique(x$Date)[tapply(x$Residuals,x$Date, function(x) sum(!is.na(x)) >= 72)],] #Filter for 75% complete days
if(nrow(x) >0){
m <- data.frame(Date = as.character(unique(x$Date)), Mean.Phase.Angle = NA, Mean.Coherence = NA, Proportion.coh.70 = NA)
for(d in as.character(unique(x$Date))){
print(d)
x1 <- x[x$Date == d,]
if (any(!is.na(x$Residuals))){
ts.x <- ts(x1$Residuals, star = 1, frequency = (24 * 60/15)) # 96 measurements per day, 1 unit = 1 day
ts.y <- ts(x1$Band.Temp, star = 1, frequency = (24 * 60/15)) # 96 measurements per day, 1 unit = 1 day but NA every 30 minutes because really we have one measurement per half-hour.
my.date = x1$TimeStamp
my.data = data.frame(date = my.date, x = as.numeric(ts.x), y = as.numeric(ts.y))
my.wc = analyze.coherency(my.data, my.pair = c("x","y"),
loess.span = 1,
dt = 1/(24 * 60/15), # dj = 1/20,
lowerPeriod = 24/24,
upperPeriod = 25/24,
make.pval = T, n.sim = 100)
# my.wc$Angle " This equals the difference of individual phases, Phase.x Phase.y, when converted to an angle in the interval [-pi; pi]. An absolute value less (larger) than =2 indicates that the two series move in phase (anti-phase, respectively) referring to the instantaneous time as time origin and at the frequency (or period) in question, while the sign of the phase difference shows which series is the leading one in this relationship. Figure 2 (in the style of a diagram by Aguiar-Conraria and Soares [2]) illustrates the range of possible phase differences and their interpretation. In line with this style, phase differences are displayed as arrows in the image plot of cross-wavelet power."
Period <- which((my.wc$Period - 1) == min(my.wc$Period - 1))
Coherence <- my.wc$Coherence[Period,]
Angle <- my.wc$Angle[Period,]
Coherence.70 <- all(Coherence > 0.70)
Mean.Phase.Angle <- ifelse(Coherence.70, mean.circular(mean.circular(as.circular(Angle, type= "angles", units = "radians", modulo = 'asis', zero = 0, rotation = 'counter', template = 'none'))), NA)
Mean.Coherence <- mean(Coherence)
Proportion.coh.70 <- sum(Coherence > 0.70) / length(Coherence)
m[m$Date == d, ]$Mean.Phase.Angle <- Mean.Phase.Angle
m[m$Date == d, ]$Mean.Coherence <- Mean.Coherence
m[m$Date == d, ]$Proportion.coh.70 <- Proportion.coh.70
}else{
m[m$Date == d, ]$Mean.Phase.Angle <- NA
m[m$Date == d, ]$Mean.Coherence <- NA
m[m$Date == d, ]$Proportion.coh.70 <- NA
}
}
}
m$Mean.Phase.Angle <- as.circular(m$Mean.Phase.Angle, type= "angles", units = "radians", modulo = 'asis', zero = 0, rotation = 'counter', template = 'none')
### circular histogram
plot(m$Mean.Phase.Angle, stack = FALSE, pch = 19, axes = F, ticks = F, bins = 9, cex = 2)
rose.diag(m$Mean.Phase.Angle, bins = 9, tcl.text = .3, cex = 1.5, prop = .9, ticks = F, add = T)
legend("topleft", paste("n =", sum(!is.na(m$Mean.Phase.Angle)), "days"), bty = "n")
|
try( detach("package:fGWAS", unload=T) )
library(fGWAS)
#load genotype data
file.plink.bed = "/home/zw355/proj/gwas2/bmi-c1c2-qc2.bed"
file.plink.bim = "/home/zw355/proj/gwas2/bmi-c1c2-qc2.bim"
file.plink.fam = "/home/zw355/proj/gwas2/bmi-c1c2-qc2.fam"
obj.gen <- fg.load.plink( file.plink.bed, file.plink.bim, file.plink.fam, plink.command=NULL, chr=NULL, options=list())
obj.gen;
#load phenotype data
tb <- read.csv("/home/zw355/proj/gwas2/phe-cov-time-64.csv");
file.phe <- tempfile( fileext = ".csv")
file.phe.cov <- tempfile( fileext = ".csv")
file.phe.time <- tempfile( fileext = ".csv")
tb.y <- tb[,c("ID", "Y_1", "Y_2", "Y_3", "Y_4", "Y_5", "Y_6", "Y_7", "Y_8" )];
tb.y[,-1] <- log(tb.y[,-1])
write.csv(tb.y, file=file.phe, quote=F, row.names=F);
write.csv(tb[,c("ID", "Z_1", "Z_2", "Z_3", "Z_4", "Z_5", "Z_6", "Z_7", "Z_8" )], file=file.phe.time, quote=F, row.names=F);
write.csv(tb[,c("ID", "X_1", "X_2", "X_3", "X_4", "X_5", "X_6" )], file=file.phe.cov, quote=F, row.names=F);
obj.phe <- fg.load.phenotype( file.phe, file.phe.cov, file.phe.time );
obj.phe;
save(obj.phe, obj.gen, file="bmi.obj.phe.rdata");
obj.phe <- fg.data.estimate( obj.phe );
obj.phe;
library(fGWAS)
load("bmi.obj.phe.rdata");
obj.fast.rs770707 <- fg.snpscan( obj.gen, obj.phe, method="fast", snp.sub=c("rs770707"), curve.type="Legendre2", covariance.type="AR1", options=list(order=3, ncores=1))
obj.fast <- fg.snpscan( obj.gen, obj.phe, method="fast", snp.sub=c(1000:3000), covariance.type="AR1", options=list(order=3, ncores=20))
obj.fgwas <- fg.snpscan( obj.gen, obj.phe, snp.sub=c(1000:3000), covariance.type="AR1", options=list(order=3, ncores=20))
library(fGWAS)
load("bmi.obj.phe.rdata");
obj.phe$intercept=T
obj.fgwas <- fg.snpscan( obj.gen, obj.phe, method="fgwas", snp.sub=c(1:100), curve.type="Legendre2",covariance.type="AR1", options=list(order=3, ncores=10))
obj.optim <- fg.snpscan( obj.gen, obj.phe, method="optim-fgwas", snp.sub=c(1:100), curve.type="Legendre2",covariance.type="AR1", options=list(order=3, ncores=10))
tb.snps <- fg.select.sigsnp ( obj.optim, sig.level=0.05, pv.adjust="none" )
plot.fgwas.curve(obj.optim, tb.snps$INDEX, file.pdf="test.pdf");
library(fGWAS);
load("bmi.obj.phe.rdata");
obj.fgwas2 <- fg.snpscan( obj.gen, obj.phe, method="optim-fgwas", snp.sub=c(1:30, 100:130, 5001:5030), covariance.type="AR1", options=list(order=3, ncores=3))
obj.fgwas <- fg.snpscan( obj.gen, obj.phe, method="fgwas", snp.sub=c(1:30, 100:130, 5001:5030), covariance.type="AR1", options=list(order=3, ncores=3))
obj.fast <- fg.snpscan( obj.gen, obj.phe, method="fast", snp.sub=c(1:30, 100:130, 5001:5030) covariance.type="AR1", options=list(order=3, ncores=3))
obj.mixed <- fg.snpscan( obj.gen, obj.phe, method="mixed", snp.sub=c(1:30, 100:130, 5001:5030), covariance.type="AR1", options=list(order=3, ncores=3))
obj.gls <- fg.snpscan( obj.gen, obj.phe, method="gls", snp.sub=c(1:30, 100:130, 5001:5030), covariance.type="AR1", options=list(order=3, ncores=10))
| /test/fg_plink.R | no_license | ZWang-Lab/fGWAS | R | false | false | 3,030 | r |
try( detach("package:fGWAS", unload=T) )
library(fGWAS)
#load genotype data
file.plink.bed = "/home/zw355/proj/gwas2/bmi-c1c2-qc2.bed"
file.plink.bim = "/home/zw355/proj/gwas2/bmi-c1c2-qc2.bim"
file.plink.fam = "/home/zw355/proj/gwas2/bmi-c1c2-qc2.fam"
obj.gen <- fg.load.plink( file.plink.bed, file.plink.bim, file.plink.fam, plink.command=NULL, chr=NULL, options=list())
obj.gen;
#load phenotype data
tb <- read.csv("/home/zw355/proj/gwas2/phe-cov-time-64.csv");
file.phe <- tempfile( fileext = ".csv")
file.phe.cov <- tempfile( fileext = ".csv")
file.phe.time <- tempfile( fileext = ".csv")
tb.y <- tb[,c("ID", "Y_1", "Y_2", "Y_3", "Y_4", "Y_5", "Y_6", "Y_7", "Y_8" )];
tb.y[,-1] <- log(tb.y[,-1])
write.csv(tb.y, file=file.phe, quote=F, row.names=F);
write.csv(tb[,c("ID", "Z_1", "Z_2", "Z_3", "Z_4", "Z_5", "Z_6", "Z_7", "Z_8" )], file=file.phe.time, quote=F, row.names=F);
write.csv(tb[,c("ID", "X_1", "X_2", "X_3", "X_4", "X_5", "X_6" )], file=file.phe.cov, quote=F, row.names=F);
obj.phe <- fg.load.phenotype( file.phe, file.phe.cov, file.phe.time );
obj.phe;
save(obj.phe, obj.gen, file="bmi.obj.phe.rdata");
obj.phe <- fg.data.estimate( obj.phe );
obj.phe;
library(fGWAS)
load("bmi.obj.phe.rdata");
obj.fast.rs770707 <- fg.snpscan( obj.gen, obj.phe, method="fast", snp.sub=c("rs770707"), curve.type="Legendre2", covariance.type="AR1", options=list(order=3, ncores=1))
obj.fast <- fg.snpscan( obj.gen, obj.phe, method="fast", snp.sub=c(1000:3000), covariance.type="AR1", options=list(order=3, ncores=20))
obj.fgwas <- fg.snpscan( obj.gen, obj.phe, snp.sub=c(1000:3000), covariance.type="AR1", options=list(order=3, ncores=20))
library(fGWAS)
load("bmi.obj.phe.rdata");
obj.phe$intercept=T
obj.fgwas <- fg.snpscan( obj.gen, obj.phe, method="fgwas", snp.sub=c(1:100), curve.type="Legendre2",covariance.type="AR1", options=list(order=3, ncores=10))
obj.optim <- fg.snpscan( obj.gen, obj.phe, method="optim-fgwas", snp.sub=c(1:100), curve.type="Legendre2",covariance.type="AR1", options=list(order=3, ncores=10))
tb.snps <- fg.select.sigsnp ( obj.optim, sig.level=0.05, pv.adjust="none" )
plot.fgwas.curve(obj.optim, tb.snps$INDEX, file.pdf="test.pdf");
library(fGWAS);
load("bmi.obj.phe.rdata");
obj.fgwas2 <- fg.snpscan( obj.gen, obj.phe, method="optim-fgwas", snp.sub=c(1:30, 100:130, 5001:5030), covariance.type="AR1", options=list(order=3, ncores=3))
obj.fgwas <- fg.snpscan( obj.gen, obj.phe, method="fgwas", snp.sub=c(1:30, 100:130, 5001:5030), covariance.type="AR1", options=list(order=3, ncores=3))
obj.fast <- fg.snpscan( obj.gen, obj.phe, method="fast", snp.sub=c(1:30, 100:130, 5001:5030) covariance.type="AR1", options=list(order=3, ncores=3))
obj.mixed <- fg.snpscan( obj.gen, obj.phe, method="mixed", snp.sub=c(1:30, 100:130, 5001:5030), covariance.type="AR1", options=list(order=3, ncores=3))
obj.gls <- fg.snpscan( obj.gen, obj.phe, method="gls", snp.sub=c(1:30, 100:130, 5001:5030), covariance.type="AR1", options=list(order=3, ncores=10))
|
## Este script sive para representar las series temporales de la media anual de radiación en los distintos puntos donde están las estaciones de bsrn.
library(zoo)
library(lattice)
## DIFERENCIAS RELATIVAS ó DIFERENCIAS ABSOLUTAS EN RADIACION ZONAS CON EL SATÉLITE.
load("../../calc/regions/Dif_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_cno_sat_zonas.Rdata")
library(reshape2)
names(Dif_caer_sat_zonas) <- c("2003", "2004", "2005", "2006", "2007", "2008", "2009", "zonas")
aer <- melt(Dif_caer_sat_zonas, id.vars='zonas')
aer$model <- rep("aer", length(aer[,1]))
names(aer) <- c("zonas", "year", "rsds", "model")
names(Dif_cno_sat_zonas) <- c("2003", "2004", "2005", "2006", "2007", "2008", "2009", "zonas")
no_aer <- melt(Dif_cno_sat_zonas, id.vars='zonas')
no_aer$model <- rep("no-aer", length(no_aer[,1]))
names(no_aer) <- c("zonas", "year", "rsds", "model")
rsds_dif <- rbind(aer,no_aer)
xyplot(rsds~year|as.factor(zonas), group=model, data=rsds_dif, type='l', lwd=3, auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
rsds_dif$zonas <- rep(c("AFRE","AFRW", "MEDE", "EURS", "EURW","EURC","EURNE","BISL"),14)
myTheme <- custom.theme.2()
myTheme$strip.background$col <- 'transparent'
myTheme$strip.shingle$col <- 'transparent'
myTheme$superpose.symbol$pch <-c(20) #,8)
pdf("dif_model_sat_zonas.pdf", height=4, width=7)
xyplot(rsds~year|as.factor(zonas), group=model,data=rsds_dif, type=c('o','l'), lwd=1.5, auto.key=TRUE, par.settings=myTheme, scales=list(x=list(rot=45), y=list(rot=0, cex=0.8)), aspect=2/3, layout=c(4,2), grid=TRUE, ylab=expression('SSR difference ' (W/m^2)),
panel = function(...) {
# panel.grid()#col="grey", lwd=0.1, h=5, v=0)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
})
#)
dev.off()
## DIFERENCIAS RELATIVAS EN PRODUCTIVIDAD
load("../../calc/regions/Dif_rel_fixed_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_rel_fixed_cno_sat_zonas.Rdata")
names(Dif_rel_fixed_caer_sat_zonas) <- c("2003", "2004", "2005", "2006", "2007", "2008", "2009", "zonas")
names(Dif_rel_fixed_cno_sat_zonas) <- c("2003", "2004", "2005", "2006", "2007", "2008", "2009", "zonas")
caerfixed <- melt(Dif_rel_fixed_caer_sat_zonas, id.vars='zonas')
caerfixed$model <- rep("caer", length(caer[,1]))
names(caerfixed) <- c("zonas", "year", "yield", "model")
cnofixed <- melt(Dif_rel_fixed_cno_sat_zonas, id.vars='zonas')
cnofixed$model <- rep("cno", length(cno[,1]))
names(cnofixed) <- c("zonas", "year", "yield", "model")
fixed_dif <- rbind(caerfixed,cnofixed)
fixed_dif$zonas <- rep(c("AFRE","AFRW", "MEDE", "EURS", "EURW","EURC","EURNE","BISL"),14)
xyplot(yield~year|as.factor(zonas), group=model, data=fixed_dif, type='l', lwd=3, ylab='rel.dif', scales=list(rot=45), par.settings=myTheme, layout=c(2,4),grid=TRUE, auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
## Diferencias relativas en prod. one
load("../../calc/regions/Dif_one_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_one_cno_sat_zonas.Rdata")
load("../../calc/regions/sat_one_yearlyMean_zones.Rdata")
load("../../calc/regions/Dif_rel_one_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_rel_one_cno_sat_zonas.Rdata")
caerone <- melt(Dif_rel_one_caer_sat_zonas, id.vars='zonas')
caerone$model <- rep("caer", length(caerone[,1]))
names(caerone) <- c("zonas", "year", "yield", "model")
cnoone <- melt(Dif_rel_one_cno_sat_zonas, id.vars='zonas')
cnoone$model <- rep("cno", length(cnoone[,1]))
names(cnoone) <- c("zonas", "year", "yield", "model")
one_dif <- rbind(caerone,cnoone)
one_dif$zonas <- rep(c("AFRE","AFRW", "EMED", "EURS", "EURW","CNEUR","NEEUR","BISL"),14)
xyplot(yield~year|as.factor(zonas), group=model, data=one_dif, type='l', lwd=3, scales=list(rot=45), auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
## Diferencias relativas en prod two
load("../../calc/regions/Dif_two_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_two_cno_sat_zonas.Rdata")
load("../../calc/regions/sat_two_yearlyMean_zones.Rdata")
load("../../calc/regions/Dif_rel_two_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_rel_two_cno_sat_zonas.Rdata")
caertwo <- melt(Dif_rel_two_caer_sat_zonas, id.vars='zonas')
caertwo$model <- rep("caer", length(caertwo[,1]))
names(caertwo) <- c("zonas", "year", "yield", "model")
cnotwo <- melt(Dif_rel_two_cno_sat_zonas, id.vars='zonas')
cnotwo$model <- rep("cno", length(cnotwo[,1]))
names(cnotwo) <- c("zonas", "year", "yield", "model")
two_dif <- rbind(caertwo,cnotwo)
two_dif$zonas <- rep(c("AFRE","AFRW", "EMED", "EURS", "EURW","CNEUR","NEEUR","BISL"),14)
xyplot(yield~year|as.factor(zonas), group=model, data=two_dif, type='l', lwd=3, scales=list(rot=45), auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
## Diferencias relativas de CAER_ rsds y fixed-two-one
names(Dif_rel_caer_sat_zonas) <- names(Dif_rel_fixed_caer_sat_zonas)
dif_rsds <- melt(Dif_rel_caer_sat_zonas, id.vars='zonas')
dif_fixed <- melt(Dif_rel_fixed_caer_sat_zonas, id.vars='zonas')
dif_one <- melt(Dif_rel_one_caer_sat_zonas, id.vars='zonas')
dif_two <- melt(Dif_rel_two_caer_sat_zonas, id.vars='zonas')
dif_fixed$var <- rep("fixed", length(dif_rsds[,1]))
dif_rsds$var <- rep("rsds", length(dif_rsds[,1]))
dif_one$var <- rep("one", length(dif_rsds[,1]))
dif_two$var <- rep("two", length(dif_rsds[,1]))
names(dif_fixed) <- c("zonas", "year", "rel.dif", "var")
names(dif_rsds) <- c("zonas", "year", "rel.dif", "var")
names(dif_one) <- c("zonas", "year", "rel.dif", "var")
names(dif_two) <- c("zonas", "year", "rel.dif", "var")
rel_dif <- rbind(dif_rsds, dif_fixed, dif_one, dif_two)
rel_dif$zonas <- rep(c("AFRE","AFRW", "EMED", "EURS", "EURW","CNEUR","NEEUR","BISL"),14)
pdf("rel_dif_rsds_fixed2.pdf")
xyplot(rel.dif~year|as.factor(zonas), group=var, data=rel_dif, type='l', lwd=1.5, scales=list(rot=45), auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
## DIFERENCIAS ENTRE LAS DOS SIMULACIONES
load("../../calc/regions/Dif_rel_fixed_caer_cno_zonas.Rdata")
load("../../calc/regions/Dif_rel_one_sat_cno_zonas.Rdata")##esta guardado con nombre incorrecto, en realidad es caer_cno
load("../../calc/regions/Dif_rel_two_caer_cno_zonas.Rdata")
dif_fixed <- melt(Dif_rel_fixed_caer_cno_zonas, id.vars='zonas')
dif_one <- melt(Dif_rel_one_caer_cno_zonas, id.vars='zonas')
dif_two <- melt(Dif_rel_two_caer_cno_zonas, id.vars='zonas')
dif_fixed$var <- rep("fixed", length(dif_fixed[,1]))
dif_one$var <- rep("one", length(dif_one[,1]))
dif_two$var <- rep("two", length(dif_two[,1]))
names(dif_fixed) <- c("zonas", "year", "rel.dif", "var")
names(dif_one) <- c("zonas", "year", "rel.dif", "var")
names(dif_two) <- c("zonas", "year", "rel.dif", "var")
rel_dif <- rbind(dif_fixed, dif_one, dif_two)
rel_dif$zonas <- rep(c("1.AFRW","2.AFRE", "3.MEDE", "6.EURW", "5.EURS","7.EURC","4.EURE","8.BISL"),21)
pdf("rel_dif_types_caer_cno.pdf")
xyplot(rel.dif~year|as.factor(zonas), group=var, data=rel_dif, type='l', lwd=2, scales=list(rot=45), auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
| /sim20032009/figs/regions/anualSeries.R | no_license | ClaudiaGEscribano/aod_and_PV | R | false | false | 7,733 | r | ## Este script sive para representar las series temporales de la media anual de radiación en los distintos puntos donde están las estaciones de bsrn.
library(zoo)
library(lattice)
## DIFERENCIAS RELATIVAS ó DIFERENCIAS ABSOLUTAS EN RADIACION ZONAS CON EL SATÉLITE.
load("../../calc/regions/Dif_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_cno_sat_zonas.Rdata")
library(reshape2)
names(Dif_caer_sat_zonas) <- c("2003", "2004", "2005", "2006", "2007", "2008", "2009", "zonas")
aer <- melt(Dif_caer_sat_zonas, id.vars='zonas')
aer$model <- rep("aer", length(aer[,1]))
names(aer) <- c("zonas", "year", "rsds", "model")
names(Dif_cno_sat_zonas) <- c("2003", "2004", "2005", "2006", "2007", "2008", "2009", "zonas")
no_aer <- melt(Dif_cno_sat_zonas, id.vars='zonas')
no_aer$model <- rep("no-aer", length(no_aer[,1]))
names(no_aer) <- c("zonas", "year", "rsds", "model")
rsds_dif <- rbind(aer,no_aer)
xyplot(rsds~year|as.factor(zonas), group=model, data=rsds_dif, type='l', lwd=3, auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
rsds_dif$zonas <- rep(c("AFRE","AFRW", "MEDE", "EURS", "EURW","EURC","EURNE","BISL"),14)
myTheme <- custom.theme.2()
myTheme$strip.background$col <- 'transparent'
myTheme$strip.shingle$col <- 'transparent'
myTheme$superpose.symbol$pch <-c(20) #,8)
pdf("dif_model_sat_zonas.pdf", height=4, width=7)
xyplot(rsds~year|as.factor(zonas), group=model,data=rsds_dif, type=c('o','l'), lwd=1.5, auto.key=TRUE, par.settings=myTheme, scales=list(x=list(rot=45), y=list(rot=0, cex=0.8)), aspect=2/3, layout=c(4,2), grid=TRUE, ylab=expression('SSR difference ' (W/m^2)),
panel = function(...) {
# panel.grid()#col="grey", lwd=0.1, h=5, v=0)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
})
#)
dev.off()
## DIFERENCIAS RELATIVAS EN PRODUCTIVIDAD
load("../../calc/regions/Dif_rel_fixed_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_rel_fixed_cno_sat_zonas.Rdata")
names(Dif_rel_fixed_caer_sat_zonas) <- c("2003", "2004", "2005", "2006", "2007", "2008", "2009", "zonas")
names(Dif_rel_fixed_cno_sat_zonas) <- c("2003", "2004", "2005", "2006", "2007", "2008", "2009", "zonas")
caerfixed <- melt(Dif_rel_fixed_caer_sat_zonas, id.vars='zonas')
caerfixed$model <- rep("caer", length(caer[,1]))
names(caerfixed) <- c("zonas", "year", "yield", "model")
cnofixed <- melt(Dif_rel_fixed_cno_sat_zonas, id.vars='zonas')
cnofixed$model <- rep("cno", length(cno[,1]))
names(cnofixed) <- c("zonas", "year", "yield", "model")
fixed_dif <- rbind(caerfixed,cnofixed)
fixed_dif$zonas <- rep(c("AFRE","AFRW", "MEDE", "EURS", "EURW","EURC","EURNE","BISL"),14)
xyplot(yield~year|as.factor(zonas), group=model, data=fixed_dif, type='l', lwd=3, ylab='rel.dif', scales=list(rot=45), par.settings=myTheme, layout=c(2,4),grid=TRUE, auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
## Diferencias relativas en prod. one
load("../../calc/regions/Dif_one_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_one_cno_sat_zonas.Rdata")
load("../../calc/regions/sat_one_yearlyMean_zones.Rdata")
load("../../calc/regions/Dif_rel_one_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_rel_one_cno_sat_zonas.Rdata")
caerone <- melt(Dif_rel_one_caer_sat_zonas, id.vars='zonas')
caerone$model <- rep("caer", length(caerone[,1]))
names(caerone) <- c("zonas", "year", "yield", "model")
cnoone <- melt(Dif_rel_one_cno_sat_zonas, id.vars='zonas')
cnoone$model <- rep("cno", length(cnoone[,1]))
names(cnoone) <- c("zonas", "year", "yield", "model")
one_dif <- rbind(caerone,cnoone)
one_dif$zonas <- rep(c("AFRE","AFRW", "EMED", "EURS", "EURW","CNEUR","NEEUR","BISL"),14)
xyplot(yield~year|as.factor(zonas), group=model, data=one_dif, type='l', lwd=3, scales=list(rot=45), auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
## Diferencias relativas en prod two
load("../../calc/regions/Dif_two_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_two_cno_sat_zonas.Rdata")
load("../../calc/regions/sat_two_yearlyMean_zones.Rdata")
load("../../calc/regions/Dif_rel_two_caer_sat_zonas.Rdata")
load("../../calc/regions/Dif_rel_two_cno_sat_zonas.Rdata")
caertwo <- melt(Dif_rel_two_caer_sat_zonas, id.vars='zonas')
caertwo$model <- rep("caer", length(caertwo[,1]))
names(caertwo) <- c("zonas", "year", "yield", "model")
cnotwo <- melt(Dif_rel_two_cno_sat_zonas, id.vars='zonas')
cnotwo$model <- rep("cno", length(cnotwo[,1]))
names(cnotwo) <- c("zonas", "year", "yield", "model")
two_dif <- rbind(caertwo,cnotwo)
two_dif$zonas <- rep(c("AFRE","AFRW", "EMED", "EURS", "EURW","CNEUR","NEEUR","BISL"),14)
xyplot(yield~year|as.factor(zonas), group=model, data=two_dif, type='l', lwd=3, scales=list(rot=45), auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
## Diferencias relativas de CAER_ rsds y fixed-two-one
names(Dif_rel_caer_sat_zonas) <- names(Dif_rel_fixed_caer_sat_zonas)
dif_rsds <- melt(Dif_rel_caer_sat_zonas, id.vars='zonas')
dif_fixed <- melt(Dif_rel_fixed_caer_sat_zonas, id.vars='zonas')
dif_one <- melt(Dif_rel_one_caer_sat_zonas, id.vars='zonas')
dif_two <- melt(Dif_rel_two_caer_sat_zonas, id.vars='zonas')
dif_fixed$var <- rep("fixed", length(dif_rsds[,1]))
dif_rsds$var <- rep("rsds", length(dif_rsds[,1]))
dif_one$var <- rep("one", length(dif_rsds[,1]))
dif_two$var <- rep("two", length(dif_rsds[,1]))
names(dif_fixed) <- c("zonas", "year", "rel.dif", "var")
names(dif_rsds) <- c("zonas", "year", "rel.dif", "var")
names(dif_one) <- c("zonas", "year", "rel.dif", "var")
names(dif_two) <- c("zonas", "year", "rel.dif", "var")
rel_dif <- rbind(dif_rsds, dif_fixed, dif_one, dif_two)
rel_dif$zonas <- rep(c("AFRE","AFRW", "EMED", "EURS", "EURW","CNEUR","NEEUR","BISL"),14)
pdf("rel_dif_rsds_fixed2.pdf")
xyplot(rel.dif~year|as.factor(zonas), group=var, data=rel_dif, type='l', lwd=1.5, scales=list(rot=45), auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
## DIFERENCIAS ENTRE LAS DOS SIMULACIONES
load("../../calc/regions/Dif_rel_fixed_caer_cno_zonas.Rdata")
load("../../calc/regions/Dif_rel_one_sat_cno_zonas.Rdata")##esta guardado con nombre incorrecto, en realidad es caer_cno
load("../../calc/regions/Dif_rel_two_caer_cno_zonas.Rdata")
dif_fixed <- melt(Dif_rel_fixed_caer_cno_zonas, id.vars='zonas')
dif_one <- melt(Dif_rel_one_caer_cno_zonas, id.vars='zonas')
dif_two <- melt(Dif_rel_two_caer_cno_zonas, id.vars='zonas')
dif_fixed$var <- rep("fixed", length(dif_fixed[,1]))
dif_one$var <- rep("one", length(dif_one[,1]))
dif_two$var <- rep("two", length(dif_two[,1]))
names(dif_fixed) <- c("zonas", "year", "rel.dif", "var")
names(dif_one) <- c("zonas", "year", "rel.dif", "var")
names(dif_two) <- c("zonas", "year", "rel.dif", "var")
rel_dif <- rbind(dif_fixed, dif_one, dif_two)
rel_dif$zonas <- rep(c("1.AFRW","2.AFRE", "3.MEDE", "6.EURW", "5.EURS","7.EURC","4.EURE","8.BISL"),21)
pdf("rel_dif_types_caer_cno.pdf")
xyplot(rel.dif~year|as.factor(zonas), group=var, data=rel_dif, type='l', lwd=2, scales=list(rot=45), auto.key=TRUE,
panel = function(...) {
panel.grid(col="grey", lwd=0.1)
panel.abline(h=0, col='black', lwd=1)
panel.xyplot(...)
}
)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/exportToJson.R
\name{exportPersonToJson}
\alias{exportPersonToJson}
\title{exportPersonToJson}
\usage{
exportPersonToJson(
connectionDetails,
cdmDatabaseSchema,
resultsDatabaseSchema,
outputPath = getwd(),
vocabDatabaseSchema = cdmDatabaseSchema
)
}
\arguments{
\item{connectionDetails}{An R object of type ConnectionDetail (details for the function
that contains server info, database type, optionally
username/password, port)}
\item{cdmDatabaseSchema}{Name of the database schema that contains the vocabulary files}
\item{resultsDatabaseSchema}{of the database schema that contains the Achilles analysis files.
Default is cdmDatabaseSchema}
\item{outputPath}{folder location to save the JSON files. Default is current
working folder}
\item{vocabDatabaseSchema}{name of database schema that contains OMOP Vocabulary. Default is
cdmDatabaseSchema. On SQL Server, this should specifiy both the
database and the schema, so for example 'results.dbo'.}
}
\value{
none
}
\description{
\code{exportPersonToJson} Exports Achilles Person report into a JSON form for reports.
}
\details{
Creates individual files for Person report found in Achilles.Web
}
\examples{
\dontrun{
connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = "sql server",
server = "yourserver")
exportPersonToJson(connectionDetails,
cdmDatabaseSchema = "cdm4_sim",
outputPath = "your/output/path")
}
}
| /man/exportPersonToJson.Rd | permissive | mdsung/Achilles | R | false | true | 1,576 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/exportToJson.R
\name{exportPersonToJson}
\alias{exportPersonToJson}
\title{exportPersonToJson}
\usage{
exportPersonToJson(
connectionDetails,
cdmDatabaseSchema,
resultsDatabaseSchema,
outputPath = getwd(),
vocabDatabaseSchema = cdmDatabaseSchema
)
}
\arguments{
\item{connectionDetails}{An R object of type ConnectionDetail (details for the function
that contains server info, database type, optionally
username/password, port)}
\item{cdmDatabaseSchema}{Name of the database schema that contains the vocabulary files}
\item{resultsDatabaseSchema}{of the database schema that contains the Achilles analysis files.
Default is cdmDatabaseSchema}
\item{outputPath}{folder location to save the JSON files. Default is current
working folder}
\item{vocabDatabaseSchema}{name of database schema that contains OMOP Vocabulary. Default is
cdmDatabaseSchema. On SQL Server, this should specifiy both the
database and the schema, so for example 'results.dbo'.}
}
\value{
none
}
\description{
\code{exportPersonToJson} Exports Achilles Person report into a JSON form for reports.
}
\details{
Creates individual files for Person report found in Achilles.Web
}
\examples{
\dontrun{
connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = "sql server",
server = "yourserver")
exportPersonToJson(connectionDetails,
cdmDatabaseSchema = "cdm4_sim",
outputPath = "your/output/path")
}
}
|
# ---------------------------------------------------------------------
# Program: 3LatentMultiRegWithModerator100521.R
# Author: Steven M. Boker
# Date: Sat May 22 11:13:51 EDT 2010
#
# This program tests variations on a latent variable multiple regression
# using a standard RAM.
#
# ---------------------------------------------------------------------
# Revision History
# -- Sat May 22 11:13:51 EDT 2010
# Created 3LatentMultiRegWithModerator100521.R.
#
# ---------------------------------------------------------------------
# ----------------------------------
# Read libraries and set options.
library(OpenMx)
options(width=100)
# ---------------------------------------------------------------------
# Data for multiple regression of F3 on F1 and F2 with moderator variable Z.
numberSubjects <- 1000
numberIndicators <- 12
numberFactors <- 3
set.seed(10)
fixedBMatrixF <- matrix(c(.4, .2), 2, 1, byrow=TRUE)
randomBMatrixF <- matrix(c(.3, .5), 2, 1, byrow=TRUE)
XMatrixF <- matrix(rnorm(numberSubjects*2, mean=0, sd=1), numberSubjects, 2)
UMatrixF <- matrix(rnorm(numberSubjects*1, mean=0, sd=1), numberSubjects, 1)
Z <- matrix(floor(runif(numberSubjects, min=0, max=1.999)), nrow=numberSubjects, ncol=2)
XMatrix <- cbind(XMatrixF, XMatrixF %*% fixedBMatrixF + (XMatrixF*Z) %*% randomBMatrixF + UMatrixF)
BMatrix <- matrix(c( 1, .6, .7, .8, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, .5, .6, .7, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, .7, .6, .5), numberFactors, numberIndicators, byrow=TRUE)
UMatrix <- matrix(rnorm(numberSubjects*numberIndicators, mean=0, sd=1), numberSubjects, numberIndicators)
YMatrix <- XMatrix %*% BMatrix + UMatrix
cor(cbind(XMatrix,Z[,1]))
dimnames(YMatrix) <- list(NULL, paste("X", 1:numberIndicators, sep=""))
YMatrixDegraded <- YMatrix
YMatrixDegraded[runif(length(c(YMatrix)), min=0.1, max=1.1) > 1] <- NA
latentMultiRegModerated1 <- data.frame(YMatrixDegraded,Z=Z[,1])
round(cor(latentMultiRegModerated1), 3)
round(cov(latentMultiRegModerated1), 3)
latentMultiRegModerated1$Z <- latentMultiRegModerated1$Z - mean(latentMultiRegModerated1$Z)
numberFactors <- 3
numberIndicators <- 12
numberModerators <- 1
indicators <- paste("X", 1:numberIndicators, sep="")
moderators <- c("Z")
totalVars <- numberIndicators + numberFactors + numberModerators
# ----------------------------------
# Build an orthogonal simple structure factor model
latents <- paste("F", 1:numberFactors, sep="")
uniqueLabels <- paste("U_", indicators, sep="")
meanLabels <- paste("M_", latents, sep="")
factorVarLabels <- paste("Var_", latents, sep="")
latents1 <- latents[1]
indicators1 <- indicators[1:4]
loadingLabels1 <- paste("b_F1", indicators[1:4], sep="")
latents2 <- latents[2]
indicators2 <- indicators[5:8]
loadingLabels2 <- paste("b_F2", indicators[5:8], sep="")
latents3 <- latents[3]
indicators3 <- indicators[9:12]
loadingLabels3 <- paste("b_F3", indicators[9:12], sep="")
# ----------------------------------
# Create model with both direct and moderated paths
threeLatentWithModerator <- mxModel("threeLatentWithModerator",
type="RAM",
manifestVars=c(indicators),
latentVars=c(latents, "dummy1"),
mxPath(from=latents1, to=indicators1,
arrows=1, connect="all.pairs",
free=TRUE, values=.2,
labels=loadingLabels1),
mxPath(from=latents2, to=indicators2,
arrows=1, connect="all.pairs",
free=TRUE, values=.2,
labels=loadingLabels2),
mxPath(from=latents3, to=indicators3,
arrows=1, connect="all.pairs",
free=TRUE, values=.2,
labels=loadingLabels3),
mxPath(from=latents1, to=indicators1[1],
arrows=1,
free=FALSE, values=1),
mxPath(from=latents2, to=indicators2[1],
arrows=1,
free=FALSE, values=1),
mxPath(from=latents3, to=indicators3[1],
arrows=1,
free=FALSE, values=1),
mxPath(from=indicators,
arrows=2,
free=TRUE, values=.8,
labels=uniqueLabels),
mxPath(from=latents,
arrows=2,
free=TRUE, values=.8,
labels=factorVarLabels),
mxPath(from=c("F1","F2"),to="F3",
arrows=1,
free=TRUE, values=.2, labels=c("b11", "b12")),
mxPath(from="F1",to="F2",
arrows=1,
free=TRUE, values=.1, labels=c("cF1F2")),
mxPath(from=c("F1","F2"),to="dummy1",
arrows=1,
free=TRUE, values=.2, labels=c("b21", "b22")),
mxPath(from="dummy1",to="F3",
arrows=1,
free=FALSE, labels="data.Z"),
mxPath(from="one", to=indicators,
arrows=1, free=FALSE, values=0),
mxPath(from="one", to=c(latents),
arrows=1, free=TRUE, values=.1,
labels=meanLabels),
mxData(observed=latentMultiRegModerated1, type="raw")
)
threeLatentWithModeratorOut <- mxRun(threeLatentWithModerator)
omxCheckCloseEnough(threeLatentWithModeratorOut$output$fit, 34129.54, .1)
| /inst/models/nightly/3LatentMultiRegWith2LevelModeratorAndMissing-c.R | permissive | falkcarl/OpenMx | R | false | false | 5,081 | r | # ---------------------------------------------------------------------
# Program: 3LatentMultiRegWithModerator100521.R
# Author: Steven M. Boker
# Date: Sat May 22 11:13:51 EDT 2010
#
# This program tests variations on a latent variable multiple regression
# using a standard RAM.
#
# ---------------------------------------------------------------------
# Revision History
# -- Sat May 22 11:13:51 EDT 2010
# Created 3LatentMultiRegWithModerator100521.R.
#
# ---------------------------------------------------------------------
# ----------------------------------
# Read libraries and set options.
library(OpenMx)
options(width=100)
# ---------------------------------------------------------------------
# Data for multiple regression of F3 on F1 and F2 with moderator variable Z.
numberSubjects <- 1000
numberIndicators <- 12
numberFactors <- 3
set.seed(10)
fixedBMatrixF <- matrix(c(.4, .2), 2, 1, byrow=TRUE)
randomBMatrixF <- matrix(c(.3, .5), 2, 1, byrow=TRUE)
XMatrixF <- matrix(rnorm(numberSubjects*2, mean=0, sd=1), numberSubjects, 2)
UMatrixF <- matrix(rnorm(numberSubjects*1, mean=0, sd=1), numberSubjects, 1)
Z <- matrix(floor(runif(numberSubjects, min=0, max=1.999)), nrow=numberSubjects, ncol=2)
XMatrix <- cbind(XMatrixF, XMatrixF %*% fixedBMatrixF + (XMatrixF*Z) %*% randomBMatrixF + UMatrixF)
BMatrix <- matrix(c( 1, .6, .7, .8, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, .5, .6, .7, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, .7, .6, .5), numberFactors, numberIndicators, byrow=TRUE)
UMatrix <- matrix(rnorm(numberSubjects*numberIndicators, mean=0, sd=1), numberSubjects, numberIndicators)
YMatrix <- XMatrix %*% BMatrix + UMatrix
cor(cbind(XMatrix,Z[,1]))
dimnames(YMatrix) <- list(NULL, paste("X", 1:numberIndicators, sep=""))
YMatrixDegraded <- YMatrix
YMatrixDegraded[runif(length(c(YMatrix)), min=0.1, max=1.1) > 1] <- NA
latentMultiRegModerated1 <- data.frame(YMatrixDegraded,Z=Z[,1])
round(cor(latentMultiRegModerated1), 3)
round(cov(latentMultiRegModerated1), 3)
latentMultiRegModerated1$Z <- latentMultiRegModerated1$Z - mean(latentMultiRegModerated1$Z)
numberFactors <- 3
numberIndicators <- 12
numberModerators <- 1
indicators <- paste("X", 1:numberIndicators, sep="")
moderators <- c("Z")
totalVars <- numberIndicators + numberFactors + numberModerators
# ----------------------------------
# Build an orthogonal simple structure factor model
latents <- paste("F", 1:numberFactors, sep="")
uniqueLabels <- paste("U_", indicators, sep="")
meanLabels <- paste("M_", latents, sep="")
factorVarLabels <- paste("Var_", latents, sep="")
latents1 <- latents[1]
indicators1 <- indicators[1:4]
loadingLabels1 <- paste("b_F1", indicators[1:4], sep="")
latents2 <- latents[2]
indicators2 <- indicators[5:8]
loadingLabels2 <- paste("b_F2", indicators[5:8], sep="")
latents3 <- latents[3]
indicators3 <- indicators[9:12]
loadingLabels3 <- paste("b_F3", indicators[9:12], sep="")
# ----------------------------------
# Create model with both direct and moderated paths
threeLatentWithModerator <- mxModel("threeLatentWithModerator",
type="RAM",
manifestVars=c(indicators),
latentVars=c(latents, "dummy1"),
mxPath(from=latents1, to=indicators1,
arrows=1, connect="all.pairs",
free=TRUE, values=.2,
labels=loadingLabels1),
mxPath(from=latents2, to=indicators2,
arrows=1, connect="all.pairs",
free=TRUE, values=.2,
labels=loadingLabels2),
mxPath(from=latents3, to=indicators3,
arrows=1, connect="all.pairs",
free=TRUE, values=.2,
labels=loadingLabels3),
mxPath(from=latents1, to=indicators1[1],
arrows=1,
free=FALSE, values=1),
mxPath(from=latents2, to=indicators2[1],
arrows=1,
free=FALSE, values=1),
mxPath(from=latents3, to=indicators3[1],
arrows=1,
free=FALSE, values=1),
mxPath(from=indicators,
arrows=2,
free=TRUE, values=.8,
labels=uniqueLabels),
mxPath(from=latents,
arrows=2,
free=TRUE, values=.8,
labels=factorVarLabels),
mxPath(from=c("F1","F2"),to="F3",
arrows=1,
free=TRUE, values=.2, labels=c("b11", "b12")),
mxPath(from="F1",to="F2",
arrows=1,
free=TRUE, values=.1, labels=c("cF1F2")),
mxPath(from=c("F1","F2"),to="dummy1",
arrows=1,
free=TRUE, values=.2, labels=c("b21", "b22")),
mxPath(from="dummy1",to="F3",
arrows=1,
free=FALSE, labels="data.Z"),
mxPath(from="one", to=indicators,
arrows=1, free=FALSE, values=0),
mxPath(from="one", to=c(latents),
arrows=1, free=TRUE, values=.1,
labels=meanLabels),
mxData(observed=latentMultiRegModerated1, type="raw")
)
threeLatentWithModeratorOut <- mxRun(threeLatentWithModerator)
omxCheckCloseEnough(threeLatentWithModeratorOut$output$fit, 34129.54, .1)
|
# Summarise all dataset and there overlap:
# - Fitness
# - Banding
# - Cognition wild
# - Eli Feeder
# - Cognition aviary
# - ornement
# - insect
# - predation
# - plumes
# -
#-------------------
# Pakages
#-------------------
library(knitr)
library(rmarkdown)
library(markdown)
library(data.table)
library("gridExtra")
library("dabestr")
#-------------------
# Folder
#-------------------
out="/Users/maximecauchoix/Documents/wild_cog_OF/results/overview/"
dir.create(out)
out_local='~/Documents/openfeeder/data/'
#-------------------
# Fitness
#-------------------
source('~/Documents/wild_cog_OF/Rscripts/tits_overview_fitness.R')
#-------------------
# OF Cognition
#-------------------
source('~/Documents/wild_cog_OF/Rscripts/tits_overview_OFcognition.R')
#-------------------
# Banding
#-------------------
#source('~/Documents/wild_cog_OF/Rscripts/band_clean_2018_19.R')
source('~/Documents/wild_cog_OF/Rscripts/OF_cleanBanding_2020.R')
#-------------------
# Injury
#-------------------
#-------------------
# Summary table
#-------------------
# fall alone
#-----------
# Nb individual all
DT <- as.data.table(b)
DT=DT[ind,list(N.ind=length(unique(BandNumber))), by="Year"]
dyi=as.data.frame(DT)
dy=dyi[order(dyi$Year),]
spe=c("Blue","Great","Marsh")
for (i in 1:length(spe))
{
DT <- as.data.table(b)
DT=DT[ind&b$Species==spe[i],list(N=length(unique(BandNumber))), by="Year"]
dyi=as.data.frame(DT)
dyi=dyi[order(dyi$Year),]
dy[[spe[i]]]=round((dyi$N/dy$N.ind)*100)
}
# plot
#-----
pdf(paste0(out_local,"Banding_Prop species by year .pdf"), height=5, width=6)
x <- barplot(t(as.matrix(dy[,c(3:5)])), col=c("blue","gold","brown"),
border=NA, xlim=c(0,8),names.arg=dy$Year,
ylab="%", xlab="Annee", col.axis = "White",col.lab="White")
text(x, dy$Blue-10, labels=round(dy$Blue), col="black")
text(x, dy$Blue+10, labels=round(dy$Great), col="black")
text(x, dy$Blue+dy$Great+2, labels=round(dy$Marsh), col="black")
dev.off()
# nb banded in fall each year
#----------------------------
# take only study sites and good species
ind=is.na(b$Nest.Number)&
b$Site %in% c("M1","C1","C4","BA","H4","H1","L1")&b$Year>2012&
b$Species %in% c("Blue","Great","Marsh")
# by year all capture
DT <- as.data.table(b)
DT=DT[ind,list(nb.capture.fall =.N), by="Year"]
dy=as.data.frame(DT)
dy=dy[order(dy$Year),]
# by year all capture
DT <- as.data.table(b)
DT=DT[ind,list(nb.individuals.fall=length(unique(BandNumber))), by="Year"]
dyi=as.data.frame(DT)
dyi=dyi[order(dyi$Year),]
dy$nb.individuals.fall=dyi$nb.individuals.fall
# nb nesting each year
#----------------------------
# nb nest occupied nesting
DT <- as.data.table(fi)
DT=DT[fi$eggORnot==1,list(n =.N), by="Year"]
dyi=as.data.frame(DT)
dyi=dyi[order(dyi$Year),]
dy$nb.nest.occupied.total=dyi$n[2:7]
# nb individuals nesting
DT <- as.data.table(fiB)
DT=DT[,list(n =.N), by="Year"]
dyi=as.data.frame(DT)
dyi=dyi[order(dyi$Year),]
dy$nb.nesting.individuals.total=dyi$n[2:7]
# overal fall banding and nesting
#----------------------------
# capture in fall and nesting the year before
n=1
for (y in 2013:2018){
dy$nb.capture.in.fall.nesting.previous.spring[n]=length(intersect(unique(b$BandNumber[b$Year==y&is.na(b$Nest.Number)]),fiB$bandNumber[fiB$Year==y]))
n=n+1
}
# capture in fall and nesting the year before
n=1
for (y in 2013:2018){
dy$nb.capture.in.fall.nesting.next.spring[n]=length(intersect(unique(b$BandNumber[b$Year==y&is.na(b$Nest.Number)]),fiB$bandNumber[fiB$Year==y+1]))
n=n+1
}
write.csv2(dy,paste0(out_local,"fall_spring_match.csv"),row.names = F)
# overal cogniton and fitness
#----------------------------
cf=data.table()
cf$species="All"
cf$nb.banded=length(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)]))
cf$nb.recordedOF=length(unique(coR$bandNumber))
cf$nb.cognition=length(unique(coco$bandNumber))
cf$nb.fitness.2018=length(unique(fiB$bandNumber[fiB$Year==2018]))
cf$nb.fitness.2019=length(unique(fiB$bandNumber[fiB$Year==2019]))
#cf$nb.ind.banded.recordedOF=length(intersect(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)]),coR$bandNumber))
#cf$nb.ind.banded.with.cognition=length(intersect(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)]),coco$bandNumber))
cf$nb.ind.cognition.fitness.2018=length(intersect(fiB$bandNumber[fiB$Year==2018],coco$bandNumber))
cf$nb.ind.cognition.fitness.2019=length(intersect(fiB$bandNumber[fiB$Year==2019],coco$bandNumber))
spe=unique(co$species)[c(3,1,2)]
for (i in 1:length(spe)){
c=data.table()
c$species=spe[i]
c$nb.banded=length(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)&b$Species==as.character(spe[i])]))
c$nb.recordedOF=length(unique(coR$bandNumber[coR$species==as.character(spe[i])]))
c$nb.cognition=length(unique(coco$bandNumber[coco$species==as.character(spe[i])]))
c$nb.fitness.2018=length(unique(fiB$bandNumber[fiB$Year==2018&fiB$Species==as.character(spe[i])]))
c$nb.fitness.2019=length(unique(fiB$bandNumber[fiB$Year==2019&fiB$Species==as.character(spe[i])]))
#c$nb.ind.banded.recordedOF=length(intersect(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)]),coR$bandNumber))
#c$nb.ind.banded.with.cognition=length(intersect(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)]),coco$bandNumber))
c$nb.ind.cognition.fitness.2018=length(intersect(fiB$bandNumber[fiB$Year==2018],coco$bandNumber[coco$species==as.character(spe[i])]))
c$nb.ind.cognition.fitness.2019=length(intersect(fiB$bandNumber[fiB$Year==2019],coco$bandNumber[coco$species==as.character(spe[i])]))
cf=rbind(cf,c)
}
write.csv2(cf,paste0(out_local,"fall_cognition_spring_match_2018-2019.csv"),row.names = F)
DT <- as.data.table(b)
DT=DT[ind,list(nbt =.N), by="Year,environement"]
desp=as.data.frame(DT)
desp=desp[order(desp$Year),]
#normalise
di$logTTC10=log(di$TTC10)
di$logTTC20=log(di$TTC20)
di$logTTC30=log(di$TTC30)
di$lognbts=log(di$nbts)
# loop on all variables
varnames=names(di)[c(13:37,39:45)+1]# +1 because I added bandNumber to check
print(paste("Nb of bird in fitness database",length(unique(fiB$bandNumber))))
print(paste(sum(unique(di$bandNumber) %in% unique(fiB$bandNumber)),"with fitness data"))
print(paste(sum(unique(di$bandNumber[di$species=="Great"]) %in% unique(fiB$bandNumber)),"Great with fitness data"))
print(paste(sum(unique(di$bandNumber[di$species=="Blue"]) %in% unique(fiB$bandNumber)),"Blue with fitness data"))
# mean by birds
DT <- as.data.table(fiB)
DT=DT[,list(nbY =.N,firstYear=min(Year),lastYear=max(Year),
Species=unique(Species),sex=unique(sex),
FledgeNb=mean(FledgeNb,na.rm=T),
EggNb=mean(EggNb,na.rm=T)), by="bandNumber"]
f=as.data.frame(DT)
# merge cog and fit
all=merge(di,f,by="bandNumber",all.x=F)
# new variables
all$learn="Learning"
all$learn[is.na(all$TTC10)]="Nolearning"
# models
#-------
# trial effect of all cognitive variables
#----------------------------------------
stat=list()
for (r in 1:length(varnames)){
ind=all$species=="Blue"&all$scenario=="30"
formF <- as.formula(paste0("FledgeNb~",varnames[r]))
formE <- as.formula(paste0("EggNb~",varnames[r]))
e=summary(lm(formF,data=all,subset=ind))
f=summary(lm(formE,data=all,subset=ind))
#store
statTemp=data.frame(variable=varnames[r],
pvalFledglings=round(f$coefficients[2,4],2),
pvalEggs=round(e$coefficients[2,4],2))
stat[[r]]=statTemp
}
statFinal=rbindlist(stat)
# exploration plots
#--------------------
# Nb fledgings learning or not
ind=all$species=="Blue"&all$scenario=="30"
estim<- dabest(
all[!is.na(all$FledgeNb)&ind,],learn,FledgeNb,idx=c("Learning","Nolearning"),
paired = FALSE
)
pdf(paste0(out_fit,"NbFledge_Learning Or not_blueTits_30.pdf"),height = 4,width = 4)
plot(estim,rawplot.ylabel="Nb fledging")
dev.off()
# Plot NbFledge_AccFi100
pdf(paste0(out_fit,"NbFledge_AccFi100_blueTits_30.pdf"))
ggplot(subset(all,ind), aes(y=FledgeNb, x=AccFi100)) +
geom_point(aes(colour=sex.y),size=6) + stat_smooth(method="lm", formula=y~x^2,aes(colour=sex.y))+ theme_bw()+
theme(text = element_text(size=18))+
ggtitle("Learning ON/OFF") +
ylab("Nb fledglings") + xlab("Accuracy last 100 trials")
dev.off()
# Plot AccPost50_10
pdf(paste0(out_fit,"NbFledge_AccPost50_10_blueTits_30.pdf"))
ggplot(subset(all,ind), aes(y=FledgeNb, x=AccPre50_10)) +
geom_point(aes(colour=sex.y),size=6) + stat_smooth(method="lm", formula=y~x^2)+ theme_bw()+
theme(text = element_text(size=18))+
ggtitle("Learning ON/OFF") +
ylab("Nb fledglings") + xlab("Accuracy post TTC")
dev.off()
# Plot AccFi30 nb egg
pdf(paste0(out_fit,"NbEgg_AccFi30_blueTits_30.pdf"))
ggplot(subset(all,ind), aes(y=EggNb, x=AccFi30)) +
geom_point(aes(colour=sex.y),size=6) + stat_smooth(method="lm", formula=y~x^2)+ theme_bw()+
theme(text = element_text(size=18))+
ggtitle("Learning ON/OFF") +
ylab("Nb eggs") + xlab("AccFi30")
dev.off()
#-------------------
# Winter nestcheck
#-------------------
wn=read.csv2(paste0(out_local,'winter_nest_check_2020.csv'))
ni=read.csv2(paste0(out_local,'NestBoxInformation.csv'))
ni$nest=toupper(substr(ni$name,1,4))
wn$nichoir=toupper(wn$nichoir)
diff=as.character(setdiff(ni$nest,wn$nichoir))
diffCast=diff[grep('H',diff)]
length(grep('H',ni$nest))
length(grep('H',wn$nichoir))
################################################################################
#-------------------
# Winter 2020 color combo for corelation with dominance !!!! NOW IN developped in DOM_main_2020.R
#------------------
# find last morpho info for each color for each site
# code color combo site
#---------------------
#from nest banding
b$SiteCorrect="Not a study site"
b$SiteCorrect[grep("H",b$Nest.Number)]="Castera"
b$SiteCorrect[grep("C",b$Nest.Number)]="Cescau"
b$SiteCorrect[grep("B",b$Nest.Number)]="Balacet"
b$SiteCorrect[grep("L",b$Nest.Number)]="Moulis" # same color combo
b$SiteCorrect[grep("M",b$Nest.Number)]="Moulis"
b$SiteCorrect[grep("G",b$Nest.Number)]="Galey"
#from winter banding
b$SiteCorrect[b$Site %in% c('C1','C4','C3','C5','C2','Castillon')]="Cescau"
b$SiteCorrect[b$Site %in% c('M1','L1','Aubert','Montegut','Ledar','AU')]="Moulis"
b$SiteCorrect[b$Site %in% c('BA')]="Balacet"
uSite=c("Cescau","Moulis","Balacet")
uSpe=c("Blue","Great","Marsh")
bcol=b[1,]
for (i in 1:length(uSite)){# loop on site
for (j in 1:length(uSpe)){ # loop on species
ind=b$SiteCorrect==uSite[i]&b$Species==uSpe[j]
uCol=unique(b$Color[ind]) # unique color combo
print(paste(uSite[i], uSpe[j]))
for (k in 1:length(uCol)){
indCol=ind&b$Color==uCol[k]
indColWing=indCol&!is.na(b$Wing.chord.num) # last morpho recorded
if (sum(indColWing,na.rm=T)>0 ) {
indCol=indColWing
}
lastCaptureDate=max(b$dateCorrected[which(indCol)])
goodLine=b[which(indCol&b$dateCorrected==lastCaptureDate),]
bcol=rbind(bcol,goodLine)
rm(indCol)
}
rm(ind)
}
}
bcol=bcol[2:dim(bcol)[1],c("BandNumber","Color","RFID.","Species","SiteCorrect","dateCorrected",
"Sex","Age","Wing.chord.num","Tarsus.num","Head.num","Photo","TagModif")]
bcol$Age[bcol$dateCorrected<"2019-03-01"]="+1a"
#------------------
# merge with patch
#------------------
patch=read.csv2(paste0(out_local,"Mesures patchs_2019.csv"),h=T,sep=";",
na.strings=c("?","","NA"))
patch$BandNumber=patch$Band.number
patch=patch[,c("BandNumber","Patch_head","Patch_cheek","Patch_tie")]
bcolpatch=merge(bcol,patch,by="BandNumber",sort=F,all.x=T)
# save
write.csv2(bcolpatch,paste0(out_local,"Color_banding.csv"),row.names = F)
| /tits_overview.R | no_license | mcauchoix/Rscripts | R | false | false | 11,641 | r | # Summarise all dataset and there overlap:
# - Fitness
# - Banding
# - Cognition wild
# - Eli Feeder
# - Cognition aviary
# - ornement
# - insect
# - predation
# - plumes
# -
#-------------------
# Pakages
#-------------------
library(knitr)
library(rmarkdown)
library(markdown)
library(data.table)
library("gridExtra")
library("dabestr")
#-------------------
# Folder
#-------------------
out="/Users/maximecauchoix/Documents/wild_cog_OF/results/overview/"
dir.create(out)
out_local='~/Documents/openfeeder/data/'
#-------------------
# Fitness
#-------------------
source('~/Documents/wild_cog_OF/Rscripts/tits_overview_fitness.R')
#-------------------
# OF Cognition
#-------------------
source('~/Documents/wild_cog_OF/Rscripts/tits_overview_OFcognition.R')
#-------------------
# Banding
#-------------------
#source('~/Documents/wild_cog_OF/Rscripts/band_clean_2018_19.R')
source('~/Documents/wild_cog_OF/Rscripts/OF_cleanBanding_2020.R')
#-------------------
# Injury
#-------------------
#-------------------
# Summary table
#-------------------
# fall alone
#-----------
# Nb individual all
DT <- as.data.table(b)
DT=DT[ind,list(N.ind=length(unique(BandNumber))), by="Year"]
dyi=as.data.frame(DT)
dy=dyi[order(dyi$Year),]
spe=c("Blue","Great","Marsh")
for (i in 1:length(spe))
{
DT <- as.data.table(b)
DT=DT[ind&b$Species==spe[i],list(N=length(unique(BandNumber))), by="Year"]
dyi=as.data.frame(DT)
dyi=dyi[order(dyi$Year),]
dy[[spe[i]]]=round((dyi$N/dy$N.ind)*100)
}
# plot
#-----
pdf(paste0(out_local,"Banding_Prop species by year .pdf"), height=5, width=6)
x <- barplot(t(as.matrix(dy[,c(3:5)])), col=c("blue","gold","brown"),
border=NA, xlim=c(0,8),names.arg=dy$Year,
ylab="%", xlab="Annee", col.axis = "White",col.lab="White")
text(x, dy$Blue-10, labels=round(dy$Blue), col="black")
text(x, dy$Blue+10, labels=round(dy$Great), col="black")
text(x, dy$Blue+dy$Great+2, labels=round(dy$Marsh), col="black")
dev.off()
# nb banded in fall each year
#----------------------------
# take only study sites and good species
ind=is.na(b$Nest.Number)&
b$Site %in% c("M1","C1","C4","BA","H4","H1","L1")&b$Year>2012&
b$Species %in% c("Blue","Great","Marsh")
# by year all capture
DT <- as.data.table(b)
DT=DT[ind,list(nb.capture.fall =.N), by="Year"]
dy=as.data.frame(DT)
dy=dy[order(dy$Year),]
# by year all capture
DT <- as.data.table(b)
DT=DT[ind,list(nb.individuals.fall=length(unique(BandNumber))), by="Year"]
dyi=as.data.frame(DT)
dyi=dyi[order(dyi$Year),]
dy$nb.individuals.fall=dyi$nb.individuals.fall
# nb nesting each year
#----------------------------
# nb nest occupied nesting
DT <- as.data.table(fi)
DT=DT[fi$eggORnot==1,list(n =.N), by="Year"]
dyi=as.data.frame(DT)
dyi=dyi[order(dyi$Year),]
dy$nb.nest.occupied.total=dyi$n[2:7]
# nb individuals nesting
DT <- as.data.table(fiB)
DT=DT[,list(n =.N), by="Year"]
dyi=as.data.frame(DT)
dyi=dyi[order(dyi$Year),]
dy$nb.nesting.individuals.total=dyi$n[2:7]
# overal fall banding and nesting
#----------------------------
# capture in fall and nesting the year before
n=1
for (y in 2013:2018){
dy$nb.capture.in.fall.nesting.previous.spring[n]=length(intersect(unique(b$BandNumber[b$Year==y&is.na(b$Nest.Number)]),fiB$bandNumber[fiB$Year==y]))
n=n+1
}
# capture in fall and nesting the year before
n=1
for (y in 2013:2018){
dy$nb.capture.in.fall.nesting.next.spring[n]=length(intersect(unique(b$BandNumber[b$Year==y&is.na(b$Nest.Number)]),fiB$bandNumber[fiB$Year==y+1]))
n=n+1
}
write.csv2(dy,paste0(out_local,"fall_spring_match.csv"),row.names = F)
# overal cogniton and fitness
#----------------------------
cf=data.table()
cf$species="All"
cf$nb.banded=length(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)]))
cf$nb.recordedOF=length(unique(coR$bandNumber))
cf$nb.cognition=length(unique(coco$bandNumber))
cf$nb.fitness.2018=length(unique(fiB$bandNumber[fiB$Year==2018]))
cf$nb.fitness.2019=length(unique(fiB$bandNumber[fiB$Year==2019]))
#cf$nb.ind.banded.recordedOF=length(intersect(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)]),coR$bandNumber))
#cf$nb.ind.banded.with.cognition=length(intersect(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)]),coco$bandNumber))
cf$nb.ind.cognition.fitness.2018=length(intersect(fiB$bandNumber[fiB$Year==2018],coco$bandNumber))
cf$nb.ind.cognition.fitness.2019=length(intersect(fiB$bandNumber[fiB$Year==2019],coco$bandNumber))
spe=unique(co$species)[c(3,1,2)]
for (i in 1:length(spe)){
c=data.table()
c$species=spe[i]
c$nb.banded=length(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)&b$Species==as.character(spe[i])]))
c$nb.recordedOF=length(unique(coR$bandNumber[coR$species==as.character(spe[i])]))
c$nb.cognition=length(unique(coco$bandNumber[coco$species==as.character(spe[i])]))
c$nb.fitness.2018=length(unique(fiB$bandNumber[fiB$Year==2018&fiB$Species==as.character(spe[i])]))
c$nb.fitness.2019=length(unique(fiB$bandNumber[fiB$Year==2019&fiB$Species==as.character(spe[i])]))
#c$nb.ind.banded.recordedOF=length(intersect(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)]),coR$bandNumber))
#c$nb.ind.banded.with.cognition=length(intersect(unique(b$BandNumber[b$Year==2018&is.na(b$Nest.Number)]),coco$bandNumber))
c$nb.ind.cognition.fitness.2018=length(intersect(fiB$bandNumber[fiB$Year==2018],coco$bandNumber[coco$species==as.character(spe[i])]))
c$nb.ind.cognition.fitness.2019=length(intersect(fiB$bandNumber[fiB$Year==2019],coco$bandNumber[coco$species==as.character(spe[i])]))
cf=rbind(cf,c)
}
write.csv2(cf,paste0(out_local,"fall_cognition_spring_match_2018-2019.csv"),row.names = F)
DT <- as.data.table(b)
DT=DT[ind,list(nbt =.N), by="Year,environement"]
desp=as.data.frame(DT)
desp=desp[order(desp$Year),]
#normalise
di$logTTC10=log(di$TTC10)
di$logTTC20=log(di$TTC20)
di$logTTC30=log(di$TTC30)
di$lognbts=log(di$nbts)
# loop on all variables
varnames=names(di)[c(13:37,39:45)+1]# +1 because I added bandNumber to check
print(paste("Nb of bird in fitness database",length(unique(fiB$bandNumber))))
print(paste(sum(unique(di$bandNumber) %in% unique(fiB$bandNumber)),"with fitness data"))
print(paste(sum(unique(di$bandNumber[di$species=="Great"]) %in% unique(fiB$bandNumber)),"Great with fitness data"))
print(paste(sum(unique(di$bandNumber[di$species=="Blue"]) %in% unique(fiB$bandNumber)),"Blue with fitness data"))
# mean by birds
DT <- as.data.table(fiB)
DT=DT[,list(nbY =.N,firstYear=min(Year),lastYear=max(Year),
Species=unique(Species),sex=unique(sex),
FledgeNb=mean(FledgeNb,na.rm=T),
EggNb=mean(EggNb,na.rm=T)), by="bandNumber"]
f=as.data.frame(DT)
# merge cog and fit
all=merge(di,f,by="bandNumber",all.x=F)
# new variables
all$learn="Learning"
all$learn[is.na(all$TTC10)]="Nolearning"
# models
#-------
# trial effect of all cognitive variables
#----------------------------------------
stat=list()
for (r in 1:length(varnames)){
ind=all$species=="Blue"&all$scenario=="30"
formF <- as.formula(paste0("FledgeNb~",varnames[r]))
formE <- as.formula(paste0("EggNb~",varnames[r]))
e=summary(lm(formF,data=all,subset=ind))
f=summary(lm(formE,data=all,subset=ind))
#store
statTemp=data.frame(variable=varnames[r],
pvalFledglings=round(f$coefficients[2,4],2),
pvalEggs=round(e$coefficients[2,4],2))
stat[[r]]=statTemp
}
statFinal=rbindlist(stat)
# exploration plots
#--------------------
# Nb fledgings learning or not
ind=all$species=="Blue"&all$scenario=="30"
estim<- dabest(
all[!is.na(all$FledgeNb)&ind,],learn,FledgeNb,idx=c("Learning","Nolearning"),
paired = FALSE
)
pdf(paste0(out_fit,"NbFledge_Learning Or not_blueTits_30.pdf"),height = 4,width = 4)
plot(estim,rawplot.ylabel="Nb fledging")
dev.off()
# Plot NbFledge_AccFi100
pdf(paste0(out_fit,"NbFledge_AccFi100_blueTits_30.pdf"))
ggplot(subset(all,ind), aes(y=FledgeNb, x=AccFi100)) +
geom_point(aes(colour=sex.y),size=6) + stat_smooth(method="lm", formula=y~x^2,aes(colour=sex.y))+ theme_bw()+
theme(text = element_text(size=18))+
ggtitle("Learning ON/OFF") +
ylab("Nb fledglings") + xlab("Accuracy last 100 trials")
dev.off()
# Plot AccPost50_10
pdf(paste0(out_fit,"NbFledge_AccPost50_10_blueTits_30.pdf"))
ggplot(subset(all,ind), aes(y=FledgeNb, x=AccPre50_10)) +
geom_point(aes(colour=sex.y),size=6) + stat_smooth(method="lm", formula=y~x^2)+ theme_bw()+
theme(text = element_text(size=18))+
ggtitle("Learning ON/OFF") +
ylab("Nb fledglings") + xlab("Accuracy post TTC")
dev.off()
# Plot AccFi30 nb egg
pdf(paste0(out_fit,"NbEgg_AccFi30_blueTits_30.pdf"))
ggplot(subset(all,ind), aes(y=EggNb, x=AccFi30)) +
geom_point(aes(colour=sex.y),size=6) + stat_smooth(method="lm", formula=y~x^2)+ theme_bw()+
theme(text = element_text(size=18))+
ggtitle("Learning ON/OFF") +
ylab("Nb eggs") + xlab("AccFi30")
dev.off()
#-------------------
# Winter nestcheck
#-------------------
wn=read.csv2(paste0(out_local,'winter_nest_check_2020.csv'))
ni=read.csv2(paste0(out_local,'NestBoxInformation.csv'))
ni$nest=toupper(substr(ni$name,1,4))
wn$nichoir=toupper(wn$nichoir)
diff=as.character(setdiff(ni$nest,wn$nichoir))
diffCast=diff[grep('H',diff)]
length(grep('H',ni$nest))
length(grep('H',wn$nichoir))
################################################################################
#-------------------
# Winter 2020 color combo for corelation with dominance !!!! NOW IN developped in DOM_main_2020.R
#------------------
# find last morpho info for each color for each site
# code color combo site
#---------------------
#from nest banding
b$SiteCorrect="Not a study site"
b$SiteCorrect[grep("H",b$Nest.Number)]="Castera"
b$SiteCorrect[grep("C",b$Nest.Number)]="Cescau"
b$SiteCorrect[grep("B",b$Nest.Number)]="Balacet"
b$SiteCorrect[grep("L",b$Nest.Number)]="Moulis" # same color combo
b$SiteCorrect[grep("M",b$Nest.Number)]="Moulis"
b$SiteCorrect[grep("G",b$Nest.Number)]="Galey"
#from winter banding
b$SiteCorrect[b$Site %in% c('C1','C4','C3','C5','C2','Castillon')]="Cescau"
b$SiteCorrect[b$Site %in% c('M1','L1','Aubert','Montegut','Ledar','AU')]="Moulis"
b$SiteCorrect[b$Site %in% c('BA')]="Balacet"
uSite=c("Cescau","Moulis","Balacet")
uSpe=c("Blue","Great","Marsh")
bcol=b[1,]
for (i in 1:length(uSite)){# loop on site
for (j in 1:length(uSpe)){ # loop on species
ind=b$SiteCorrect==uSite[i]&b$Species==uSpe[j]
uCol=unique(b$Color[ind]) # unique color combo
print(paste(uSite[i], uSpe[j]))
for (k in 1:length(uCol)){
indCol=ind&b$Color==uCol[k]
indColWing=indCol&!is.na(b$Wing.chord.num) # last morpho recorded
if (sum(indColWing,na.rm=T)>0 ) {
indCol=indColWing
}
lastCaptureDate=max(b$dateCorrected[which(indCol)])
goodLine=b[which(indCol&b$dateCorrected==lastCaptureDate),]
bcol=rbind(bcol,goodLine)
rm(indCol)
}
rm(ind)
}
}
bcol=bcol[2:dim(bcol)[1],c("BandNumber","Color","RFID.","Species","SiteCorrect","dateCorrected",
"Sex","Age","Wing.chord.num","Tarsus.num","Head.num","Photo","TagModif")]
bcol$Age[bcol$dateCorrected<"2019-03-01"]="+1a"
#------------------
# merge with patch
#------------------
patch=read.csv2(paste0(out_local,"Mesures patchs_2019.csv"),h=T,sep=";",
na.strings=c("?","","NA"))
patch$BandNumber=patch$Band.number
patch=patch[,c("BandNumber","Patch_head","Patch_cheek","Patch_tie")]
bcolpatch=merge(bcol,patch,by="BandNumber",sort=F,all.x=T)
# save
write.csv2(bcolpatch,paste0(out_local,"Color_banding.csv"),row.names = F)
|
## A script that for each meaningful principal component regresses on the design equation variables.
args = base::commandArgs(trailingOnly = TRUE)
print(args)
path2_json_file = args[1]
# **********************************************************************
## Load in the necessary libraries:
options(stringsAsFactors = FALSE)
options(bitmapType='quartz')
library(jsonlite)
library(readr)
library(ggplot2)
library(stringr)
# Read in input files:
print("*** Reading the input files ***")
json = read_json(path2_json_file)
parent_folder = json$folders$output_folder
experiment = json$experiment_name
path2_design = file.path(parent_folder, "results", paste0(experiment, "_design_meaningful.txt"))
path_2_pca = file.path(parent_folder, "results", paste0(experiment, "_pca_object.rds"))
path_2_json_copy = file.path(parent_folder, "results", paste0(experiment, "_json_copy.json"))
json_copy = read_json(path_2_json_copy)
# Load files
design = read.table(path2_design, sep = "\t", header = TRUE, row.names = 1)
pca = read_rds(path_2_pca)
# Chek 1:1 correspondence b/w experiment labels in the design file
# and sample values in the PCs.
stopifnot(rownames(pca$x) == rownames(design))
# Creating an empty data set to store my cor.model results.
# Create as many datasets as there are design formulas.
# Create a list of the design formulas from the JSON file
design_formulas = c(rep(0, length(json$design_variables)))
for (i in 1:(length(json$design_variables))){
if (str_length(json$design_variables[[i]]) > 0){
design_formulas[i] = json$design_variables[[i]]
}else if (str_length(json$design_variables[[i]]) <= 0){
design_formulas = design_formulas[-i]
}
}
# Extract the number of meaningful PC from the design file:
columns = grep("PC", colnames(design))
number_PC = length(columns)
print("*** Performing the correlation test and generating plots ***")
### A loop that performs the following operations: ###
# extract the column from the design file for each design formula (e.g. column "site")
# performs a cor.test between each design formula (e.g. "sex": "M" or "F") and each meaningful PC
# saves results to a table
# plot the correlations and saves the plots in the figures folder (for the automated report)
# main loop across the design formulas:
for (formula in 1:length(design_formulas)){
# extract the design formula variables from design file
variable_pca = design[, design_formulas[formula]]
# convert them into numeric to fit the model
categorical_variable = as.numeric(as.factor(variable_pca))
# temporary data set to store model results and then rename:
results = data.frame(pc_num = rep(1:number_PC),
cor = rep(0, number_PC),
pv = rep(0, number_PC))
# loop across all the meaningful PCs:
for (j in 1:number_PC){
# fit the correlation test between current PC (j) and current formula (formula)
mod = cor.test(categorical_variable, pca$x[, j])
# assign results to the right column and row in the results data set
results$cor[j] = mod$estimate
results$pv[j] = mod$p.value
# rename the results data set appropriately
assign(paste0("results_", design_formulas[formula]), results)
# save the results table
path_2_correlation = file.path(parent_folder,
"results",
paste0(experiment, "_", design_formulas[formula], "_correlation.txt"))
write.table(results, file = path_2_correlation, sep = '\t',col.names=NA,row.names=TRUE,quote=FALSE)
# save the path to the table into the json copy
json_copy$path_2_results$correlation_table[formula] = as.character(path_2_correlation)
}
### Create plots for the automated report ###
#
labels=list(unique(variable_pca)[1], unique(variable_pca)[2])
# a file path to store the figure:
figurex = file.path(parent_folder, "figures", paste0(experiment, "_cor_plot_", formula, ".png"))
png(figurex,height=300,width=300*number_PC)
par(mfrow = c(1, number_PC))
for (i in 1:number_PC){
x <- categorical_variable
y <- pca$x[,i]
plot(x, y, main = c("PC", i),
xlab = "Samples", ylab = "PC value",
pch = 1, col = categorical_variable, frame = FALSE)
abline(lm(pca$x[,i] ~ categorical_variable), col = "blue")
legend("top", legend = c(unique(variable_pca)),pch=1)
#legend("top", legend = c(unique(variable_pca)[1], unique(variable_pca)[2]),
# pch = 1, col = 1:2)
mtext(paste("correlation results for '", as.character(design_formulas[formula]), "' variable"),
side = 3, line = -1, outer = TRUE)
}
dev.off()
# Save the figure path into the json_copy:
json_copy$figures$scree_plot_cor[formula] = as.character(figurex)
}
# save the updated json copy
write_json(json_copy, path_2_json_copy, auto_unbox = TRUE)
# Following steps to come:
# Perform a regression with interaction terms
# Filter for p-value and correlation coefficient to establish whether the meaningful PCs have strong correlation
# with the design equations variables
### Find if meaningful PCs have association with the experimental design
### Boundaries for p-value and correlation coefficient
## Find the principal component that explain the design equation
## Standards chosen: p-value = 0.5
## abs(slope) >= 0.3
# significant_results = data.frame(pc_num = rep(NA, number_PC),
# cor = rep(NA, number_PC),
# pv = rep(NA, number_PC))
#
#
# for (i in 1:nrow(results)){
# if((results$pv)[i] <= 0.06 & (abs((results$cor)[i]) >= 0.3)) {
# significant_results[i, ] = results[i, ]
# }
# }
#
# output_sig_res = file.path(parent_folder, "results", paste0(experiment, "_significant_PC_vs_designformula.txt"))
# write.table(significant_results, file = output_sig_res, sep = '\t')
| /step_07.R | no_license | mdibl/biocore_automated-pca | R | false | false | 5,856 | r | ## A script that for each meaningful principal component regresses on the design equation variables.
args = base::commandArgs(trailingOnly = TRUE)
print(args)
path2_json_file = args[1]
# **********************************************************************
## Load in the necessary libraries:
options(stringsAsFactors = FALSE)
options(bitmapType='quartz')
library(jsonlite)
library(readr)
library(ggplot2)
library(stringr)
# Read in input files:
print("*** Reading the input files ***")
json = read_json(path2_json_file)
parent_folder = json$folders$output_folder
experiment = json$experiment_name
path2_design = file.path(parent_folder, "results", paste0(experiment, "_design_meaningful.txt"))
path_2_pca = file.path(parent_folder, "results", paste0(experiment, "_pca_object.rds"))
path_2_json_copy = file.path(parent_folder, "results", paste0(experiment, "_json_copy.json"))
json_copy = read_json(path_2_json_copy)
# Load files
design = read.table(path2_design, sep = "\t", header = TRUE, row.names = 1)
pca = read_rds(path_2_pca)
# Chek 1:1 correspondence b/w experiment labels in the design file
# and sample values in the PCs.
stopifnot(rownames(pca$x) == rownames(design))
# Creating an empty data set to store my cor.model results.
# Create as many datasets as there are design formulas.
# Create a list of the design formulas from the JSON file
design_formulas = c(rep(0, length(json$design_variables)))
for (i in 1:(length(json$design_variables))){
if (str_length(json$design_variables[[i]]) > 0){
design_formulas[i] = json$design_variables[[i]]
}else if (str_length(json$design_variables[[i]]) <= 0){
design_formulas = design_formulas[-i]
}
}
# Extract the number of meaningful PC from the design file:
columns = grep("PC", colnames(design))
number_PC = length(columns)
print("*** Performing the correlation test and generating plots ***")
### A loop that performs the following operations: ###
# extract the column from the design file for each design formula (e.g. column "site")
# performs a cor.test between each design formula (e.g. "sex": "M" or "F") and each meaningful PC
# saves results to a table
# plot the correlations and saves the plots in the figures folder (for the automated report)
# main loop across the design formulas:
for (formula in 1:length(design_formulas)){
# extract the design formula variables from design file
variable_pca = design[, design_formulas[formula]]
# convert them into numeric to fit the model
categorical_variable = as.numeric(as.factor(variable_pca))
# temporary data set to store model results and then rename:
results = data.frame(pc_num = rep(1:number_PC),
cor = rep(0, number_PC),
pv = rep(0, number_PC))
# loop across all the meaningful PCs:
for (j in 1:number_PC){
# fit the correlation test between current PC (j) and current formula (formula)
mod = cor.test(categorical_variable, pca$x[, j])
# assign results to the right column and row in the results data set
results$cor[j] = mod$estimate
results$pv[j] = mod$p.value
# rename the results data set appropriately
assign(paste0("results_", design_formulas[formula]), results)
# save the results table
path_2_correlation = file.path(parent_folder,
"results",
paste0(experiment, "_", design_formulas[formula], "_correlation.txt"))
write.table(results, file = path_2_correlation, sep = '\t',col.names=NA,row.names=TRUE,quote=FALSE)
# save the path to the table into the json copy
json_copy$path_2_results$correlation_table[formula] = as.character(path_2_correlation)
}
### Create plots for the automated report ###
#
labels=list(unique(variable_pca)[1], unique(variable_pca)[2])
# a file path to store the figure:
figurex = file.path(parent_folder, "figures", paste0(experiment, "_cor_plot_", formula, ".png"))
png(figurex,height=300,width=300*number_PC)
par(mfrow = c(1, number_PC))
for (i in 1:number_PC){
x <- categorical_variable
y <- pca$x[,i]
plot(x, y, main = c("PC", i),
xlab = "Samples", ylab = "PC value",
pch = 1, col = categorical_variable, frame = FALSE)
abline(lm(pca$x[,i] ~ categorical_variable), col = "blue")
legend("top", legend = c(unique(variable_pca)),pch=1)
#legend("top", legend = c(unique(variable_pca)[1], unique(variable_pca)[2]),
# pch = 1, col = 1:2)
mtext(paste("correlation results for '", as.character(design_formulas[formula]), "' variable"),
side = 3, line = -1, outer = TRUE)
}
dev.off()
# Save the figure path into the json_copy:
json_copy$figures$scree_plot_cor[formula] = as.character(figurex)
}
# save the updated json copy
write_json(json_copy, path_2_json_copy, auto_unbox = TRUE)
# Following steps to come:
# Perform a regression with interaction terms
# Filter for p-value and correlation coefficient to establish whether the meaningful PCs have strong correlation
# with the design equations variables
### Find if meaningful PCs have association with the experimental design
### Boundaries for p-value and correlation coefficient
## Find the principal component that explain the design equation
## Standards chosen: p-value = 0.5
## abs(slope) >= 0.3
# significant_results = data.frame(pc_num = rep(NA, number_PC),
# cor = rep(NA, number_PC),
# pv = rep(NA, number_PC))
#
#
# for (i in 1:nrow(results)){
# if((results$pv)[i] <= 0.06 & (abs((results$cor)[i]) >= 0.3)) {
# significant_results[i, ] = results[i, ]
# }
# }
#
# output_sig_res = file.path(parent_folder, "results", paste0(experiment, "_significant_PC_vs_designformula.txt"))
# write.table(significant_results, file = output_sig_res, sep = '\t')
|
library(tidyverse)
library(magrittr)
library(lubridate)
library(stringr)
library(naniar)
# For the first vignette we will be looking at an example from a file of Nevada voters. Right from the start, we would see that there are some problems, the data is parsed over two files and the second file is long-form while the other is wide:
#
# To load the data, we’ll be using the read_csv() function from the readr package.
#
# Readr gives you a lot more control over your data. Unless you are using .xlsx (my condolences, but also why?) for instance readr lets you parse the data from the start buth column specification:
#
# cols( firstname = col_character(), sex = col_character(), race = col_character(), call = col_double() )
#
# Moreover, readr embeds a lot internal functionality:
#
# skip = 3(throw away the first three lines)
# n_max = 10 (only read the first ten lines)
# na = c(“8”, “9”, "") (specify missing data)
# col_names = c(“year”, “grade”) (rename columns)
# Base R
df_1 <- read.csv("nevada_1.csv")
str(df_1); head(df_1)
tbl_1 <- read_csv("nevada_1.csv")[-1]
str(tbl_1); head(df_1)
class(df_1)
class(tbl_1)
tbl_2 <- read_csv("nevada_2.csv")
str(tbl_2); head(tbl_2)
# The output of readr is a tibble!
# Tibbles are lazy and surly: they don’t change variable names or types
# and don’t do partial matching and they hate missing data.
# This forces you to confront problems earlier and since we are always trying
# to stay on top of the bias we introduce when parsing data, this is exactly what we want.
# Simple Transformations
tbl_2 %<>%
pivot_wider(.,
id_cols = "VoterID",
names_from = "Election Date",
values_from = "Vote Code")
# Revert Back to Original
tbl_2 %>%
pivot_longer(.,
!VoterID,
names_to = "Election Date",
values_to = "Vote Code") %>%
head()
# Manipulate Dates with Lubridate
tbl_1 %<>%
mutate(Birth.Date = mdy(Birth.Date),
Registration.Date = mdy(Registration.Date))
# Merging your data
tbl <-
full_join(tbl_1,
tbl_2,
by = "VoterID")
# Basic Manipulation with dplyr/stringi/stringr
tbl %<>%
mutate(City = tolower(City))
# stringr gives you more control over how you manipulate strings
# here we'll combine stringr with select (subset on columns)
tbl %>%
mutate(Address = str_to_title(Address.1)) %>%
select(., Address) %>%
head()
# Conversely, filter can be used to subset on rows and pass that object onto the next function
tbl %>%
filter(., city == "las vegas") %>%
head()
# Easy to extend with logical comparisons
cities <- c("las vegas", "henderson")
tbl %>%
filter(., city %in% cities ) %>%
head()
# Let's talk about the quintisential data cleaning problem NAs
tbl_ab <- read_csv("ab1.csv")
head(tbl_ab[,14:40], 5L)
tbl_ab %>%
select(., 6:10) %>%
vis_miss()
## Inspect Elements
tbl_ab %<>%
select(., 6:10) %>%
mutate_if(is.character, ~as.numeric(.)) %>%
mutate_if(is.numeric, list(~na_if(., 8|9)))
#alternative: mutate(across(where(is.character), ~na_if(., 9)))
tbl_ab %>%
vis_miss(.)
# Let's shift gears and talk a little more about strings
# remotes::install_github('EandrewJones/how2scrape', build_vignettes = TRUE)
congress <- how2scrape::df_bills
# Let's combine regular expressions and stringr to manipulate information from sponsors
# 1. Convert to Tibble
tbl_c <-
congress %>%
tibble(.)
# 2. Look at the String
sponsorID <- tbl_c %>%
select(., sponsor) %>%
head(., 10)
### Let's expound on this a little more ###
str_split(sponsorID[,1], "\\[|\\]") #use \\ to escape the [] and split
str_split(sponsorID[,1], "-") #Risky with nieve matching
# 3. Regular Expressions
tbl_d <- tbl_c # set checkpoint
tbl_d <-
tbl_d %>%
separate(.,
col = sponsor,
into = c("name", "party", "stateID", "district"),
sep = "\\[|\\]|-" )
# Check your results!
tbl_d %>% select(., party) %>%
distinct()
dev <- tbl_c[which(str_detect(tbl_c$sponsor, "Porter, Carol")),]
dev %>%
select(., sponsor) %>%
head()
# Restart with more selective parsing
tbl_c <-
tbl_c %>%
separate(.,
col = sponsor,
into = c("name", "info"),
sep = "\\[|\\]" ) %>%
separate(.,
col = info,
into = c("party", "stateID", "district"),
sep = "-")
tbl_c %>%
select(., party) %>%
distinct()
# My view? Take your time with parsing, saves you trouble later on.
| /datacleaning/gsa_datacleaning.R | no_license | EandrewJones/gvpt-methods | R | false | false | 4,846 | r | library(tidyverse)
library(magrittr)
library(lubridate)
library(stringr)
library(naniar)
# For the first vignette we will be looking at an example from a file of Nevada voters. Right from the start, we would see that there are some problems, the data is parsed over two files and the second file is long-form while the other is wide:
#
# To load the data, we’ll be using the read_csv() function from the readr package.
#
# Readr gives you a lot more control over your data. Unless you are using .xlsx (my condolences, but also why?) for instance readr lets you parse the data from the start buth column specification:
#
# cols( firstname = col_character(), sex = col_character(), race = col_character(), call = col_double() )
#
# Moreover, readr embeds a lot internal functionality:
#
# skip = 3(throw away the first three lines)
# n_max = 10 (only read the first ten lines)
# na = c(“8”, “9”, "") (specify missing data)
# col_names = c(“year”, “grade”) (rename columns)
# Base R
df_1 <- read.csv("nevada_1.csv")
str(df_1); head(df_1)
tbl_1 <- read_csv("nevada_1.csv")[-1]
str(tbl_1); head(df_1)
class(df_1)
class(tbl_1)
tbl_2 <- read_csv("nevada_2.csv")
str(tbl_2); head(tbl_2)
# The output of readr is a tibble!
# Tibbles are lazy and surly: they don’t change variable names or types
# and don’t do partial matching and they hate missing data.
# This forces you to confront problems earlier and since we are always trying
# to stay on top of the bias we introduce when parsing data, this is exactly what we want.
# Simple Transformations
tbl_2 %<>%
pivot_wider(.,
id_cols = "VoterID",
names_from = "Election Date",
values_from = "Vote Code")
# Revert Back to Original
tbl_2 %>%
pivot_longer(.,
!VoterID,
names_to = "Election Date",
values_to = "Vote Code") %>%
head()
# Manipulate Dates with Lubridate
tbl_1 %<>%
mutate(Birth.Date = mdy(Birth.Date),
Registration.Date = mdy(Registration.Date))
# Merging your data
tbl <-
full_join(tbl_1,
tbl_2,
by = "VoterID")
# Basic Manipulation with dplyr/stringi/stringr
tbl %<>%
mutate(City = tolower(City))
# stringr gives you more control over how you manipulate strings
# here we'll combine stringr with select (subset on columns)
tbl %>%
mutate(Address = str_to_title(Address.1)) %>%
select(., Address) %>%
head()
# Conversely, filter can be used to subset on rows and pass that object onto the next function
tbl %>%
filter(., city == "las vegas") %>%
head()
# Easy to extend with logical comparisons
cities <- c("las vegas", "henderson")
tbl %>%
filter(., city %in% cities ) %>%
head()
# Let's talk about the quintisential data cleaning problem NAs
tbl_ab <- read_csv("ab1.csv")
head(tbl_ab[,14:40], 5L)
tbl_ab %>%
select(., 6:10) %>%
vis_miss()
## Inspect Elements
tbl_ab %<>%
select(., 6:10) %>%
mutate_if(is.character, ~as.numeric(.)) %>%
mutate_if(is.numeric, list(~na_if(., 8|9)))
#alternative: mutate(across(where(is.character), ~na_if(., 9)))
tbl_ab %>%
vis_miss(.)
# Let's shift gears and talk a little more about strings
# remotes::install_github('EandrewJones/how2scrape', build_vignettes = TRUE)
congress <- how2scrape::df_bills
# Let's combine regular expressions and stringr to manipulate information from sponsors
# 1. Convert to Tibble
tbl_c <-
congress %>%
tibble(.)
# 2. Look at the String
sponsorID <- tbl_c %>%
select(., sponsor) %>%
head(., 10)
### Let's expound on this a little more ###
str_split(sponsorID[,1], "\\[|\\]") #use \\ to escape the [] and split
str_split(sponsorID[,1], "-") #Risky with nieve matching
# 3. Regular Expressions
tbl_d <- tbl_c # set checkpoint
tbl_d <-
tbl_d %>%
separate(.,
col = sponsor,
into = c("name", "party", "stateID", "district"),
sep = "\\[|\\]|-" )
# Check your results!
tbl_d %>% select(., party) %>%
distinct()
dev <- tbl_c[which(str_detect(tbl_c$sponsor, "Porter, Carol")),]
dev %>%
select(., sponsor) %>%
head()
# Restart with more selective parsing
tbl_c <-
tbl_c %>%
separate(.,
col = sponsor,
into = c("name", "info"),
sep = "\\[|\\]" ) %>%
separate(.,
col = info,
into = c("party", "stateID", "district"),
sep = "-")
tbl_c %>%
select(., party) %>%
distinct()
# My view? Take your time with parsing, saves you trouble later on.
|
## START unit test getBegEndIndMSP
testMSP <- convert2MSP(sd02_deconvoluted, split = " _ ",
splitIndMZ = 2, splitIndRT = NULL)
testMSPmsp <- getMSP(testMSP)
BegEndIndMSP <- getBegEndIndMSP(testMSPmsp)
test_getBegEndIndMSP <- function() {
checkTrue(is.list(getBegEndIndMSP(testMSPmsp)))
checkTrue(length(BegEndIndMSP[[1]]) == length(BegEndIndMSP[[2]]))
checkTrue(all(BegEndIndMSP[[1]] <= BegEndIndMSP[[2]]))
checkTrue(is.numeric(BegEndIndMSP[[1]]))
checkTrue(is.vector(BegEndIndMSP[[1]]))
checkTrue(is.numeric(BegEndIndMSP[[2]]))
checkTrue(is.vector(BegEndIndMSP[[2]]))
}
## END unit test getBegIndMSP
## START unit test binning
compartment <- c(rep("a", 90), rep("b", 90), rep("c", 90), rep("d", 90))
## create binnedMSPs
binnedMSP001 <- binning(testMSP, 0.01, group = compartment, method = "mean")
test_binning <- function() {
checkTrue(is.matrix(binnedMSP001))
checkTrue(is.numeric(binnedMSP001))
checkEquals(dim(binnedMSP001), c(360, 764))
checkException(binning(finalMSP, 1, compartment[1:7]))
}
## END unit test binning
| /inst/unitTests/test_binning.R | no_license | Huansi/MetCirc | R | false | false | 1,098 | r |
## START unit test getBegEndIndMSP
testMSP <- convert2MSP(sd02_deconvoluted, split = " _ ",
splitIndMZ = 2, splitIndRT = NULL)
testMSPmsp <- getMSP(testMSP)
BegEndIndMSP <- getBegEndIndMSP(testMSPmsp)
test_getBegEndIndMSP <- function() {
checkTrue(is.list(getBegEndIndMSP(testMSPmsp)))
checkTrue(length(BegEndIndMSP[[1]]) == length(BegEndIndMSP[[2]]))
checkTrue(all(BegEndIndMSP[[1]] <= BegEndIndMSP[[2]]))
checkTrue(is.numeric(BegEndIndMSP[[1]]))
checkTrue(is.vector(BegEndIndMSP[[1]]))
checkTrue(is.numeric(BegEndIndMSP[[2]]))
checkTrue(is.vector(BegEndIndMSP[[2]]))
}
## END unit test getBegIndMSP
## START unit test binning
compartment <- c(rep("a", 90), rep("b", 90), rep("c", 90), rep("d", 90))
## create binnedMSPs
binnedMSP001 <- binning(testMSP, 0.01, group = compartment, method = "mean")
test_binning <- function() {
checkTrue(is.matrix(binnedMSP001))
checkTrue(is.numeric(binnedMSP001))
checkEquals(dim(binnedMSP001), c(360, 764))
checkException(binning(finalMSP, 1, compartment[1:7]))
}
## END unit test binning
|
library(ineq)
### Name: Lc.mehran
### Title: Mehran Bounds For Lorenz Curves
### Aliases: Lc.mehran
### Keywords: misc
### ** Examples
# income distribution of the USA in 1968 (in 10 classes)
# x vector of class means, n vector of class frequencies
x <- c(541, 1463, 2445, 3438, 4437, 5401, 6392, 8304, 11904, 22261)
n <- c(482, 825, 722, 690, 661, 760, 745, 2140, 1911, 1024)
# compute minimal Lorenz curve (= no inequality in each group)
Lc.min <- Lc(x, n=n)
# compute maximal Lorenz curve (limits of Mehran)
Lc.max <- Lc.mehran(x,n)
# plot both Lorenz curves in one plot
plot(Lc.min)
lines(Lc.max, col=4)
# add the theoretic Lorenz curve of a Lognormal-distribution with variance 0.78
lines(Lc.lognorm, parameter=0.78)
# add the theoretic Lorenz curve of a Dagum-distribution
lines(Lc.dagum, parameter=c(3.4,2.6))
| /data/genthat_extracted_code/ineq/examples/Lc.mehran.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 826 | r | library(ineq)
### Name: Lc.mehran
### Title: Mehran Bounds For Lorenz Curves
### Aliases: Lc.mehran
### Keywords: misc
### ** Examples
# income distribution of the USA in 1968 (in 10 classes)
# x vector of class means, n vector of class frequencies
x <- c(541, 1463, 2445, 3438, 4437, 5401, 6392, 8304, 11904, 22261)
n <- c(482, 825, 722, 690, 661, 760, 745, 2140, 1911, 1024)
# compute minimal Lorenz curve (= no inequality in each group)
Lc.min <- Lc(x, n=n)
# compute maximal Lorenz curve (limits of Mehran)
Lc.max <- Lc.mehran(x,n)
# plot both Lorenz curves in one plot
plot(Lc.min)
lines(Lc.max, col=4)
# add the theoretic Lorenz curve of a Lognormal-distribution with variance 0.78
lines(Lc.lognorm, parameter=0.78)
# add the theoretic Lorenz curve of a Dagum-distribution
lines(Lc.dagum, parameter=c(3.4,2.6))
|
testlist <- list(m = NULL, repetitions = 0L, in_m = structure(c(2.31584307392677e+77, 9.53818320927564e+295, 1.22810536108214e+146, 4.12396251261199e-221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 7L)))
result <- do.call(CNull:::communities_individual_based_sampling_beta,testlist)
str(result) | /CNull/inst/testfiles/communities_individual_based_sampling_beta/AFL_communities_individual_based_sampling_beta/communities_individual_based_sampling_beta_valgrind_files/1615829418-test.R | no_license | akhikolla/updatedatatype-list2 | R | false | false | 361 | r | testlist <- list(m = NULL, repetitions = 0L, in_m = structure(c(2.31584307392677e+77, 9.53818320927564e+295, 1.22810536108214e+146, 4.12396251261199e-221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 7L)))
result <- do.call(CNull:::communities_individual_based_sampling_beta,testlist)
str(result) |
###################################
### Smad translocation analysis ###
###################################
# Analysis pipeline for detecting nuclear translocation of Smad2/3 proteins into the nucleus
# (c) 2014 Till Dettmering
# Before starting, set working directory with setwd("DIR") to directory containing CellProfiler output files
# Read CellProfiler results
if (!exists("img")) img <- read.csv("Image.csv")
if (!exists("nuc")) nuc <- read.csv("Nuclei.csv")
if (!exists("cytopl")) cytopl <- read.csv("Cytoplasm.csv")
z.threshold <- 2 # How many SDs must the nuclear signal be away from the cytoplasm signal to count as translocated?
# Load sources
library(devtools) # needed for https source from github
source_url('https://raw.githubusercontent.com/tdett/r-helpers/master/generateList.R')
source_url('https://raw.githubusercontent.com/dettmering/r-helpers/master/dfBackup.R')
# Set classifiers; the results will be separated by these columns
classifiers <- c(
'Metadata_Dose',
'Metadata_Treatment',
'Metadata_Time',
'Metadata_Celltype',
'Metadata_Experiment',
'Metadata_Replicate'
)
image_area_cm2 <- 635.34 * 474.57 / 10^8 # Image size in cm^2. These values are likely different for your microscope.
img$cells_per_cm2 <- img$Count_Nuclei / image_area_cm2
# Add Cytoplasm data
nuc$Cytoplasm_Mean <- cytopl$Intensity_MeanIntensity_OrigPOI
nuc$Cytoplasm_SD <- cytopl$Intensity_StdIntensity_OrigPOI
# Calculate Cytoplasm-to-Nucleus ratio
nuc$Ratio <- nuc$Intensity_MeanIntensity_OrigPOI / nuc$Cytoplasm_Mean
# Calculate z-score
nuc$z.score <- (nuc$Intensity_MeanIntensity_OrigPOI - nuc$Cytoplasm_Mean) / nuc$Cytoplasm_SD
# Determine translocation status
nuc$Translocated <- nuc$z.score > z.threshold # Binary operator: Is Smad translocated?
# Area
nuc$Cells_Area <- nuc$AreaShape_Area + cytopl$AreaShape_Area
nuc$AreaRatio <- nuc$AreaShape_Area / nuc$Cells_Area * 100
# QC
nuc <- subset(nuc, AreaRatio < 100) # Exclude nuclei without cytoplasm
##########################################################
# Calculate percentage translocated and other parameters #
##########################################################
summary <- generateList(nuc, classifiers)
for (i in 1:length(summary$Metadata_Dose)) {
temp <- merge(nuc, summary[i, classifiers])
temp_img <- merge(img, summary[i, classifiers])
summary[i, 'Translocated'] <- sum(temp$Translocated, na.rm = TRUE)
summary[i, 'Mean.Intensity'] <- mean(temp$Intensity_MeanIntensity_OrigPOI, na.rm = TRUE)
summary[i, 'Median.Intensity'] <- median(temp$Intensity_MeanIntensity_OrigPOI, na.rm = TRUE)
summary[i, 'SD.Intensity'] <- sd(temp$Intensity_MeanIntensity_OrigPOI, na.rm = TRUE)
summary[i, 'Mean.Ratio'] <- mean(temp$Ratio, na.rm = TRUE)
summary[i, 'SD.Ratio'] <- sd(temp$Ratio, na.rm = TRUE)
summary[i, 'Mean.cells_per_cm2'] <- mean(temp_img$cells_per_cm2)
}
summary$CV.Intensity <- summary$SD.Intensity / abs(summary$Mean.Intensity) * 100
summary$Translocated.Percent <- summary$Translocated / summary$n * 100
################################################
# Summarize translocation over all experiments #
################################################
transloc_classifiers <- c(
'Metadata_Dose',
'Metadata_Treatment',
'Metadata_Time',
'Metadata_Celltype'
)
transloc <- generateList(summary, transloc_classifiers)
for (i in 1:length(transloc$Metadata_Dose)) {
temp <- merge(summary, transloc[i, transloc_classifiers])
transloc[i, 'Mean.Translocated'] <- mean(temp$Translocated.Percent)
transloc[i, 'SD.Translocated'] <- sd(temp$Translocated.Percent)
}
transloc$SEM.Translocated <- transloc$SD.Translocated / sqrt(transloc$n)
# Export raw data and summary table to csv (working directory)
dfBackup(c('img', 'summary', 'transloc')) | /analysis/analysis.R | no_license | dettmering/smad-translocation | R | false | false | 3,781 | r | ###################################
### Smad translocation analysis ###
###################################
# Analysis pipeline for detecting nuclear translocation of Smad2/3 proteins into the nucleus
# (c) 2014 Till Dettmering
# Before starting, set working directory with setwd("DIR") to directory containing CellProfiler output files
# Read CellProfiler results
if (!exists("img")) img <- read.csv("Image.csv")
if (!exists("nuc")) nuc <- read.csv("Nuclei.csv")
if (!exists("cytopl")) cytopl <- read.csv("Cytoplasm.csv")
z.threshold <- 2 # How many SDs must the nuclear signal be away from the cytoplasm signal to count as translocated?
# Load sources
library(devtools) # needed for https source from github
source_url('https://raw.githubusercontent.com/tdett/r-helpers/master/generateList.R')
source_url('https://raw.githubusercontent.com/dettmering/r-helpers/master/dfBackup.R')
# Set classifiers; the results will be separated by these columns
classifiers <- c(
'Metadata_Dose',
'Metadata_Treatment',
'Metadata_Time',
'Metadata_Celltype',
'Metadata_Experiment',
'Metadata_Replicate'
)
image_area_cm2 <- 635.34 * 474.57 / 10^8 # Image size in cm^2. These values are likely different for your microscope.
img$cells_per_cm2 <- img$Count_Nuclei / image_area_cm2
# Add Cytoplasm data
nuc$Cytoplasm_Mean <- cytopl$Intensity_MeanIntensity_OrigPOI
nuc$Cytoplasm_SD <- cytopl$Intensity_StdIntensity_OrigPOI
# Calculate Cytoplasm-to-Nucleus ratio
nuc$Ratio <- nuc$Intensity_MeanIntensity_OrigPOI / nuc$Cytoplasm_Mean
# Calculate z-score
nuc$z.score <- (nuc$Intensity_MeanIntensity_OrigPOI - nuc$Cytoplasm_Mean) / nuc$Cytoplasm_SD
# Determine translocation status
nuc$Translocated <- nuc$z.score > z.threshold # Binary operator: Is Smad translocated?
# Area
nuc$Cells_Area <- nuc$AreaShape_Area + cytopl$AreaShape_Area
nuc$AreaRatio <- nuc$AreaShape_Area / nuc$Cells_Area * 100
# QC
nuc <- subset(nuc, AreaRatio < 100) # Exclude nuclei without cytoplasm
##########################################################
# Calculate percentage translocated and other parameters #
##########################################################
summary <- generateList(nuc, classifiers)
for (i in 1:length(summary$Metadata_Dose)) {
temp <- merge(nuc, summary[i, classifiers])
temp_img <- merge(img, summary[i, classifiers])
summary[i, 'Translocated'] <- sum(temp$Translocated, na.rm = TRUE)
summary[i, 'Mean.Intensity'] <- mean(temp$Intensity_MeanIntensity_OrigPOI, na.rm = TRUE)
summary[i, 'Median.Intensity'] <- median(temp$Intensity_MeanIntensity_OrigPOI, na.rm = TRUE)
summary[i, 'SD.Intensity'] <- sd(temp$Intensity_MeanIntensity_OrigPOI, na.rm = TRUE)
summary[i, 'Mean.Ratio'] <- mean(temp$Ratio, na.rm = TRUE)
summary[i, 'SD.Ratio'] <- sd(temp$Ratio, na.rm = TRUE)
summary[i, 'Mean.cells_per_cm2'] <- mean(temp_img$cells_per_cm2)
}
summary$CV.Intensity <- summary$SD.Intensity / abs(summary$Mean.Intensity) * 100
summary$Translocated.Percent <- summary$Translocated / summary$n * 100
################################################
# Summarize translocation over all experiments #
################################################
transloc_classifiers <- c(
'Metadata_Dose',
'Metadata_Treatment',
'Metadata_Time',
'Metadata_Celltype'
)
transloc <- generateList(summary, transloc_classifiers)
for (i in 1:length(transloc$Metadata_Dose)) {
temp <- merge(summary, transloc[i, transloc_classifiers])
transloc[i, 'Mean.Translocated'] <- mean(temp$Translocated.Percent)
transloc[i, 'SD.Translocated'] <- sd(temp$Translocated.Percent)
}
transloc$SEM.Translocated <- transloc$SD.Translocated / sqrt(transloc$n)
# Export raw data and summary table to csv (working directory)
dfBackup(c('img', 'summary', 'transloc')) |
Plearning<-function(X,AA,RR,n,K,pi,pentype='lasso',kernel='linear',sigma=c(0.03,0.05,0.07),clinear=2.^(-2:2),m=4,e=0.00001){
select=matrix(1,n,1)
QL=matrix(0,n,K)
M=matrix(1,n,K)
C=matrix(1,n,K)
models=list()
prob=matrix(1,n,K)
QLproj=matrix(0,n,K+1)
Qspecify=matrix(0,n,K)
QR_future=0
Rsum=0
if (is.matrix(X)){
for (k in K:1){
A=AA[[k]]
output_Q=Qlearning_Single(X,A,RR[[k]]+QR_future,pentype=pentype,m=m)
QR_future=output_Q$Q
#subsititute the outcome by expected outcome of best treatment
QL[,k]=output_Q$Q
if(k<K) R_p=Rsum*select/prob[,K]+apply(QLproj[,(k+1):K]%*%Qspecify[,(k+1):K],2,sum)
if(k==K) R_p=Rsum*select/prob[,K]
R=(RR[[k]]+R_p)
if (kernel=='linear'){
models[[k]]=Olearning_Single(X,A,R,pi[[k]],pentype=pentype,clinear=clinear,e=e,m=m)
}else if (kernel=='rbf'){
models[[k]]=Olearning_Single(X,A,R,pi[[k]],pentype=pentype,kernel=kernel,sigma=sigma,clinear=clinear,e=e,m=m)
}else stop(gettextf("Kernel function should be 'linear' or 'rbf'"))
right=(sign(models[[k]]$fit)==A)
#update fo next stage
M[,k:K]=M[,k:K]*(right%*%rep(1,K-k+1))
if (k>1) C[,k:K]=M[,k-1:K-1]-M[,k:K]
if (k==1){
C[,2:K]=M[,1:(K-1)]-M[,2:K]
C[,1]=rep(1,n)-M[,1]
}
select=select*right
prob[,k:K]=prob[,k:K]*(pi[[k]]*rep(1,K-k+1))
Rsum=rep(1,n)
for (j in k:K){
if (j>1) {QLproj[,j]=(C[,j]-(1-pi[[j]])*M[,j-1])/prob[,j]
} else QLproj[,1]=(C[,j]-(1-pi[[j]]))/prob[,j]
Qspecify[,j]=QL[,j]+Rsum
Rsum=Rsum+RR[[j]]
}}}
if (is.list(X)){
for (k in K:1){
A=AA[[k]]
output_Q=Qlearning_Single(X[[k]],A,RR[[k]]+QR_future,pentype=pentype)
QR_future=output_Q$Q
#subsititute the outcome by expected outcome of best treatment
QL[,k]=output_Q$Q
if(k<K) R_p=Rsum*select/prob[,K]+apply(QLproj[,(k+1):K]%*%Qspecify[,(k+1):K],2,sum)
if(k==K) R_p=Rsum*select/prob[,K]
R=(RR[[k]]+R_p)
if (kernel=='linear'){
models[[k]]=Olearning_Single(X[[k]],A,R,pi[[k]],pentype=pentype)
}else if (kernel=='rbf'){
models[[k]]=Olearning_Single(X[[k]],A,R,pi[[k]],pentype=pentype,kernel=kernel,sigma=sigma,clinear=clinear,e=e,m=m)
}else stop(gettextf("Kernel function should be 'linear' or 'rbf'"))
right=(sign(models[[k]]$fit)==A)
#update fo next stage
M[,k:K]=M[,k:K]*(right%*%rep(1,K-k+1))
if (k>1) C[,k:K]=M[,k-1:K-1]-M[,k:K]
if (k==1){
C[,2:K]=M[,1:(K-1)]-M[,2:K]
C[,1]=rep(1,n)-M[,1]
}
select=select*right
prob[,k:K]=prob[,k:K]*(pi[[k]]*rep(1,K-k+1))
Rsum=rep(1,n)
for (j in k:K){
if (j>1) {QLproj[,j]=(C[,j]-(1-pi[[j]])*M[,j-1])/prob[,j]
} else QLproj[,1]=(C[,j]-(1-pi[[j]]))/prob[,j]
Qspecify[,j]=QL[,j]+Rsum
Rsum=Rsum+RR[[j]]
}}}
models
} | /R/Plearning.R | no_license | cran/DTRlearn | R | false | false | 2,653 | r | Plearning<-function(X,AA,RR,n,K,pi,pentype='lasso',kernel='linear',sigma=c(0.03,0.05,0.07),clinear=2.^(-2:2),m=4,e=0.00001){
select=matrix(1,n,1)
QL=matrix(0,n,K)
M=matrix(1,n,K)
C=matrix(1,n,K)
models=list()
prob=matrix(1,n,K)
QLproj=matrix(0,n,K+1)
Qspecify=matrix(0,n,K)
QR_future=0
Rsum=0
if (is.matrix(X)){
for (k in K:1){
A=AA[[k]]
output_Q=Qlearning_Single(X,A,RR[[k]]+QR_future,pentype=pentype,m=m)
QR_future=output_Q$Q
#subsititute the outcome by expected outcome of best treatment
QL[,k]=output_Q$Q
if(k<K) R_p=Rsum*select/prob[,K]+apply(QLproj[,(k+1):K]%*%Qspecify[,(k+1):K],2,sum)
if(k==K) R_p=Rsum*select/prob[,K]
R=(RR[[k]]+R_p)
if (kernel=='linear'){
models[[k]]=Olearning_Single(X,A,R,pi[[k]],pentype=pentype,clinear=clinear,e=e,m=m)
}else if (kernel=='rbf'){
models[[k]]=Olearning_Single(X,A,R,pi[[k]],pentype=pentype,kernel=kernel,sigma=sigma,clinear=clinear,e=e,m=m)
}else stop(gettextf("Kernel function should be 'linear' or 'rbf'"))
right=(sign(models[[k]]$fit)==A)
#update fo next stage
M[,k:K]=M[,k:K]*(right%*%rep(1,K-k+1))
if (k>1) C[,k:K]=M[,k-1:K-1]-M[,k:K]
if (k==1){
C[,2:K]=M[,1:(K-1)]-M[,2:K]
C[,1]=rep(1,n)-M[,1]
}
select=select*right
prob[,k:K]=prob[,k:K]*(pi[[k]]*rep(1,K-k+1))
Rsum=rep(1,n)
for (j in k:K){
if (j>1) {QLproj[,j]=(C[,j]-(1-pi[[j]])*M[,j-1])/prob[,j]
} else QLproj[,1]=(C[,j]-(1-pi[[j]]))/prob[,j]
Qspecify[,j]=QL[,j]+Rsum
Rsum=Rsum+RR[[j]]
}}}
if (is.list(X)){
for (k in K:1){
A=AA[[k]]
output_Q=Qlearning_Single(X[[k]],A,RR[[k]]+QR_future,pentype=pentype)
QR_future=output_Q$Q
#subsititute the outcome by expected outcome of best treatment
QL[,k]=output_Q$Q
if(k<K) R_p=Rsum*select/prob[,K]+apply(QLproj[,(k+1):K]%*%Qspecify[,(k+1):K],2,sum)
if(k==K) R_p=Rsum*select/prob[,K]
R=(RR[[k]]+R_p)
if (kernel=='linear'){
models[[k]]=Olearning_Single(X[[k]],A,R,pi[[k]],pentype=pentype)
}else if (kernel=='rbf'){
models[[k]]=Olearning_Single(X[[k]],A,R,pi[[k]],pentype=pentype,kernel=kernel,sigma=sigma,clinear=clinear,e=e,m=m)
}else stop(gettextf("Kernel function should be 'linear' or 'rbf'"))
right=(sign(models[[k]]$fit)==A)
#update fo next stage
M[,k:K]=M[,k:K]*(right%*%rep(1,K-k+1))
if (k>1) C[,k:K]=M[,k-1:K-1]-M[,k:K]
if (k==1){
C[,2:K]=M[,1:(K-1)]-M[,2:K]
C[,1]=rep(1,n)-M[,1]
}
select=select*right
prob[,k:K]=prob[,k:K]*(pi[[k]]*rep(1,K-k+1))
Rsum=rep(1,n)
for (j in k:K){
if (j>1) {QLproj[,j]=(C[,j]-(1-pi[[j]])*M[,j-1])/prob[,j]
} else QLproj[,1]=(C[,j]-(1-pi[[j]]))/prob[,j]
Qspecify[,j]=QL[,j]+Rsum
Rsum=Rsum+RR[[j]]
}}}
models
} |
## Plot3
## Read file
## We will only be using data from the dates 2007-02-01 and 2007-02-02.
## One alternative is to read the data from just those dates rather than
## reading in the entire dataset and subsetting to those dates.
## prerequisite: setwd() has been set and "household_power_consumption.txt" has been downloaded to wd already
powerData <- read.table(pipe('grep "^[1-2]/2/2007" "household_power_consumption.txt"'), sep = ";")
colnames(powerData)<-c("Date","Time", "Global_active_power", "Global_reactive_power",
"Voltage", "Global_intensity","Sub_metering_1",
"Sub_metering_2","Sub_metering_3")
powerData$Date<- as.Date(powerData$Date,format = "%d/%m/%Y")
DateTime <- paste(powerData$Date, powerData$Time)
powerData$Datetime <- as.POSIXct(DateTime)
## Construct the plot
png(file = "Plot3.png")
with(powerData, {
plot(Sub_metering_1 ~ powerData$Datetime, type = "l",
ylab = "Global Active Power (kilowatts)", xlab = "")
lines(Sub_metering_2 ~ powerData$Datetime, col = 'Red')
lines(Sub_metering_3 ~ powerData$Datetime, col = 'Blue')
})
legend("topright", col = c("black", "red", "blue"), lty = 1, lwd = 2,
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
dev.off()
| /Plot3.R | no_license | linayang28/ExData_Plotting1 | R | false | false | 1,328 | r |
## Plot3
## Read file
## We will only be using data from the dates 2007-02-01 and 2007-02-02.
## One alternative is to read the data from just those dates rather than
## reading in the entire dataset and subsetting to those dates.
## prerequisite: setwd() has been set and "household_power_consumption.txt" has been downloaded to wd already
powerData <- read.table(pipe('grep "^[1-2]/2/2007" "household_power_consumption.txt"'), sep = ";")
colnames(powerData)<-c("Date","Time", "Global_active_power", "Global_reactive_power",
"Voltage", "Global_intensity","Sub_metering_1",
"Sub_metering_2","Sub_metering_3")
powerData$Date<- as.Date(powerData$Date,format = "%d/%m/%Y")
DateTime <- paste(powerData$Date, powerData$Time)
powerData$Datetime <- as.POSIXct(DateTime)
## Construct the plot
png(file = "Plot3.png")
with(powerData, {
plot(Sub_metering_1 ~ powerData$Datetime, type = "l",
ylab = "Global Active Power (kilowatts)", xlab = "")
lines(Sub_metering_2 ~ powerData$Datetime, col = 'Red')
lines(Sub_metering_3 ~ powerData$Datetime, col = 'Blue')
})
legend("topright", col = c("black", "red", "blue"), lty = 1, lwd = 2,
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
dev.off()
|
\name{pair.dist.dna}
\alias{pair.dist.dna}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{ Calculate pairwise distances among DNA sequences }
\description{
Calculate pairwise distances among DNA sequences. The DNA sequences are coded as 1:A, 2:G, 3:C, 4:T.
}
\usage{
pair.dist.dna(sequences, nst = 0)
}
\arguments{
\item{sequences}{ DNA sequences }
\item{nst}{ substitution model. 0:no model, 1:JC }
}
\details{
If nst=0, the distance is equal to the proportion of sites having different nucleotides between two sequences.
}
\value{
The function returns a distance matrix.
}
\references{
Jukes, TH and Cantor, CR. 1969. Evolution of protein molecules. Pp. 21-123 in H. N. Munro, ed. Mammalian protein metabolism. Academic Press, New York. }
\author{ Liang Liu \email{lliu@oeb.harvard.edu} }
\seealso{ \code{\link{upgma}} }
\examples{
tree<-"(((H:0.00402#0.01,C:0.00402#0.01):0.00304#0.01,G:0.00707#0.01):0.00929#0.01,O:0.01635#0.01)#0.01;"
nodematrix<-read.tree.nodes(tree)$nodes
sequences<-sim.dna(nodematrix,10000,model=1)
pair.dist.dna(sequences,nst=1)
}
\keyword{ programming }
| /man/pair.dist.dna.Rd | no_license | cran/phybase | R | false | false | 1,151 | rd | \name{pair.dist.dna}
\alias{pair.dist.dna}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{ Calculate pairwise distances among DNA sequences }
\description{
Calculate pairwise distances among DNA sequences. The DNA sequences are coded as 1:A, 2:G, 3:C, 4:T.
}
\usage{
pair.dist.dna(sequences, nst = 0)
}
\arguments{
\item{sequences}{ DNA sequences }
\item{nst}{ substitution model. 0:no model, 1:JC }
}
\details{
If nst=0, the distance is equal to the proportion of sites having different nucleotides between two sequences.
}
\value{
The function returns a distance matrix.
}
\references{
Jukes, TH and Cantor, CR. 1969. Evolution of protein molecules. Pp. 21-123 in H. N. Munro, ed. Mammalian protein metabolism. Academic Press, New York. }
\author{ Liang Liu \email{lliu@oeb.harvard.edu} }
\seealso{ \code{\link{upgma}} }
\examples{
tree<-"(((H:0.00402#0.01,C:0.00402#0.01):0.00304#0.01,G:0.00707#0.01):0.00929#0.01,O:0.01635#0.01)#0.01;"
nodematrix<-read.tree.nodes(tree)$nodes
sequences<-sim.dna(nodematrix,10000,model=1)
pair.dist.dna(sequences,nst=1)
}
\keyword{ programming }
|
plot6 <- function() {
png("plot6.png")
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
baltData <- NEI[NEI$fips == "24510",]
laData <- NEI[NEI$fips == "06037",]
scc <- SCC[SCC$EI.Sector == "Mobile - On-Road Diesel Heavy Duty Vehicles" |
SCC$EI.Sector == "Mobile - On-Road Diesel Light Duty Vehicles" |
SCC$EI.Sector == "Mobile - On-Road Gasoline Heavy Duty Vehicles" |
SCC$EI.Sector == "Mobile - On-Road Gasoline Light Duty Vehicles",
"SCC"]
scc <- as.character(scc)
baltMotorEmi <- baltData[baltData$SCC %in% scc,]
laMotorEmi <- laData[laData$SCC %in% scc,]
baltEmi_year <- tapply(baltMotorEmi$Emissions, baltMotorEmi$year, FUN = sum)
laEmi_year <- tapply(laMotorEmi$Emissions, laMotorEmi$year, FUN = sum)
split.screen(c(1,2))
screen(1)
barplot(baltEmi_year, col = "red",
main = "Baltimore",
xlab = "Year", ylab = "Total PM2.5 emission")
screen(2)
barplot(laEmi_year, col = "red",
main = "Los Angeles",
xlab = "Year", ylab = "Total PM2.5 emission")
dev.off()
} | /plot6.R | no_license | huangzhenbc/Course_Project_2_Huang | R | false | false | 1,266 | r | plot6 <- function() {
png("plot6.png")
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
baltData <- NEI[NEI$fips == "24510",]
laData <- NEI[NEI$fips == "06037",]
scc <- SCC[SCC$EI.Sector == "Mobile - On-Road Diesel Heavy Duty Vehicles" |
SCC$EI.Sector == "Mobile - On-Road Diesel Light Duty Vehicles" |
SCC$EI.Sector == "Mobile - On-Road Gasoline Heavy Duty Vehicles" |
SCC$EI.Sector == "Mobile - On-Road Gasoline Light Duty Vehicles",
"SCC"]
scc <- as.character(scc)
baltMotorEmi <- baltData[baltData$SCC %in% scc,]
laMotorEmi <- laData[laData$SCC %in% scc,]
baltEmi_year <- tapply(baltMotorEmi$Emissions, baltMotorEmi$year, FUN = sum)
laEmi_year <- tapply(laMotorEmi$Emissions, laMotorEmi$year, FUN = sum)
split.screen(c(1,2))
screen(1)
barplot(baltEmi_year, col = "red",
main = "Baltimore",
xlab = "Year", ylab = "Total PM2.5 emission")
screen(2)
barplot(laEmi_year, col = "red",
main = "Los Angeles",
xlab = "Year", ylab = "Total PM2.5 emission")
dev.off()
} |
#read in Trump data frame
trump <- read.csv("./data_tidy/ky_trump_2016.csv", header = T, stringsAsFactors = F)
#fit linear model to Trump
fit.lm <- lm(tr_pct ~ per_capita_income + pop_dens + pct_bachelor_deg +
coal_2015_pct_chg + pop_2015 + pct_reg_repubs +
pct_reg_males + pct_65_and_older + pct_non_white, data = trump)
summary(fit.lm)
#get Jim Gray Results by County
#Variable 1--Trump Winning percentage--Outcome Variable
#load secretary of state general election results Nov 2016.
file <- "./data_raw/2016_11_08_paul_results.csv"
paul <- read.csv(file = file, header = T, stringsAsFactors = F, nrows = 120)
paul$paul_pct <- round((paul$Paul / paul$Total) * 100, 4)
#build data frame for paul
library(magrittr)
library(dplyr)
df.paul <- trump %>%
select(County, per_capita_income, pop_dens, pop_2015, pct_bachelor_deg,
pct_reg_repubs, pct_reg_males, pct_65_and_older, log_pop_2015,
coal_2015_pct_chg, region, senate_dist, pct_non_white)
df.paul <- cbind(paul$Total, paul$paul_pct, df.paul)
names(df.paul)[grep("Total", names(df.paul))] <- "tot_votes"
names(df.paul)[grep("paul_pct", names(df.paul))] <- "paul_pct"
#add outcome variable
df.paul$outcome <- "w"
counties.lost <- df.paul[which(df.paul$paul_pct < .5) == T, ]
#fit linear model to Paul
fit.lm <- lm(paul_pct ~ per_capita_income + pop_dens + pct_bachelor_deg +
coal_2015_pct_chg + pop_2015 + pct_reg_repubs +
pct_reg_males + pct_65_and_older + pct_non_white, data = df.paul)
summary(fit.lm)
df.paul$fitted <- fit.lm$fitted.values
df.paul$resids <- fit.lm$residuals
write.csv(df.paul, file = "./data_tidy/ky_paul_2016.csv", row.names = F)
| /trump_ky/R/04_create_dataframe_paul.R | permissive | RobWiederstein/blog | R | false | false | 1,734 | r | #read in Trump data frame
trump <- read.csv("./data_tidy/ky_trump_2016.csv", header = T, stringsAsFactors = F)
#fit linear model to Trump
fit.lm <- lm(tr_pct ~ per_capita_income + pop_dens + pct_bachelor_deg +
coal_2015_pct_chg + pop_2015 + pct_reg_repubs +
pct_reg_males + pct_65_and_older + pct_non_white, data = trump)
summary(fit.lm)
#get Jim Gray Results by County
#Variable 1--Trump Winning percentage--Outcome Variable
#load secretary of state general election results Nov 2016.
file <- "./data_raw/2016_11_08_paul_results.csv"
paul <- read.csv(file = file, header = T, stringsAsFactors = F, nrows = 120)
paul$paul_pct <- round((paul$Paul / paul$Total) * 100, 4)
#build data frame for paul
library(magrittr)
library(dplyr)
df.paul <- trump %>%
select(County, per_capita_income, pop_dens, pop_2015, pct_bachelor_deg,
pct_reg_repubs, pct_reg_males, pct_65_and_older, log_pop_2015,
coal_2015_pct_chg, region, senate_dist, pct_non_white)
df.paul <- cbind(paul$Total, paul$paul_pct, df.paul)
names(df.paul)[grep("Total", names(df.paul))] <- "tot_votes"
names(df.paul)[grep("paul_pct", names(df.paul))] <- "paul_pct"
#add outcome variable
df.paul$outcome <- "w"
counties.lost <- df.paul[which(df.paul$paul_pct < .5) == T, ]
#fit linear model to Paul
fit.lm <- lm(paul_pct ~ per_capita_income + pop_dens + pct_bachelor_deg +
coal_2015_pct_chg + pop_2015 + pct_reg_repubs +
pct_reg_males + pct_65_and_older + pct_non_white, data = df.paul)
summary(fit.lm)
df.paul$fitted <- fit.lm$fitted.values
df.paul$resids <- fit.lm$residuals
write.csv(df.paul, file = "./data_tidy/ky_paul_2016.csv", row.names = F)
|
#'Returns a link directly to a file.
#'
#'Similar to \code{drop_shared}. The difference is that this bypasses the
#'Dropbox webserver, used to provide a preview of the file, so that you can
#'effectively stream the contents of your media. This URL should not be used to
#'display content directly in the browser. IMPORTANT: The media link will expire
#' after 4 hours. So you'll need to cache the content with knitr cache OR re-run
#' the function call after exipry.
#'@template path
#'@template locale
#' @template token
#'@export
#' @examples \dontrun{
#' drop_media('Public/gifs/duck_rabbit.gif')
#'}
drop_media <- function(path = NULL, locale = NULL, dtoken = get_dropbox_token()) {
assert_that(!is.null(path))
if(drop_exists(path)) {
args <- as.list(drop_compact(c(path = path,
locale = locale)))
media_url <- "https://api.dropbox.com/1/media/auto/"
res <- POST(media_url, query = args, config(token = dtoken), encode = "form")
pretty_lists(content(res))
} else {
stop("File not found \n")
FALSE
}
}
| /R/drop_media.R | no_license | scheidec/rdrop2 | R | false | false | 1,078 | r |
#'Returns a link directly to a file.
#'
#'Similar to \code{drop_shared}. The difference is that this bypasses the
#'Dropbox webserver, used to provide a preview of the file, so that you can
#'effectively stream the contents of your media. This URL should not be used to
#'display content directly in the browser. IMPORTANT: The media link will expire
#' after 4 hours. So you'll need to cache the content with knitr cache OR re-run
#' the function call after exipry.
#'@template path
#'@template locale
#' @template token
#'@export
#' @examples \dontrun{
#' drop_media('Public/gifs/duck_rabbit.gif')
#'}
drop_media <- function(path = NULL, locale = NULL, dtoken = get_dropbox_token()) {
assert_that(!is.null(path))
if(drop_exists(path)) {
args <- as.list(drop_compact(c(path = path,
locale = locale)))
media_url <- "https://api.dropbox.com/1/media/auto/"
res <- POST(media_url, query = args, config(token = dtoken), encode = "form")
pretty_lists(content(res))
} else {
stop("File not found \n")
FALSE
}
}
|
cat("\014") # Clear your console
rm(list = ls()) #clear your environment
########################## Load in header file ######################## #
setwd("~/git/of_dollars_and_data")
source(file.path(paste0(getwd(),"/header.R")))
########################## Load in Libraries ########################## #
library(ggplot2)
library(tidyr)
library(scales)
library(grid)
library(gridExtra)
library(gtable)
library(RColorBrewer)
library(stringr)
library(ggrepel)
library(dplyr)
folder_name <- "0357_return_on_hassle_spectrum"
out_path <- paste0(exportdir, folder_name)
dir.create(file.path(paste0(out_path)), showWarnings = FALSE)
########################## Start Program Here ######################### #
df <- data.frame()
df[1, "difficulty"] <- 1
df[1, "return"] <- 0.04
df[1, "name"] <- "T-Bills"
df[2, "difficulty"] <- 2
df[2, "return"] <- 0.045
df[2, "name"] <- "U.S. Bonds"
df[3, "difficulty"] <- 3
df[3, "return"] <- 0.055
df[3, "name"] <- "Diversified Portfolio (i.e. 60/40)"
df[4, "difficulty"] <- 5
df[4, "return"] <- 0.07
df[4, "name"] <- "Passive Stock Fund"
df[5, "difficulty"] <- 6
df[5, "return"] <- 0.075
df[5, "name"] <- "Active Stock Fund"
df[6, "difficulty"] <- 7
df[6, "return"] <- 0.08
df[6, "name"] <- "Individual Stock Picking"
df[7, "difficulty"] <- 8
df[7, "return"] <- 0.1
df[7, "name"] <- "Real Estate Rentals"
df[8, "difficulty"] <- 10
df[8, "return"] <- 0.12
df[8, "name"] <- "Starting Your\nOwn Business"
to_plot <- df
text_labels <- to_plot %>%
mutate(difficulty = case_when(
difficulty == 1 ~ 1.7,
difficulty == 2 ~ 2.75,
difficulty == 3 ~ 4.9,
difficulty == 5 ~ 6.3,
difficulty == 6 ~ 7.2,
difficulty == 7 ~ 8.5,
difficulty == 8 ~ 9.2,
difficulty == 10 ~ 8.8,
TRUE ~ difficulty
))
file_path <- paste0(out_path, "/return_on_hassle_spectrum_2023_final.jpeg")
source_string <- paste0("Source: Simulated data (OfDollarsAndData.com)")
plot <- ggplot(data = to_plot, aes(x = difficulty, y = return)) +
geom_line() +
geom_point() +
geom_text(data = text_labels, aes(x= difficulty, y=return, label = name),
family = my_font,
size = 2.7) +
scale_x_continuous(label = comma, breaks = seq(1, 10, 1)) +
scale_y_continuous(label = percent_format(accuracy = 1)) +
ggtitle("The Return on Hassle Spectrum") +
of_dollars_and_data_theme +
labs(x = "Difficulty/Hassle" , y = "Expected Annualized Return",
caption = paste0(source_string))
# Save the gtable
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
# ############################ End ################################## # | /analysis/0357_return_on_hassle_spectrum.R | no_license | nmaggiulli/of-dollars-and-data | R | false | false | 2,784 | r | cat("\014") # Clear your console
rm(list = ls()) #clear your environment
########################## Load in header file ######################## #
setwd("~/git/of_dollars_and_data")
source(file.path(paste0(getwd(),"/header.R")))
########################## Load in Libraries ########################## #
library(ggplot2)
library(tidyr)
library(scales)
library(grid)
library(gridExtra)
library(gtable)
library(RColorBrewer)
library(stringr)
library(ggrepel)
library(dplyr)
folder_name <- "0357_return_on_hassle_spectrum"
out_path <- paste0(exportdir, folder_name)
dir.create(file.path(paste0(out_path)), showWarnings = FALSE)
########################## Start Program Here ######################### #
df <- data.frame()
df[1, "difficulty"] <- 1
df[1, "return"] <- 0.04
df[1, "name"] <- "T-Bills"
df[2, "difficulty"] <- 2
df[2, "return"] <- 0.045
df[2, "name"] <- "U.S. Bonds"
df[3, "difficulty"] <- 3
df[3, "return"] <- 0.055
df[3, "name"] <- "Diversified Portfolio (i.e. 60/40)"
df[4, "difficulty"] <- 5
df[4, "return"] <- 0.07
df[4, "name"] <- "Passive Stock Fund"
df[5, "difficulty"] <- 6
df[5, "return"] <- 0.075
df[5, "name"] <- "Active Stock Fund"
df[6, "difficulty"] <- 7
df[6, "return"] <- 0.08
df[6, "name"] <- "Individual Stock Picking"
df[7, "difficulty"] <- 8
df[7, "return"] <- 0.1
df[7, "name"] <- "Real Estate Rentals"
df[8, "difficulty"] <- 10
df[8, "return"] <- 0.12
df[8, "name"] <- "Starting Your\nOwn Business"
to_plot <- df
text_labels <- to_plot %>%
mutate(difficulty = case_when(
difficulty == 1 ~ 1.7,
difficulty == 2 ~ 2.75,
difficulty == 3 ~ 4.9,
difficulty == 5 ~ 6.3,
difficulty == 6 ~ 7.2,
difficulty == 7 ~ 8.5,
difficulty == 8 ~ 9.2,
difficulty == 10 ~ 8.8,
TRUE ~ difficulty
))
file_path <- paste0(out_path, "/return_on_hassle_spectrum_2023_final.jpeg")
source_string <- paste0("Source: Simulated data (OfDollarsAndData.com)")
plot <- ggplot(data = to_plot, aes(x = difficulty, y = return)) +
geom_line() +
geom_point() +
geom_text(data = text_labels, aes(x= difficulty, y=return, label = name),
family = my_font,
size = 2.7) +
scale_x_continuous(label = comma, breaks = seq(1, 10, 1)) +
scale_y_continuous(label = percent_format(accuracy = 1)) +
ggtitle("The Return on Hassle Spectrum") +
of_dollars_and_data_theme +
labs(x = "Difficulty/Hassle" , y = "Expected Annualized Return",
caption = paste0(source_string))
# Save the gtable
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
# ############################ End ################################## # |
run_analysis<-function(){
library(dplyr)
j<-1
col.number<-col.number.lst<-feature.name.lst<-temp.col.mean<-NULL
subjects<-read.table("subject_test.txt")
act.code<-read.table("y_test.txt")
act.label<-read.table("activity_labels.txt")
code.label<-merge(act.code,act.label) ##naming the columns and then merging will cause the system to hang, requires a reboot!
colnames(code.label)[1]<-paste("ActivityCode")
colnames(code.label)[2]<-paste("ActivityType")
colnames(subjects)[1]<-paste("Subjects")
sub.code.label<-cbind(subjects,code.label)
test.data<-read.table("X_test.txt")
features.all<-read.table("features.txt")
features.lst<-features.all[,2]
features.lst.clean<-gsub('\\W',"",features.lst)
df2<-matrix(nrow=14,ncol=79)
for(i in 1:561){
feature.name<-features.lst.clean[i]
#print(feature.name)
features.all.heading<-colnames(test.data)[j]<-paste(feature.name)
if((grepl("mean",feature.name))|(grepl("std",feature.name))){
col.number<-i
col.number.lst<-append(col.number.lst,col.number)
feature.name.lst<-append(feature.name.lst,as.character(feature.name)) #appending characters to a list requires as.character
len<-length(feature.name.lst)
}
j=j+1
}
test.final<-cbind(sub.code.label,test.data)
std.mean.vec<-c(col.number.lst)
collect.std.mean<-test.final[,std.mean.vec]
test.final.test<-write.csv(collect.std.mean,file="test_data_test.csv")
col.names<-colnames(collect.std.mean)
test<-read.csv("test_data_test.csv")
df_test <- test %>%
group_by(Subjects,ActivityCode,ActivityType) %>%
summarise_each(funs(mean))
df_test<-subset(df_test,select = -X)
#write.file<-write.csv(df_test,file="write_df_test.csv")
#This is a replica of the code above for train data set
j<-1
col.number<-col.number.lst<-feature.name.lst<-temp.col.mean<-NULL
subjects<-read.table("subject_train.txt")
act.code<-read.table("y_train.txt")
act.label<-read.table("activity_labels.txt")
code.label<-merge(act.code,act.label) ##naming the columns and then merging will cause the system to hang, requires a reboot!
colnames(code.label)[1]<-paste("ActivityCode")
colnames(code.label)[2]<-paste("ActivityType")
colnames(subjects)[1]<-paste("Subjects")
sub.code.label<-cbind(subjects,code.label)
test.data<-read.table("X_train.txt")
features.all<-read.table("features.txt")
features.lst<-features.all[,2]
features.lst.clean<-gsub('\\W',"",features.lst)
df2<-matrix(nrow=14,ncol=79)
for(i in 1:561){
feature.name<-features.lst.clean[i]
features.all.heading<-colnames(test.data)[j]<-paste(feature.name)
if((grepl("mean",feature.name))|(grepl("std",feature.name))){
col.number<-i
col.number.lst<-append(col.number.lst,col.number)
feature.name.lst<-append(feature.name.lst,as.character(feature.name)) #appending characters to a list requires as.character
len<-length(feature.name.lst)
}
j=j+1
}
test.final<-cbind(sub.code.label,test.data)
std.mean.vec<-c(col.number.lst)
collect.std.mean<-test.final[,std.mean.vec]
test.final.test<-write.csv(collect.std.mean,file="test_data_test.csv")
col.names<-colnames(collect.std.mean)
test<-read.csv("test_data_test.csv")
df_train <- test %>%
group_by(Subjects,ActivityCode,ActivityType) %>%
summarise_each(funs(mean))
df_train<-subset(df_train,select = -X)
#write.file<-write.csv(df1,file="write_df_train.csv")
#create tidy data set
tidy.data<-rbind(df_test,df_train)
tidy.data.wrt<-write.csv(tidy.data,file="Tidy_Data.csv")
tidy.data.wrt<-write.table(tidy.data,file="Tidy_Data.txt",row.name=FALSE)
}
| /GettingAndCleaningDataCoursera/run_analysis.R | no_license | chandrasharma/GettingAndCleaningDataCoursera | R | false | false | 5,283 | r | run_analysis<-function(){
library(dplyr)
j<-1
col.number<-col.number.lst<-feature.name.lst<-temp.col.mean<-NULL
subjects<-read.table("subject_test.txt")
act.code<-read.table("y_test.txt")
act.label<-read.table("activity_labels.txt")
code.label<-merge(act.code,act.label) ##naming the columns and then merging will cause the system to hang, requires a reboot!
colnames(code.label)[1]<-paste("ActivityCode")
colnames(code.label)[2]<-paste("ActivityType")
colnames(subjects)[1]<-paste("Subjects")
sub.code.label<-cbind(subjects,code.label)
test.data<-read.table("X_test.txt")
features.all<-read.table("features.txt")
features.lst<-features.all[,2]
features.lst.clean<-gsub('\\W',"",features.lst)
df2<-matrix(nrow=14,ncol=79)
for(i in 1:561){
feature.name<-features.lst.clean[i]
#print(feature.name)
features.all.heading<-colnames(test.data)[j]<-paste(feature.name)
if((grepl("mean",feature.name))|(grepl("std",feature.name))){
col.number<-i
col.number.lst<-append(col.number.lst,col.number)
feature.name.lst<-append(feature.name.lst,as.character(feature.name)) #appending characters to a list requires as.character
len<-length(feature.name.lst)
}
j=j+1
}
test.final<-cbind(sub.code.label,test.data)
std.mean.vec<-c(col.number.lst)
collect.std.mean<-test.final[,std.mean.vec]
test.final.test<-write.csv(collect.std.mean,file="test_data_test.csv")
col.names<-colnames(collect.std.mean)
test<-read.csv("test_data_test.csv")
df_test <- test %>%
group_by(Subjects,ActivityCode,ActivityType) %>%
summarise_each(funs(mean))
df_test<-subset(df_test,select = -X)
#write.file<-write.csv(df_test,file="write_df_test.csv")
#This is a replica of the code above for train data set
j<-1
col.number<-col.number.lst<-feature.name.lst<-temp.col.mean<-NULL
subjects<-read.table("subject_train.txt")
act.code<-read.table("y_train.txt")
act.label<-read.table("activity_labels.txt")
code.label<-merge(act.code,act.label) ##naming the columns and then merging will cause the system to hang, requires a reboot!
colnames(code.label)[1]<-paste("ActivityCode")
colnames(code.label)[2]<-paste("ActivityType")
colnames(subjects)[1]<-paste("Subjects")
sub.code.label<-cbind(subjects,code.label)
test.data<-read.table("X_train.txt")
features.all<-read.table("features.txt")
features.lst<-features.all[,2]
features.lst.clean<-gsub('\\W',"",features.lst)
df2<-matrix(nrow=14,ncol=79)
for(i in 1:561){
feature.name<-features.lst.clean[i]
features.all.heading<-colnames(test.data)[j]<-paste(feature.name)
if((grepl("mean",feature.name))|(grepl("std",feature.name))){
col.number<-i
col.number.lst<-append(col.number.lst,col.number)
feature.name.lst<-append(feature.name.lst,as.character(feature.name)) #appending characters to a list requires as.character
len<-length(feature.name.lst)
}
j=j+1
}
test.final<-cbind(sub.code.label,test.data)
std.mean.vec<-c(col.number.lst)
collect.std.mean<-test.final[,std.mean.vec]
test.final.test<-write.csv(collect.std.mean,file="test_data_test.csv")
col.names<-colnames(collect.std.mean)
test<-read.csv("test_data_test.csv")
df_train <- test %>%
group_by(Subjects,ActivityCode,ActivityType) %>%
summarise_each(funs(mean))
df_train<-subset(df_train,select = -X)
#write.file<-write.csv(df1,file="write_df_train.csv")
#create tidy data set
tidy.data<-rbind(df_test,df_train)
tidy.data.wrt<-write.csv(tidy.data,file="Tidy_Data.csv")
tidy.data.wrt<-write.table(tidy.data,file="Tidy_Data.txt",row.name=FALSE)
}
|
library(tidyverse)
library(modelr)
library(tidyverse)
library(lme4)
library(afex)
library(broom)
library(broom.mixed) #plays will with afex p-values in lmer wrapper
library(ggpubr)
library(car)
library(viridis)
library(psych)
library(corrplot)
# simulate dataset
sigmoid = function(x) {
p = 1/(1+exp(-x))
return(p)
}
# k = runif(1000, min = 0.001, max = 0.25)
# delay = runif(10000, min = 1, max = 300)
# sir = runif(10000, min = 1, max = 50)
# ldr = runif(10000, min = 50, max = 100)
# # compute variables
# dd <- as_tibble(data.frame(k, delay, sir, ldr))
# dd <- dd %>% mutate(ldr_disc = ldr/(1+k*delay),
# k_ind = (ldr/sir - 1)/delay,
# value_diff = ldr_disc - sir,
# value_ratio = ldr_disc/sir,
# p_ldr = 1/(1+exp(-value_diff)),
# p_ldr_mlm = 1/(1+exp(-(log(k_ind) - log(k)))),
# p_ldr_mlm_10 = 1/(1+exp(-(10*(log(k_ind) - log(k))))),
# p_ldr_mlm_5 = 1/(1+exp(-(5*(log(k_ind) - log(k))))),
# log_ratio = log(k_ind) - log(k),
# log_diff = log(k_ind) - log(k)
# )
# ggplot(dd, aes(value_diff, log_diff)) + geom_point()
# ggplot(dd, aes(k_ind, k_ind_simp)) + geom_point()
# cor.test(dd$value_diff,dd$log_diff)
# ggplot(dd, aes(value_diff, p_ldr_mlm, color = ldr, alpha = sir)) + geom_point() + geom_smooth()
ggplot(dd, aes(p_ldr, p_ldr_mlm_5, color = ldr, alpha = sir)) + geom_point() + geom_smooth()
mean(dd$value_diff)
plot(dd$value_diff,dd$p_ldr)
MCQ_options=matrix(data=c(
54,55,117,
55,75,61,
19,25,53,
84.5,85,155,
14,25,19,
47,50,160,
15,35,13,
25,60,14,
78,80,162,
40,55,62,
34.75,35,186,
67,75,119,
34,35,186,
27,50,21,
69,85,91,
49,60,89,
80,85,157,
24,35,29,
33,80,14,
28,30,179,
34,50,30,
25,30,80,
41,75,20,
54,60,111,
54,80,30,
22,25,136,
59.75,60,109,
34.5,35,186,
84,85,150,
59.5,60,108),nrow=30,byrow=TRUE)
mcq=as_tibble(as.data.frame(MCQ_options))
names(mcq)=c('sir','ldr','delay')
ks <- runif(100, min = 0.001, max = 0.25)
mcq$k <- NA
dd <- mcq
for (k in ks) {
temp <- mcq
temp$k <- k
dd <- rbind(mcq1,temp)
}
dd <- dd %>% mutate(ldr_disc = ldr/(1+k*delay),
k_ind = (ldr/sir - 1)/delay,
value_diff = ldr_disc - sir,
value_ratio = ldr_disc/sir,
p_ldr = 1/(1+exp(-value_diff)),
p_ldr_mlm = 1/(1+exp(-(log(k_ind) - log(k)))),
p_ldr_mlm_10 = 1/(1+exp(-(10*(log(k_ind) - log(k))))),
p_ldr_mlm_half = 1/(1+exp(-(.5*(log(k_ind) - log(k))))),
p_ldr_mlm_5 = 1/(1+exp(-(5*(log(k_ind) - log(k))))),
log_ratio = log(k_ind) - log(k),
log_diff = log(k_ind) - log(k)
)
# ggplot(dd, aes(value_diff, log_diff)) + geom_point()
# ggplot(dd, aes(k_ind, k_ind_simp)) + geom_point()
# cor.test(dd$value_diff,dd$log_diff)
# ggplot(dd, aes(value_diff, p_ldr_mlm, color = ldr, alpha = sir)) + geom_point() + geom_smooth()
# ggplot(dd, aes(p_ldr, p_ldr_mlm_5, color = ldr, alpha = sir)) + geom_point() + geom_smooth()
# ggplot(dd, aes(p_ldr, p_ldr_mlm_5, color = ldr, alpha = sir)) + geom_point() + geom_smooth(method = 'glm')
dt <- pivot_longer(dd, c(p_ldr_mlm, p_ldr_mlm_10, p_ldr_mlm_half, p_ldr_mlm_5, p_ldr_mlm_100),
names_to = "beta", names_prefix = "p_ldr_mlm", values_to = "p_ldr_mlm")
ggplot(dt, aes(value_diff, p_ldr_mlm, color = sir)) + geom_smooth(method = 'gam') + geom_point() +
facet_wrap(~beta)
ggplot(dt, aes(p_ldr, p_ldr_mlm, color = sir)) + geom_smooth(method = 'gam') + geom_point() +
facet_wrap(~beta)
ggplot(dd, aes(value_diff, p_ldr_mlm, color = k)) + geom_smooth(method = 'gam')
ggplot(dd, aes(value_diff, p_ldr_mlm_5, color = k)) + geom_smooth(method = 'gam')
ggplot(dd, aes(value_diff, p_ldr_mlm_10, color = k)) + geom_smooth(method = 'gam')
ggplot(dd, aes(value_diff, p_ldr_mlm, color = k)) + geom_smooth(method = 'gam')
| /discounting_mlm_approximation_tests.R | no_license | DecisionNeurosciencePsychopathology/MCQ | R | false | false | 4,044 | r | library(tidyverse)
library(modelr)
library(tidyverse)
library(lme4)
library(afex)
library(broom)
library(broom.mixed) #plays will with afex p-values in lmer wrapper
library(ggpubr)
library(car)
library(viridis)
library(psych)
library(corrplot)
# simulate dataset
sigmoid = function(x) {
p = 1/(1+exp(-x))
return(p)
}
# k = runif(1000, min = 0.001, max = 0.25)
# delay = runif(10000, min = 1, max = 300)
# sir = runif(10000, min = 1, max = 50)
# ldr = runif(10000, min = 50, max = 100)
# # compute variables
# dd <- as_tibble(data.frame(k, delay, sir, ldr))
# dd <- dd %>% mutate(ldr_disc = ldr/(1+k*delay),
# k_ind = (ldr/sir - 1)/delay,
# value_diff = ldr_disc - sir,
# value_ratio = ldr_disc/sir,
# p_ldr = 1/(1+exp(-value_diff)),
# p_ldr_mlm = 1/(1+exp(-(log(k_ind) - log(k)))),
# p_ldr_mlm_10 = 1/(1+exp(-(10*(log(k_ind) - log(k))))),
# p_ldr_mlm_5 = 1/(1+exp(-(5*(log(k_ind) - log(k))))),
# log_ratio = log(k_ind) - log(k),
# log_diff = log(k_ind) - log(k)
# )
# ggplot(dd, aes(value_diff, log_diff)) + geom_point()
# ggplot(dd, aes(k_ind, k_ind_simp)) + geom_point()
# cor.test(dd$value_diff,dd$log_diff)
# ggplot(dd, aes(value_diff, p_ldr_mlm, color = ldr, alpha = sir)) + geom_point() + geom_smooth()
ggplot(dd, aes(p_ldr, p_ldr_mlm_5, color = ldr, alpha = sir)) + geom_point() + geom_smooth()
mean(dd$value_diff)
plot(dd$value_diff,dd$p_ldr)
MCQ_options=matrix(data=c(
54,55,117,
55,75,61,
19,25,53,
84.5,85,155,
14,25,19,
47,50,160,
15,35,13,
25,60,14,
78,80,162,
40,55,62,
34.75,35,186,
67,75,119,
34,35,186,
27,50,21,
69,85,91,
49,60,89,
80,85,157,
24,35,29,
33,80,14,
28,30,179,
34,50,30,
25,30,80,
41,75,20,
54,60,111,
54,80,30,
22,25,136,
59.75,60,109,
34.5,35,186,
84,85,150,
59.5,60,108),nrow=30,byrow=TRUE)
mcq=as_tibble(as.data.frame(MCQ_options))
names(mcq)=c('sir','ldr','delay')
ks <- runif(100, min = 0.001, max = 0.25)
mcq$k <- NA
dd <- mcq
for (k in ks) {
temp <- mcq
temp$k <- k
dd <- rbind(mcq1,temp)
}
dd <- dd %>% mutate(ldr_disc = ldr/(1+k*delay),
k_ind = (ldr/sir - 1)/delay,
value_diff = ldr_disc - sir,
value_ratio = ldr_disc/sir,
p_ldr = 1/(1+exp(-value_diff)),
p_ldr_mlm = 1/(1+exp(-(log(k_ind) - log(k)))),
p_ldr_mlm_10 = 1/(1+exp(-(10*(log(k_ind) - log(k))))),
p_ldr_mlm_half = 1/(1+exp(-(.5*(log(k_ind) - log(k))))),
p_ldr_mlm_5 = 1/(1+exp(-(5*(log(k_ind) - log(k))))),
log_ratio = log(k_ind) - log(k),
log_diff = log(k_ind) - log(k)
)
# ggplot(dd, aes(value_diff, log_diff)) + geom_point()
# ggplot(dd, aes(k_ind, k_ind_simp)) + geom_point()
# cor.test(dd$value_diff,dd$log_diff)
# ggplot(dd, aes(value_diff, p_ldr_mlm, color = ldr, alpha = sir)) + geom_point() + geom_smooth()
# ggplot(dd, aes(p_ldr, p_ldr_mlm_5, color = ldr, alpha = sir)) + geom_point() + geom_smooth()
# ggplot(dd, aes(p_ldr, p_ldr_mlm_5, color = ldr, alpha = sir)) + geom_point() + geom_smooth(method = 'glm')
dt <- pivot_longer(dd, c(p_ldr_mlm, p_ldr_mlm_10, p_ldr_mlm_half, p_ldr_mlm_5, p_ldr_mlm_100),
names_to = "beta", names_prefix = "p_ldr_mlm", values_to = "p_ldr_mlm")
ggplot(dt, aes(value_diff, p_ldr_mlm, color = sir)) + geom_smooth(method = 'gam') + geom_point() +
facet_wrap(~beta)
ggplot(dt, aes(p_ldr, p_ldr_mlm, color = sir)) + geom_smooth(method = 'gam') + geom_point() +
facet_wrap(~beta)
ggplot(dd, aes(value_diff, p_ldr_mlm, color = k)) + geom_smooth(method = 'gam')
ggplot(dd, aes(value_diff, p_ldr_mlm_5, color = k)) + geom_smooth(method = 'gam')
ggplot(dd, aes(value_diff, p_ldr_mlm_10, color = k)) + geom_smooth(method = 'gam')
ggplot(dd, aes(value_diff, p_ldr_mlm, color = k)) + geom_smooth(method = 'gam')
|
#' Calculate and Save Bumphunter Method Results for Specified Design Points
#'
#' @description Given a set of design points (treatment effect size to be added
#' and number of repetitions), simulate methylation data with DMRs and then
#' apply the \code{bumphunter} method to them. Write the results to a file.
#'
#' @param beta_mat A beta value matrix for methylation samples from a
#' 450k methylation array with CpG IDs as the row names and sample IDs as
#' the column names. An example is given in the \code{betaVals_mat} data set.
#'
#' @param CPGs_df Annotation table that indicates locations of CpGs.
#' This data frame has CpG IDs as the rows with matching chromosome and
#' location info in the columns. Specifically, the columns are: \code{ILMNID}
#' - the CPG ID; \code{chr} - the chromosome label; and \code{MAPINFO} -
#' the chromosome location. An example is given in the \code{cpgLocation_df}
#' data set.
#'
#' @param Aclusters_df A data frame of beta values and CpG information for
#' clusters of CpGs over a 450k methylation array. The rows correspond to the
#' CPGs. The columns have information on the cluster number, chromosome,
#' cluster start and end locations, and the beta values for each subject
#' grouped by some clinical indicator (e.g. case v. control). An example is
#' given in the \code{startEndCPG_df} data set. This data set can be
#' generated by the file \code{/inst/1_Aclust_data_import.R}
#'
#' @param parallel Should computing be completed over multiple computing cores?
#' Defaults to \code{TRUE}.
#'
#' @param numCores If \code{parallel}, how many cores should be used? Defaults
#' to two less than the number of available cores (as calculated by the
#' \code{\link[parallel]{detectCores}} function). These cores are used
#' internally by the \code{\link[bumphunter]{bumphunter}} function.
#'
#' @param deltas_num A vector of treatment sizes: non-negative real numbers to
#' add to the beta values within randomly-selected clusters for a single
#' class of subjects. This artifically creates differentially-methylated
#' regions (DMRs).
#'
#' @param seeds_int A vector of seed values passed to the
#' \code{\link[base]{Random}} function to enable reproducible results
#'
#' @param cutoffQ_num A vector of quantiles used for picking the cutoff using
#' the permutation distribution, passed through the call to the internal
#' \code{\link{RunBumphunter}} call to \code{\link[bumphunter]{bumphunter}}.
#'
#' @param maxGap_int A vector of maximum location gaps, passed to the
#' \code{\link[bumphunter]{bumphunter}} function. These will be used to
#' define the clusters of locations that are to be analyzed together via the
#' \code{\link[bumphunter]{clusterMaker}} function.
#'
#' @param resultsDir Where should the results be saved? Defaults to
#' \code{Bumphunter_compare/}.
#'
#' @param verbose Should the function print progress messages? Defaults to
#' \code{TRUE}.
#'
#' @return Saves output files in the specified results directory.
#'
#' @details This function creates matrices of all combinations of design points
#' and all combinations of parameters. For each combination, this function
#' executes the internal \code{\link{RunBumphunter}} function and saves the
#' results as a compressed \code{.RDS} file.
#'
#' @importFrom doParallel registerDoParallel
#' @importFrom parallel detectCores
#' @importFrom parallel makeCluster
#' @importFrom parallel stopCluster
#'
#'
#' @export
#'
#' @examples
#' \dontrun{
#' data("betaVals_mat")
#' data("cpgLocation_df")
#' data("startEndCPG_df")
#'
#' WriteBumphunterResults(
#' beta_mat = betaVals_mat,
#' CPGs_df = cpgLocation_df,
#' Aclusters_df = startEndCPG_df
#' )
#' }
WriteBumphunterResults <- function(beta_mat,
CPGs_df,
Aclusters_df,
parallel = TRUE,
numCores = detectCores() - 2,
deltas_num = c(0, 0.025, 0.05, 0.10,
0.15, 0.20, 0.30, 0.40),
seeds_int = c(100, 210, 330, 450, 680),
cutoffQ_num = c(0.9, 0.95, 0.99),
maxGap_int = c(200, 250, 500, 750, 1000),
resultsDir = "Bumphunter_compare/",
verbose = TRUE){
dir.create(paste0("./", resultsDir), showWarnings = FALSE)
### Data Simulation Outer Loop ###
designPts_mat <- expand.grid(deltas_num, seeds_int)
paramsGrid_mat <- expand.grid(cutoffQ_num, maxGap_int)
for(i in 1:nrow(designPts_mat)){
### Generate Data Set ###
delta <- designPts_mat[i, 1]
seed <- designPts_mat[i, 2]
treatment_ls <- SimulateData(beta_mat = beta_mat,
Aclusters_df = Aclusters_df,
delta_num = delta,
seed_int = seed)
betas_df <- treatment_ls$simBetaVals_df
### Data Wrangling ###
mergedBetas_df <- merge(betas_df, CPGs_df,
by.x = "row.names",
by.y = "ILMNID")
cpgInfo_df <- subset(mergedBetas_df, select = c("chr", "MAPINFO"))
cpgInfo_df$chr <- substr(cpgInfo_df$chr, 4, 6)
betaSorted_df <- mergedBetas_df
row.names(betaSorted_df) <- betaSorted_df$Row.names
betaSorted_df$Row.names <-
betaSorted_df$chr <-
betaSorted_df$MAPINFO <-
NULL
betaSorted_mat <- as.matrix(betaSorted_df)
### Inner Parameter Grid Search ###
for(j in 1:nrow(paramsGrid_mat)){
### Calculate Method Output ###
cutoffQ <- paramsGrid_mat[j, 1]
maxGap <- paramsGrid_mat[j, 2]
### Parallel Setup ###
if(!parallel){
numCores <- 1
}
# Clean memory
rm(treatment_ls, betas_df, mergedBetas_df, betaSorted_df)
# Make and Register Cluster
clust <- makeCluster(numCores)
registerDoParallel(clust)
suppressMessages(
res_ls <- RunBumphunter(betaVals_mat = betaSorted_mat,
chromos_char = cpgInfo_df$chr,
chromPosit_num = cpgInfo_df$MAPINFO,
cpgLocation_df = CPGs_df,
pickCutoffQ_num = cutoffQ,
maxGap_int = maxGap,
numCores = numCores)
)
stopCluster(clust)
### Define NULL Data ###
if(is.null(res_ls[[1]])){
res_ls[[1]] <- data.frame(
dmr.chr = NA_character_,
dmr.start = NA_integer_,
dmr.end = NA_integer_,
chr = NA_character_,
start = NA_integer_,
end = NA_integer_,
value = NA_real_,
area = NA_real_,
cluster = NA_integer_,
indexStart = NA_integer_,
indexEnd = NA_integer_,
L = NA_integer_,
clusterL = NA_integer_,
p.value = NA_real_,
fwer = NA_real_,
p.valueArea = NA_real_,
fwerArea = NA_real_,
dmr.pval = NA_real_,
dmr.n.cpgs = NA_integer_
)
}
### Save Results ###
file_char <- paste0(
resultsDir, "BumphunterResults_delta", delta, "_seed", seed,
"_pickQ", cutoffQ, "_maxGap", maxGap, ".RDS"
)
if(verbose){
message("Saving results to file ", file_char, "\n")
}
saveRDS(res_ls, file = file_char)
} # END for(j)
} # END for(i)
}
| /R/4_simulate_and_save_Bumphunter_results.R | no_license | jennyjyounglee/DMRcomparePaper | R | false | false | 7,834 | r | #' Calculate and Save Bumphunter Method Results for Specified Design Points
#'
#' @description Given a set of design points (treatment effect size to be added
#' and number of repetitions), simulate methylation data with DMRs and then
#' apply the \code{bumphunter} method to them. Write the results to a file.
#'
#' @param beta_mat A beta value matrix for methylation samples from a
#' 450k methylation array with CpG IDs as the row names and sample IDs as
#' the column names. An example is given in the \code{betaVals_mat} data set.
#'
#' @param CPGs_df Annotation table that indicates locations of CpGs.
#' This data frame has CpG IDs as the rows with matching chromosome and
#' location info in the columns. Specifically, the columns are: \code{ILMNID}
#' - the CPG ID; \code{chr} - the chromosome label; and \code{MAPINFO} -
#' the chromosome location. An example is given in the \code{cpgLocation_df}
#' data set.
#'
#' @param Aclusters_df A data frame of beta values and CpG information for
#' clusters of CpGs over a 450k methylation array. The rows correspond to the
#' CPGs. The columns have information on the cluster number, chromosome,
#' cluster start and end locations, and the beta values for each subject
#' grouped by some clinical indicator (e.g. case v. control). An example is
#' given in the \code{startEndCPG_df} data set. This data set can be
#' generated by the file \code{/inst/1_Aclust_data_import.R}
#'
#' @param parallel Should computing be completed over multiple computing cores?
#' Defaults to \code{TRUE}.
#'
#' @param numCores If \code{parallel}, how many cores should be used? Defaults
#' to two less than the number of available cores (as calculated by the
#' \code{\link[parallel]{detectCores}} function). These cores are used
#' internally by the \code{\link[bumphunter]{bumphunter}} function.
#'
#' @param deltas_num A vector of treatment sizes: non-negative real numbers to
#' add to the beta values within randomly-selected clusters for a single
#' class of subjects. This artifically creates differentially-methylated
#' regions (DMRs).
#'
#' @param seeds_int A vector of seed values passed to the
#' \code{\link[base]{Random}} function to enable reproducible results
#'
#' @param cutoffQ_num A vector of quantiles used for picking the cutoff using
#' the permutation distribution, passed through the call to the internal
#' \code{\link{RunBumphunter}} call to \code{\link[bumphunter]{bumphunter}}.
#'
#' @param maxGap_int A vector of maximum location gaps, passed to the
#' \code{\link[bumphunter]{bumphunter}} function. These will be used to
#' define the clusters of locations that are to be analyzed together via the
#' \code{\link[bumphunter]{clusterMaker}} function.
#'
#' @param resultsDir Where should the results be saved? Defaults to
#' \code{Bumphunter_compare/}.
#'
#' @param verbose Should the function print progress messages? Defaults to
#' \code{TRUE}.
#'
#' @return Saves output files in the specified results directory.
#'
#' @details This function creates matrices of all combinations of design points
#' and all combinations of parameters. For each combination, this function
#' executes the internal \code{\link{RunBumphunter}} function and saves the
#' results as a compressed \code{.RDS} file.
#'
#' @importFrom doParallel registerDoParallel
#' @importFrom parallel detectCores
#' @importFrom parallel makeCluster
#' @importFrom parallel stopCluster
#'
#'
#' @export
#'
#' @examples
#' \dontrun{
#' data("betaVals_mat")
#' data("cpgLocation_df")
#' data("startEndCPG_df")
#'
#' WriteBumphunterResults(
#' beta_mat = betaVals_mat,
#' CPGs_df = cpgLocation_df,
#' Aclusters_df = startEndCPG_df
#' )
#' }
WriteBumphunterResults <- function(beta_mat,
CPGs_df,
Aclusters_df,
parallel = TRUE,
numCores = detectCores() - 2,
deltas_num = c(0, 0.025, 0.05, 0.10,
0.15, 0.20, 0.30, 0.40),
seeds_int = c(100, 210, 330, 450, 680),
cutoffQ_num = c(0.9, 0.95, 0.99),
maxGap_int = c(200, 250, 500, 750, 1000),
resultsDir = "Bumphunter_compare/",
verbose = TRUE){
dir.create(paste0("./", resultsDir), showWarnings = FALSE)
### Data Simulation Outer Loop ###
designPts_mat <- expand.grid(deltas_num, seeds_int)
paramsGrid_mat <- expand.grid(cutoffQ_num, maxGap_int)
for(i in 1:nrow(designPts_mat)){
### Generate Data Set ###
delta <- designPts_mat[i, 1]
seed <- designPts_mat[i, 2]
treatment_ls <- SimulateData(beta_mat = beta_mat,
Aclusters_df = Aclusters_df,
delta_num = delta,
seed_int = seed)
betas_df <- treatment_ls$simBetaVals_df
### Data Wrangling ###
mergedBetas_df <- merge(betas_df, CPGs_df,
by.x = "row.names",
by.y = "ILMNID")
cpgInfo_df <- subset(mergedBetas_df, select = c("chr", "MAPINFO"))
cpgInfo_df$chr <- substr(cpgInfo_df$chr, 4, 6)
betaSorted_df <- mergedBetas_df
row.names(betaSorted_df) <- betaSorted_df$Row.names
betaSorted_df$Row.names <-
betaSorted_df$chr <-
betaSorted_df$MAPINFO <-
NULL
betaSorted_mat <- as.matrix(betaSorted_df)
### Inner Parameter Grid Search ###
for(j in 1:nrow(paramsGrid_mat)){
### Calculate Method Output ###
cutoffQ <- paramsGrid_mat[j, 1]
maxGap <- paramsGrid_mat[j, 2]
### Parallel Setup ###
if(!parallel){
numCores <- 1
}
# Clean memory
rm(treatment_ls, betas_df, mergedBetas_df, betaSorted_df)
# Make and Register Cluster
clust <- makeCluster(numCores)
registerDoParallel(clust)
suppressMessages(
res_ls <- RunBumphunter(betaVals_mat = betaSorted_mat,
chromos_char = cpgInfo_df$chr,
chromPosit_num = cpgInfo_df$MAPINFO,
cpgLocation_df = CPGs_df,
pickCutoffQ_num = cutoffQ,
maxGap_int = maxGap,
numCores = numCores)
)
stopCluster(clust)
### Define NULL Data ###
if(is.null(res_ls[[1]])){
res_ls[[1]] <- data.frame(
dmr.chr = NA_character_,
dmr.start = NA_integer_,
dmr.end = NA_integer_,
chr = NA_character_,
start = NA_integer_,
end = NA_integer_,
value = NA_real_,
area = NA_real_,
cluster = NA_integer_,
indexStart = NA_integer_,
indexEnd = NA_integer_,
L = NA_integer_,
clusterL = NA_integer_,
p.value = NA_real_,
fwer = NA_real_,
p.valueArea = NA_real_,
fwerArea = NA_real_,
dmr.pval = NA_real_,
dmr.n.cpgs = NA_integer_
)
}
### Save Results ###
file_char <- paste0(
resultsDir, "BumphunterResults_delta", delta, "_seed", seed,
"_pickQ", cutoffQ, "_maxGap", maxGap, ".RDS"
)
if(verbose){
message("Saving results to file ", file_char, "\n")
}
saveRDS(res_ls, file = file_char)
} # END for(j)
} # END for(i)
}
|
# Rdata sets
https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/00Index.html
data(CO2)
head(CO2)
| /Data/Rdatasets.R | no_license | anhnguyendepocen/Ranalytics18 | R | false | false | 108 | r | # Rdata sets
https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/00Index.html
data(CO2)
head(CO2)
|
################################################################################
################################################################################
# Spatial and temporal diversity trends in the Niagara River fish assemblage
# Karl A. Lamothe, Justin A. G. Hubbard, D. Andrew R. Drake
# R Code prepared by Karl A. Lamothe, PhD - Karl.Lamothe@dfo-mpo.gc.ca
# 2020-10-28 revision; R version 4.0.2
################################################################################
################################################################################
# Load libraries
library(pacman) # For p_load function
p_load(xlsx) # For importing xlsx documents
p_load(ggplot2) # For plotting
p_load(ggrepel) # For plotting
p_load(psych) # For correlation calculations
p_load(vegan) # For multivariate analyses
p_load(FD) # For functional diversity analysis
p_load(corrplot)# For correlation analysis
p_load(tidyr) # For reshaping Data
p_load(dplyr) # For reshaping Data
# Personal ggplot theme
theme_me <- theme_bw() +
theme(axis.title=element_text(family="sans", colour="black"),
axis.text.x=element_text(size=10, family="sans", colour="black"),
axis.text.y=element_text(size=10, family="sans", colour="black"),
legend.title=element_text(size=10, family="sans", colour="black"),
legend.text=element_text(size=10, family="sans", colour="black"),
panel.border = element_rect(colour = "black", fill=NA),
axis.ticks = element_line(colour="black"))
# To plot multiple ggplots in one pane
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
library(grid)
plots <- c(list(...), plotlist)
numPlots = length(plots)
if (is.null(layout)) {
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))}
if (numPlots==1) {
print(plots[[1]])
} else {
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
for (i in 1:numPlots) {
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))}}
}
################################################################################
# Load data
################################################################################
Fish.traits <- read.xlsx("NiagaraRiverFishDiv.xlsx", header=T,
sheetName= "NiagaraStudyTraits")
Habitat <- read.xlsx("NiagaraRiverFishDiv.xlsx", header=T,
sheetName= "Habitat")
Fish.comm <- read.xlsx("NiagaraRiverFishDiv.xlsx", header=T,
sheetName= "FishCommunity")
################################################################################
# Check data
################################################################################
head(Fish.traits) # Data are ordered by common name
str(Fish.traits)
# Fish community CPUE data frame
Fish.comm.CPUE <- Fish.comm[10:74]/Fish.comm$Effort_sec # CPUE
colnames(Fish.comm.CPUE) <- Fish.traits$CODE # Shortens species names
# Observations summed across 1000 m transects
Fishagg<-aggregate(Fish.comm[8:74], list(Site.No = Fish.comm$Site.No,
Year = Fish.comm$Year,
Season = Fish.comm$Season), sum)
head(Fishagg)
Fishagg <- Fishagg[-5] # Remove aggregated sampling pass variable
# Order observations by Site
Fishagg <- Fishagg[order(Fishagg$Site.No),]
# Set up data frame for future RDA
Fish.RDA <- Fishagg[5:69]
colnames(Fish.RDA) <- Fish.traits$CODE
# Presence absence data frame
Fish.comm.PA <- Fish.comm.CPUE
Fish.comm.PA[Fish.comm.PA > 0] <- 1
################################################################################
################################################################################
############ Figure 1. Abundance and CPUE of species ###########################
################################################################################
################################################################################
#Total Counts
Fish.Counts <- as.data.frame(cbind(Count=colSums(Fishagg[5:69]),
Common=as.character(Fish.traits$COMMONNAME)))
# Ensure proper class
str(Fish.Counts)
Fish.Counts$Count <- as.numeric(Fish.Counts$Count)
# Only plot species where more than 100 were caught
Fish.Counts2 <- Fish.Counts[Fish.Counts$Count>100,]
################################################################################
# Plot Total Catch
################################################################################
Fish.Counts2$Common <- factor(Fish.Counts2$Common, levels = Fish.Counts2$Common[order(Fish.Counts2$Count)])
Countplot<-ggplot(Fish.Counts2, aes(x = reorder(Common,Count), y = Count))+
geom_bar(stat="identity")+ylab("Total caputured")+ xlab("Species")+
coord_flip()+
theme_me
Countplot
################################################################################
# CPUE by river section
################################################################################
# Lower section
Fish.comm.CPUE.lower <- Fish.comm[Fish.comm$Section=="Lower",]
Fish.comm.CPUE.lower <- Fish.comm.CPUE.lower[10:74]/Fish.comm.CPUE.lower$Effort
# Upper section
Fish.comm.CPUE.upper <- Fish.comm[Fish.comm$Section=="Upper",]
Fish.comm.CPUE.upper <- Fish.comm.CPUE.upper[10:74]/Fish.comm.CPUE.upper$Effort
# Combine
Fishes<-as.data.frame(rbind(Fish.comm.CPUE.lower,Fish.comm.CPUE.upper))
Section<-c(rep("Lower",length(Fish.comm.CPUE.lower$Alewife)),
rep("Upper",length(Fish.comm.CPUE.upper$Alewife)))
Fishes<-cbind(Fishes, Section)
# Make Data frames
Fish.CPUE.mean.section<-as.data.frame(aggregate(Fishes[1:65],
list(Fishes$Section),mean))
Fish.CPUE.mean.section.t<-t(Fish.CPUE.mean.section) #transpose
Fish.CPUE.mean.section.t<-Fish.CPUE.mean.section.t[-1,] # remove first row
Species<-colnames(Fish.CPUE.mean.section[2:66]) #Species
Fish.CPUE.mean.section.t<-cbind(Fish.CPUE.mean.section.t,Species) # combine
colnames(Fish.CPUE.mean.section.t)<-c("Lower","Upper","Species")
Fish.CPUE.mean.section.t<-as.data.frame(Fish.CPUE.mean.section.t)
# Check class
str(Fish.CPUE.mean.section.t)
Fish.CPUE.mean.section.t$Upper<-as.numeric(Fish.CPUE.mean.section.t$Upper)
Fish.CPUE.mean.section.t$Lower<-as.numeric(Fish.CPUE.mean.section.t$Lower)
# Remove periods and substitute space for species names
Fish.CPUE.mean.section.t$Species<-gsub(".", " ",
Fish.CPUE.mean.section.t$Species,
fixed=TRUE)
head(Fish.CPUE.mean.section.t)
# Only use the same fishes from Total catch plot
CPUE2<-Fish.CPUE.mean.section.t[match(Fish.Counts2$Common,
Fish.CPUE.mean.section.t$Species), ]
CPUE3<-as.data.frame(cbind(Species=rep(CPUE2$Species,2),
CPUE = c(CPUE2$Upper,CPUE2$Lower),
Section = c(rep("Upper",length(CPUE2$Upper)),
rep("Lower",length(CPUE2$Lower))
)))
CPUE3$CPUE<-as.numeric(CPUE3$CPUE)
################################################################################
# Plot CPUE by section
################################################################################
CPUEplot<-ggplot(CPUE3, aes(reorder(Species, CPUE), CPUE, fill=Section))+
geom_bar(stat="identity", position="dodge")+
scale_fill_manual(values=c("black","grey"))+
ylab("CPUE") + xlab("Species") +
coord_flip()+
theme_me+
theme(
legend.position = c(.95, .25),
legend.justification = c("right", "bottom"),
legend.box.just = "right",
legend.margin = margin(6, 6, 6, 6),
legend.background = element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank()
)
CPUEplot
#dev.off()
#tiff("Figure1.tiff", width = 6, height = 4.5, units = 'in', res = 1000)
multiplot(Countplot,CPUEplot,cols=2)
#dev.off()
################################################################################
################################################################################
#################### Summarize taxonomic diversity #############################
################################################################################
################################################################################
length(unique(Fish.traits$GENUS))
length(unique(Fish.traits$FAMILY))
# Summarize abundance of species
colnames(Fish.comm)
colSums(Fish.comm[c(10:74)]) #species specific catch
# Introduced, reintroduced, reportedly introduced, probably introduced
Introduced<-colnames(Fish.comm[c(10,12,13,22,25,26,27,37,55,56,58,59,60,71)])
Introduced
# Total number caught
sum(Fish.comm[c(10,12,13,22,25,26,27,37,55,56,58,59,60,71)]) #3568
# Proportion of catch
sum(Fish.comm[c(10,12,13,22,25,26,27,37,55,56,58,59,60,71)])/sum(Fish.comm[c(10:74)])
# 0.086
# Number of observations for each species that was caught
colnames(Fishagg)
Fish.agg.PA <- Fishagg[5:69]
Fish.agg.PA[Fish.agg.PA > 0] <- 1
Fish.agg.PA <- cbind(Fish.agg.PA, Site.No = Fishagg$Site.No)
# Number of sites present
colSums(aggregate(Fish.agg.PA[1:65], list(Site.No = Fish.agg.PA$Site.No), sum))
# Total number of white sucker captured
sum(Fish.comm$White.Sucker)
# Proportion of sites white sucker captured
84/88 #95.5%
# Emerald Shiner
sum(Fish.comm$Emerald.Shiner)
77/88 #87.5
# Yellow Perch
sum(Fish.comm$Yellow.Perch)
79/88 #89.8
# Seasonal species catch
Seasonal<-aggregate(Fish.comm[c(10:74)], by = list(Year = Fish.comm$Year,
Season = Fish.comm$Season,
Section = Fish.comm$Section),
FUN = sum)
Seasonal
z<-aggregate(Fish.comm[c(10:74)], by = list(Season=Fish.comm$Section), FUN = sum)
rowSums(z[2:66])
z<-(aggregate(Fish.comm[c(10:74)], by = list(Season=Fish.comm$Year), FUN = sum))
rowSums(z[2:66])
z<-aggregate(Fish.comm[c(10:74)], by = list(Season=Fish.comm$Season), FUN = sum)
rowSums(z[2:66])
rowSums(Seasonal[4:68])
# Number of species per section
Section2<-aggregate(Fish.comm[c(10:74)], by = list(Season=Fish.comm$Section),
FUN = sum)
Section2[Section2>0] <-1
rowSums(Section2[2:66])
#########################################################################
#########################################################################
##################### Prepare data for RDA ##############################
#########################################################################
#########################################################################
colnames(Habitat)
Habitat1<-as.data.frame(cbind(Site.No = Habitat$Site.No,
Season = as.character(Habitat$Season),
Year = as.character(Habitat$Year),
Section = as.character(Habitat$Section),
Temp = Habitat$WaterTemp,
Cond = Habitat$Conductivity,
DO = Habitat$DO,
Turb = Habitat$Turbidity,
Depth = Habitat$AvDepth,
WV = Habitat$AvWaterVelocity,
Veg = Habitat$Submerged,
dMouth = Habitat$dMouth))
str(Habitat1)
# Convert back to numeric variables
Columns<-colnames(Habitat1[5:12])
Habitat1[Columns] <- sapply(Habitat1[Columns],as.numeric)
# Calculate pearson correlations
cor_mat <- cor(Habitat1[,c(5:12)], method='pearson')
###############################################################################
# Figure S2 ###################################################################
###############################################################################
par(xpd=T)
corrplot.mixed(cor_mat, tl.pos='lt', tl.cex=1, number.cex=1, addCoefasPercent=T,
mar = c(1, 1, 4, 1), tl.col="black")
################################################################################
# Table 1 ######################################################################
################################################################################
length(Habitat1$Section[Habitat1$Section=="Lower"])
length(Habitat1$Section[Habitat1$Section=="Upper"])
aggregate(.~Section, Habitat1[4:12], mean)
aggregate(.~Section, Habitat1[4:12], min)
aggregate(.~Section, Habitat1[4:12], max)
# Aggregate per site
head(Habitat1)
Hab.agg <- aggregate(Habitat1[c(1,5:12)], list(Site.No = Habitat1$Site.No,
Year = Habitat1$Year,
Season = Habitat1$Season), mean)
head(Hab.agg)
Hab.agg <- Hab.agg[-c(4)] # Remove aggregated site variable
# Order the data by Site No
Hab.agg$Site.No<-as.numeric(Hab.agg$Site.No)
Hab.agg <- Hab.agg[order(Hab.agg$Site.No),]
# Scaling continuous covariates to improve model fit and interpretation
Habitat.RDA <- as.data.frame(scale(Hab.agg[4:11], center = TRUE))
head(Habitat.RDA)
################################################################################
################################################################################
#################### Redundancy Analysis (RDA) #################################
################################################################################
################################################################################
#Transform fish data to reduce effects of abundant species
FishesTransformed <- decostand(Fish.RDA, method = "hellinger")
#reproducible results (unnecessary for performing analysis)
set.seed(2336)
# Stepwise model selection
head(Habitat.RDA)
mod0<-rda(FishesTransformed ~ 1, Habitat.RDA)
mod1<-rda(FishesTransformed ~ ., Habitat.RDA)
rda_select.r <-ordistep(mod0, scope = formula(mod1), direction = "both",
Pin = 0.05, Pout = 0.10, perm.max = 9999)
# Run final model
NR.rda <-rda(FishesTransformed ~ Depth + Temp + dMouth + Veg,
data = Habitat.RDA)
summary(NR.rda)
################################################################################
############################### Figure 2: Triplot ##############################
################################################################################
# Observation scores (site scores)
scores <- data.frame(Habitat.RDA,NR.rda$CCA$u)
# Species scores
vscores <- data.frame(NR.rda$CCA$v)
# Covariate scores
var.score <- data.frame(NR.rda$CCA$biplot[,1:2])
var.score.sc <- var.score * 0.8 # Scaling covariates for plotting purposes
var.score.sc$variables <- c("Depth", "Temp", "dMouth", "Veg")
# Only plotting the most abundant species for visualization purposes
rownames(vscores)
vscores2.sc <- vscores[c(6,9,18,21,25,30,35,46,54,56,63,65),]
Section <- c(rep("Upper", 52), rep("Lower", 36))
# Create plot of model
ggRDA <- ggplot(scores, aes(x = RDA1, y = RDA2)) +
geom_hline(yintercept=0,linetype="dashed",col="black")+
geom_vline(xintercept=0,linetype="dashed",col="black")+
geom_point(aes(shape=Section, color=Hab.agg$Season)) +
scale_shape_manual(name = "River Section", values = c(15:17))+
scale_color_manual(name = "Season",
values=c("black","lightgrey","darkgrey"),
labels = c("Fall","Spring","Summer"))+
geom_segment(data = vscores2.sc,
aes(x = 0, y = 0, xend = RDA1, yend = RDA2),
arrow=arrow(length=unit(0.2,"cm")),
color = "black",inherit.aes = FALSE,lwd=0.25) +
geom_text(data = vscores2.sc,
aes(x = RDA1, y = RDA2, label = rownames(vscores2.sc)),
col = 'black', inherit.aes = FALSE,
nudge_y = ifelse(vscores2.sc$RDA2 > 0, 0.02, -0.02),
nudge_x = ifelse(vscores2.sc$RDA1 > 0, 0.02, -0.02),size=3)+
geom_segment(data = var.score.sc,
aes(x = 0, y = 0, xend = RDA1, yend = RDA2),
arrow = arrow(length=unit(0.2,"cm")),
color = 'black', inherit.aes = FALSE, lwd=0.25) +
geom_text(data = var.score.sc,
aes(x = RDA1, y = RDA2, label = variables),
col = 'black', inherit.aes = FALSE,
nudge_y = ifelse(var.score.sc$RDA2 > 0, 0.02, -0.02),
nudge_x = ifelse(var.score.sc$RDA1 > 0, 0.02, -0.02),size=3) +
labs(x = "RDA Axis 1", y = "RDA Axis 2") +
theme_me + theme(legend.justification = c(1,0),
legend.position = c(1,0),
legend.background = element_blank(),
legend.box = 'horizontal')
ggRDA
#tiff("ggRDA.tiff", width = 6, height = 4, units = 'in', res = 1000)
#ggRDA
#dev.off()
################################################################################
################################################################################
############ Non-metric multidimensional scaling (NMDS) ########################
################################################################################
################################################################################
# Prepare data
colnames(Fish.RDA)
#habitat data
colnames(Habitat.RDA)
Habitat.NMDS<-Habitat.RDA[c(1,5,7,8)]
#comm data
NMDSdist<-decostand(Fish.RDA, method="hellinger")
#Final
NMDSord <- metaMDS(NMDSdist,k=2, try=20, trymax=1000) #final used
NMDSord
# Stressplot
stressplot(NMDSord)
# Shepards test/goodness of fit
goodness(NMDSord) # Produces a results of test statistics for goodness of fit for each point
# fit environmental variables
en = envfit(NMDSord, Habitat.NMDS, permutations = 9999, na.rm = TRUE,
choices=c(1,2))
en
# data
data.scores = as.data.frame(scores(NMDSord))
head(data.scores)
data.scores$season = Hab.agg$Season
en_coord_cont = as.data.frame(scores(en, "vectors"))
# for plotting species
Species<-as.data.frame(NMDSord$species)
Spec<-rownames(Species)
Count<-Fish.Counts$Count
Species<-cbind(Species, Spec,Count)
Species2<-Species[Species$Count>25,]
Species3<-Species[Species$Count>600,] #only plotting abundant species
################################################################################
############################ Figure S3 #########################################
################################################################################
ggNMDSENV <- ggplot(data.scores, aes(x = NMDS1, y = NMDS2)) +
geom_hline(yintercept=0,linetype="dashed",col="black")+
geom_vline(xintercept=0,linetype="dashed",col="black")+
geom_point(aes(color=Hab.agg$Season, shape=Section),
size=3, alpha=0.5) +
scale_shape_manual(name = "River Section", values = c(15:17))+
scale_colour_manual(values = c("orange", "violet","green"),
labels = c("Fall","Spring","Summer")) +
geom_segment(data=Species3, aes(x=0,y=0,xend=MDS1, yend=MDS2),
arrow=arrow(length=unit(0.2,"cm")),
size =0.5, colour = "black") +
geom_text(data=Species3, aes(x=MDS1, y=MDS2),
label=Species3$Spec, check_overlap = F,
nudge_y = ifelse(Species3$MDS2 > 0, 0.03, -0.03),
nudge_x = ifelse(Species3$MDS1 > 0, 0.03, -0.03))+
geom_segment(aes(x = 0, y = 0,
xend = NMDS1, yend = NMDS2),
arrow=arrow(length=unit(0.2,"cm")),
data = en_coord_cont, size =0.5, colour = "black") +
geom_text(data = en_coord_cont, aes(x = NMDS1, y = NMDS2),
colour = "black",
label = row.names(en_coord_cont),
nudge_y = ifelse(en_coord_cont$NMDS2 > 0, 0.03, -0.03),
nudge_x = ifelse(en_coord_cont$NMDS1 > 0, 0.03, -0.03)) +
labs(colour = "Season")+
theme_me+
theme(legend.position = c(.95, 0.75),
legend.justification = c("right", "top"),
legend.box.just = "right",
legend.margin = margin(6, 6, 6, 6))
ggNMDSENV
################################################################################
################################################################################
################ Functional Diversity Analysis #################################
################################################################################
################################################################################
# Provide correlation of trait data
head(Fish.traits)
Traitscorr<-Fish.traits[-c(1:8)]
colSums(Traitscorr[2:20])/65
str(Traitscorr)
################################################################################
########################## Figure S4 ###########################################
################################################################################
cor_mat <- cor(Traitscorr, method='spearman')
corrplot.mixed(cor_mat, tl.pos='lt', tl.cex=1, number.cex=1, addCoefasPercent=T,
mar = c(1, 1, 4, 1), tl.col="black")
# Reduce three trait categories into respective trait dimensions
# Diet analysis - what the species eat
# Removed correlated variables and variables without variation
Diet.data <- as.data.frame(cbind(Algae = Fish.traits$ALGPHYTO,
Macrophyte = Fish.traits$MACVASCU,
Fish = Fish.traits$FSHCRCRB,
Eggs = Fish.traits$EGGS))
# PCA of diet preference
F.transformed1 <- decostand(Diet.data, method = "hellinger")
PCA1 <- princomp(F.transformed1, cor=FALSE, scores=TRUE)
summary(PCA1)
# Quick plots
par(xpd=F)
plot(PCA1)
biplot(PCA1, xlim = c(-.4,.4), ylim = c(-.4,.3), cex = 0.8)
abline(v=0,h=0,lty="dashed")
# Substrate analysis
Habitat.data <- as.data.frame(cbind(CLAYSILT = Fish.traits$CLAYSILT,
SAND = Fish.traits$SAND,
GRAVEL = Fish.traits$GRAVEL,
COBBLE = Fish.traits$COBBLE,
BOULDER = Fish.traits$BOULDER,
BEDROCK = Fish.traits$BEDROCK,
VEGETAT = Fish.traits$VEGETAT,
LWD = Fish.traits$LWD,
DEBRDETR = Fish.traits$DEBRDETR))
# PCA on Substrate data
F.transformed2 <- decostand(Habitat.data, method = "hellinger")
PCA2 <- princomp(F.transformed2, cor = FALSE, scores = TRUE)
summary(PCA2)
# Quick plots
plot(PCA2)
biplot(PCA2, xlim = c(-.4,.4), ylim = c(-.4,.3), cex = 0.8)
abline(v=0,h=0,lty="dashed")
# Reproduction analysis
Reprod<-Fish.traits[c(17,18)]
F.transformed3 <- decostand(Reprod, method="hellinger")
PCA3<-princomp(F.transformed3, cor=FALSE, scores = TRUE)
summary(PCA3)
# Quick plots
plot(PCA3)
biplot(PCA3, xlim = c(-.4,.4), ylim = c(-.4,.3), cex = 0.8)
abline(v=0,h=0,lty="dashed")
# Fuction to assess significance of the principal components.
sign.pc <-function(x, R=9999, s=10, cor=T,...){
pc.out <- princomp(x, cor=cor,...) # run PCA
# the proportion of variance of each PC
pve=(pc.out$sdev^2/sum(pc.out$sdev^2))[1:s]
pve.perm <- matrix(NA,ncol=s,nrow=R)
for(i in 1:R){
x.perm <- apply(x,2,sample)# permutate each column
pc.perm.out <- princomp(x.perm,cor=cor,...)# run PCA
# the proportion of variance of each PC.perm
pve.perm[i,]=(pc.perm.out$sdev^2/sum(pc.perm.out$sdev^2))[1:s]
}
pval<-apply(t(pve.perm)>pve,1,sum)/R # calcalute the p-values
return(list(pve=pve,pval=pval))
}
# Apply the significance function
sign.pc(F.transformed1, cor = FALSE) #Axis 1 is significant
sign.pc(F.transformed2, cor = FALSE) #Axes 1 + 2 are significant
sign.pc(F.transformed3, cor = FALSE) #Axis 1 is significant
################################################################################
# Create full data frame for final ordination analysis
Fish.traits.reduced<-data.frame(Spp = Fish.traits$CODE,
Habitat1 = PCA2$scores[,1],
Habitat2 = PCA2$scores[,2],
Diet = PCA1$scores[,1],
Reproduction = PCA3$scores[,1],
Size = scale(Fish.traits$AV.TL.CM,
scale = TRUE, center = TRUE))
rownames(Fish.traits.reduced)<-Fish.traits$CODE
# Look at the variability across data axes
sd(Fish.traits.reduced$Habitat1)
sd(Fish.traits.reduced$Habitat2)
sd(Fish.traits.reduced$Diet)
sd(Fish.traits.reduced$Reproduction)
sd(Fish.traits.reduced$Size)
summary(Fish.traits.reduced$Habitat1)
summary(Fish.traits.reduced$Habitat2)
summary(Fish.traits.reduced$Diet)
summary(Fish.traits.reduced$Reproduction)
summary(Fish.traits.reduced$Size)
################################################################################
# Calculate Functional Diversity Measures
################################################################################
Fishfunction<-dbFD(x = Fish.traits.reduced[2:6], a = Fish.RDA,
w.abun = TRUE, stand.x = TRUE, calc.FRic = TRUE, m = "max",
stand.FRic = FALSE, scale.RaoQ = FALSE,
print.pco = TRUE, calc.FGR = FALSE, messages = TRUE)
# Extract diversity measures per fish community
SpeciesRichness <- Fishfunction$nbsp # Species Richness
FunctionalDivergence <- Fishfunction$FDiv # Functional divergences
FunctionalDispersion <- Fishfunction$FDis # Functional dispersion
Eigen <- Fishfunction$x.values # Eigenvalues
Axes <- Fishfunction$x.axes
Eigen[1]/sum(Eigen) # 29.3%
Eigen[2]/sum(Eigen) # 23.7%
Eigen[3]/sum(Eigen) # 20.0%
################################################################################
################# Figure 3 - Functional Trait PCOA #############################
################################################################################
Ord1<-ggplot(Axes, aes(x = A1, y = A2, label=rownames(Axes))) +
geom_hline(yintercept=0,linetype="dashed",col="black")+
geom_vline(xintercept=0,linetype="dashed",col="black")+
geom_point(pch=20) +
geom_text_repel(min.segment.length = Inf, seed = 42, box.padding = 0.2, size=2) +
xlab("Component 1 (29.3%)")+
ylab("Component 2 (23.7%)")+
theme_me
Ord1
Ord2<-ggplot(Axes, aes(x = A2, y = A3,label=rownames(Axes))) +
geom_hline(yintercept=0,linetype="dashed",col="black")+
geom_vline(xintercept=0,linetype="dashed",col="black")+
geom_point(pch=20) +
geom_text_repel(min.segment.length = Inf, seed = 42, box.padding = 0.2, size=2) +
xlab("Component 2 (23.7%)")+
ylab("Component 3 (20.0%)")+
theme_me
Ord2
#tiff("Figure3.tiff", width = 6.5, height = 4, units = 'in', res = 1000)
multiplot(Ord1,Ord2,cols=2)
#dev.off()
################################################################################
# Create data frame for post-analyses
Gradient.Frame<-data.frame(Site = Hab.agg$Site.No,
Year = Hab.agg$Year,
Season = Hab.agg$Season,
FDis = FunctionalDispersion,
FDiv = FunctionalDivergence,
SpRich = SpeciesRichness,
Section = Section)
head(Gradient.Frame)
str(Gradient.Frame)
{Gradient.Frame$Year <- as.character(Gradient.Frame$Year)
Gradient.Frame$Year <- as.factor(Gradient.Frame$Year)}
# Aggregate functional diversity measures
aggregate(Gradient.Frame[4], list(Gradient.Frame$Season, Gradient.Frame$Section, Gradient.Frame$Year), mean)
aggregate(Gradient.Frame[5], list(Gradient.Frame$Season, Gradient.Frame$Section, Gradient.Frame$Year), mean)
aggregate(Gradient.Frame[4], list(Gradient.Frame$Season, Gradient.Frame$Section, Gradient.Frame$Year), sd)
aggregate(Gradient.Frame[5], list(Gradient.Frame$Season, Gradient.Frame$Section, Gradient.Frame$Year), sd)
###############################################################################
# Permanova to look at differences in functional metrics
###############################################################################
# Functional dispersion
perm.fdis <- adonis(FunctionalDispersion ~ Season + Year + Section,
data = Gradient.Frame, permutations = 9999,
method = "euclidean")
perm.fdis
# Functional divergence
perm.fdiv <- adonis(FunctionalDivergence ~ Season + Year + Section,
data = Gradient.Frame, permutations = 9999,
method = "euclidean")
perm.fdiv
################################################################################
# Summary statistics
################################################################################
aggregate(Gradient.Frame$FDis, by = list(Gradient.Frame$Section), FUN = mean)
aggregate(Gradient.Frame$FDis, by = list(Gradient.Frame$Section), FUN = sd)
aggregate(Gradient.Frame$FDis, by = list(Gradient.Frame$Year), FUN = mean)
aggregate(Gradient.Frame$FDis, by = list(Gradient.Frame$Year), FUN = sd)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Section), FUN = mean)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Section), FUN = sd)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Season), FUN = mean)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Season), FUN = sd)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Year), FUN = mean)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Year), FUN = sd)
################################################################################
# Figure 4: Plotting Functional diversity difference
################################################################################
Fdis.year.box <- ggplot(data = Gradient.Frame,
aes(x = Year, y = FunctionalDispersion)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional dispersion") + theme_me +
theme(panel.background = element_rect(fill = "lightgrey"),
axis.text.x = element_text(angle = 35, hjust = 1))
Gradient.Frame$Season <- factor(Gradient.Frame$Season , levels=c("SPRING","SUMMER","FALL"))
Fdis.season.box <- ggplot(data = Gradient.Frame,
aes(x = Season, y = FunctionalDispersion)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional dispersion") + theme_me +
theme(axis.text.x = element_text(angle = 35, hjust = 1))
Fdis.section.box <- ggplot(data = Gradient.Frame,
aes(x = Section, y = FunctionalDispersion)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional dispersion") + theme_me+
theme(panel.background = element_rect(fill = "lightgrey"),
axis.text.x = element_text(angle = 35, hjust = 1))
Fdiv.year.box <- ggplot(data = Gradient.Frame,
aes(x = Year, y = FunctionalDivergence)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional divergence") + theme_me+
theme(panel.background = element_rect(fill = "lightgrey"),
axis.text.x = element_text(angle = 35, hjust = 1))
Fdiv.season.box <- ggplot(data = Gradient.Frame,
aes(x = Season, y = FunctionalDivergence)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional divergence") + theme_me+
theme(panel.background = element_rect(fill = "lightgrey"),
axis.text.x = element_text(angle = 35, hjust = 1))
Fdiv.section.box <- ggplot(data = Gradient.Frame,
aes(x = Section, y = FunctionalDivergence)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional divergence") + theme_me+
theme(panel.background = element_rect(fill = "lightgrey"),
axis.text.x = element_text(angle = 35, hjust = 1))
###############################################################################
################ Figure 4 Functional Diversity Metrics ########################
###############################################################################
#tiff("Figure4.tiff", width = 6.5, height = 5, units = 'in', res = 1000)
multiplot(Fdis.year.box,Fdiv.year.box,
Fdis.season.box,Fdiv.season.box,
Fdis.section.box,Fdiv.section.box,cols=3)
#dev.off()
###############################################################################
################# Figure 5 Functional dispersion x Functional divergence ######
###############################################################################
fdisfdivplot<-ggplot(Gradient.Frame, aes(x=FDiv, y=FDis, shape=Section,
color=Season, linetype=Section))+
geom_point() +
scale_shape_manual(name = "River Section", values = c(15:17))+
scale_color_manual(name = "Season",
values=c("black","darkgrey","lightgrey"),
labels = c("Fall","Spring","Summer"))+
geom_smooth(method='lm', se=F) +
labs(y="Functional Dispersion",x="Functional Divergence")+
scale_linetype_discrete(name="Season",
breaks=c("Fall","Spring","Summer"),
labels = c("Fall", "Spring", "Summer"))+
theme_me + theme(legend.justification = c("left", "top"),
legend.position = c(0,1),
legend.background = element_blank(),
legend.box = 'vertical',
legend.key = element_rect(fill = NA, colour = NA, size = 0.25))
fdisfdivplot
#tiff("Figure5.tiff", width = 5, height = 3.5, units = 'in', res = 1000)
#fdisfdivplot
#dev.off()
################################################################################
# Plot relationship between functional diversity and habitat variables
plot(Gradient.Frame$FDis~Hab.agg$Temp, pch=20, las=1)
plot(Gradient.Frame$FDis~Hab.agg$Cond, pch=20, las=1)
plot(Gradient.Frame$FDis~Hab.agg$DO, pch=20, las=1)
plot(Gradient.Frame$FDis~Hab.agg$Turb, pch=20, las=1)
plot(Gradient.Frame$FDis~Hab.agg$Depth, pch=20, las=1)
plot(Gradient.Frame$FDis~Hab.agg$WV, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$Temp, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$Cond, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$DO, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$Turb, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$Depth, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$WV, pch=20, las=1)
################################################################################
# Upper versus lower unique species
################################################################################
Fishagg<- cbind(Fishagg,
Section=Gradient.Frame$Section,
FDis=Gradient.Frame$FDis,
FDiv=Gradient.Frame$FDiv,
SpRich=Gradient.Frame$SpRich)
str(Fishagg)
Fishagg$Section<-as.factor(Fishagg$Section)
#Upper
Fish.Upper<-Fishagg[1:52,]
summary(Fish.Upper$Section)
colnames(Fish.Upper)
Fish.Upper<-Fish.Upper[c(1:4,6,18,19,24,26,27,33,49,62,65,71,72,73)]
head(Fish.Upper)
Abund.Upper<-rowSums(Fish.Upper[5:14])
#lower
Fish.Lower<-Fishagg[53:88,]
summary(Fish.Lower$Section)
colnames(Fish.Lower)
Fish.Lower<-Fish.Lower[c(1:4,7,8,20,21,38,41,55,57,71,72,73)]
head(Fish.Lower)
Abund.Lower<-rowSums(Fish.Lower[5:12])
################################################################################
###########Figure 6 Functional dispersion and unique sp abundance ##############
################################################################################
Dis<-ggplot()+
geom_smooth(aes(x=Fish.Upper$FDis, y=Abund.Upper),method="lm", col="black", lwd=0.5)+
geom_point(aes(x=Fish.Upper$FDis, y=Abund.Upper))+
geom_smooth(aes(x=Fish.Lower$FDis, y=Abund.Lower), method="lm", col="grey", lwd=0.5)+
geom_point(aes(x=Fish.Lower$FDis, y=Abund.Lower), col="grey")+ylim(-10,50)+theme_me+
scale_x_continuous(expand=c(0,0), limits=c(0,2.5)) +
scale_y_continuous(expand=c(0,0), limits=c(-50,50)) +
coord_cartesian(xlim=c(0.8,2.5), ylim=c(0,50))+
ylab("Abundance")+xlab("Functional Dispersion")
Dis
Div<-ggplot()+
geom_smooth(aes(x=Fish.Upper$FDiv, y=Abund.Upper), method="lm", col="black", lwd=0.5)+
geom_point(aes(x=Fish.Upper$FDiv, y=Abund.Upper))+
geom_smooth(aes(x=Fish.Lower$FDiv, y=Abund.Lower), method="lm", col="grey", lwd=0.5)+
geom_point(aes(x=Fish.Lower$FDiv, y=Abund.Lower), col="grey")+ylim(-10,50)+
theme_me+
scale_x_continuous(expand=c(0,0), limits=c(0,1.2)) +
scale_y_continuous(expand=c(0,0), limits=c(-50,50)) +
coord_cartesian(xlim=c(0.3,1), ylim=c(0,50))+
ylab("Abundance")+xlab("Functional Divergence")
#tiff("Figure6.tiff", width = 5, height = 3, units = 'in', res = 1000)
multiplot(Dis, Div, cols=2)
#dev.off()
################################################################################
# Calculate distance between Rainbow Smelt and other species
################################################################################
D.RS<-matrix(0)
for(x in 1:(length(Axes$A1))){
D.RS[x]<-sqrt((Axes$A1[x] - Axes$A1[46])^2 +
(Axes$A2[x] - Axes$A2[46])^2 +
(Axes$A3[x] - Axes$A3[46])^2)
}
D.RS <- data.frame(cbind(D.RS, as.character(Fish.traits$COMMONNAME)))
D.RS$D.RS <- as.character(D.RS$D.RS)
D.RS$D.RS <- as.numeric(D.RS$D.RS)
#calculate distance between Rainbow Smelt and other species in RDA
D.RS<-matrix(0)
for(x in 1:(length(vscores$RDA1))){
D.RS[x]<-sqrt((vscores$RDA1[x] - vscores$RDA1[46])^2 +
(vscores$RDA2[x] - vscores$RDA2[46])^2)
}
D.RS <- data.frame(cbind(D.RS, as.character(Fish.traits$COMMONNAME)))
D.RS
D.RS$D.RS <- as.character(D.RS$D.RS)
D.RS$D.RS <- as.numeric(D.RS$D.RS)
| /NiagaraRiverAnalysis.R | permissive | KarlLamothe/NiagaraRiver | R | false | false | 37,932 | r | ################################################################################
################################################################################
# Spatial and temporal diversity trends in the Niagara River fish assemblage
# Karl A. Lamothe, Justin A. G. Hubbard, D. Andrew R. Drake
# R Code prepared by Karl A. Lamothe, PhD - Karl.Lamothe@dfo-mpo.gc.ca
# 2020-10-28 revision; R version 4.0.2
################################################################################
################################################################################
# Load libraries
library(pacman) # For p_load function
p_load(xlsx) # For importing xlsx documents
p_load(ggplot2) # For plotting
p_load(ggrepel) # For plotting
p_load(psych) # For correlation calculations
p_load(vegan) # For multivariate analyses
p_load(FD) # For functional diversity analysis
p_load(corrplot)# For correlation analysis
p_load(tidyr) # For reshaping Data
p_load(dplyr) # For reshaping Data
# Personal ggplot theme
theme_me <- theme_bw() +
theme(axis.title=element_text(family="sans", colour="black"),
axis.text.x=element_text(size=10, family="sans", colour="black"),
axis.text.y=element_text(size=10, family="sans", colour="black"),
legend.title=element_text(size=10, family="sans", colour="black"),
legend.text=element_text(size=10, family="sans", colour="black"),
panel.border = element_rect(colour = "black", fill=NA),
axis.ticks = element_line(colour="black"))
# To plot multiple ggplots in one pane
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
library(grid)
plots <- c(list(...), plotlist)
numPlots = length(plots)
if (is.null(layout)) {
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))}
if (numPlots==1) {
print(plots[[1]])
} else {
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
for (i in 1:numPlots) {
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))}}
}
################################################################################
# Load data
################################################################################
Fish.traits <- read.xlsx("NiagaraRiverFishDiv.xlsx", header=T,
sheetName= "NiagaraStudyTraits")
Habitat <- read.xlsx("NiagaraRiverFishDiv.xlsx", header=T,
sheetName= "Habitat")
Fish.comm <- read.xlsx("NiagaraRiverFishDiv.xlsx", header=T,
sheetName= "FishCommunity")
################################################################################
# Check data
################################################################################
head(Fish.traits) # Data are ordered by common name
str(Fish.traits)
# Fish community CPUE data frame
Fish.comm.CPUE <- Fish.comm[10:74]/Fish.comm$Effort_sec # CPUE
colnames(Fish.comm.CPUE) <- Fish.traits$CODE # Shortens species names
# Observations summed across 1000 m transects
Fishagg<-aggregate(Fish.comm[8:74], list(Site.No = Fish.comm$Site.No,
Year = Fish.comm$Year,
Season = Fish.comm$Season), sum)
head(Fishagg)
Fishagg <- Fishagg[-5] # Remove aggregated sampling pass variable
# Order observations by Site
Fishagg <- Fishagg[order(Fishagg$Site.No),]
# Set up data frame for future RDA
Fish.RDA <- Fishagg[5:69]
colnames(Fish.RDA) <- Fish.traits$CODE
# Presence absence data frame
Fish.comm.PA <- Fish.comm.CPUE
Fish.comm.PA[Fish.comm.PA > 0] <- 1
################################################################################
################################################################################
############ Figure 1. Abundance and CPUE of species ###########################
################################################################################
################################################################################
#Total Counts
Fish.Counts <- as.data.frame(cbind(Count=colSums(Fishagg[5:69]),
Common=as.character(Fish.traits$COMMONNAME)))
# Ensure proper class
str(Fish.Counts)
Fish.Counts$Count <- as.numeric(Fish.Counts$Count)
# Only plot species where more than 100 were caught
Fish.Counts2 <- Fish.Counts[Fish.Counts$Count>100,]
################################################################################
# Plot Total Catch
################################################################################
Fish.Counts2$Common <- factor(Fish.Counts2$Common, levels = Fish.Counts2$Common[order(Fish.Counts2$Count)])
Countplot<-ggplot(Fish.Counts2, aes(x = reorder(Common,Count), y = Count))+
geom_bar(stat="identity")+ylab("Total caputured")+ xlab("Species")+
coord_flip()+
theme_me
Countplot
################################################################################
# CPUE by river section
################################################################################
# Lower section
Fish.comm.CPUE.lower <- Fish.comm[Fish.comm$Section=="Lower",]
Fish.comm.CPUE.lower <- Fish.comm.CPUE.lower[10:74]/Fish.comm.CPUE.lower$Effort
# Upper section
Fish.comm.CPUE.upper <- Fish.comm[Fish.comm$Section=="Upper",]
Fish.comm.CPUE.upper <- Fish.comm.CPUE.upper[10:74]/Fish.comm.CPUE.upper$Effort
# Combine
Fishes<-as.data.frame(rbind(Fish.comm.CPUE.lower,Fish.comm.CPUE.upper))
Section<-c(rep("Lower",length(Fish.comm.CPUE.lower$Alewife)),
rep("Upper",length(Fish.comm.CPUE.upper$Alewife)))
Fishes<-cbind(Fishes, Section)
# Make Data frames
Fish.CPUE.mean.section<-as.data.frame(aggregate(Fishes[1:65],
list(Fishes$Section),mean))
Fish.CPUE.mean.section.t<-t(Fish.CPUE.mean.section) #transpose
Fish.CPUE.mean.section.t<-Fish.CPUE.mean.section.t[-1,] # remove first row
Species<-colnames(Fish.CPUE.mean.section[2:66]) #Species
Fish.CPUE.mean.section.t<-cbind(Fish.CPUE.mean.section.t,Species) # combine
colnames(Fish.CPUE.mean.section.t)<-c("Lower","Upper","Species")
Fish.CPUE.mean.section.t<-as.data.frame(Fish.CPUE.mean.section.t)
# Check class
str(Fish.CPUE.mean.section.t)
Fish.CPUE.mean.section.t$Upper<-as.numeric(Fish.CPUE.mean.section.t$Upper)
Fish.CPUE.mean.section.t$Lower<-as.numeric(Fish.CPUE.mean.section.t$Lower)
# Remove periods and substitute space for species names
Fish.CPUE.mean.section.t$Species<-gsub(".", " ",
Fish.CPUE.mean.section.t$Species,
fixed=TRUE)
head(Fish.CPUE.mean.section.t)
# Only use the same fishes from Total catch plot
CPUE2<-Fish.CPUE.mean.section.t[match(Fish.Counts2$Common,
Fish.CPUE.mean.section.t$Species), ]
CPUE3<-as.data.frame(cbind(Species=rep(CPUE2$Species,2),
CPUE = c(CPUE2$Upper,CPUE2$Lower),
Section = c(rep("Upper",length(CPUE2$Upper)),
rep("Lower",length(CPUE2$Lower))
)))
CPUE3$CPUE<-as.numeric(CPUE3$CPUE)
################################################################################
# Plot CPUE by section
################################################################################
CPUEplot<-ggplot(CPUE3, aes(reorder(Species, CPUE), CPUE, fill=Section))+
geom_bar(stat="identity", position="dodge")+
scale_fill_manual(values=c("black","grey"))+
ylab("CPUE") + xlab("Species") +
coord_flip()+
theme_me+
theme(
legend.position = c(.95, .25),
legend.justification = c("right", "bottom"),
legend.box.just = "right",
legend.margin = margin(6, 6, 6, 6),
legend.background = element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank()
)
CPUEplot
#dev.off()
#tiff("Figure1.tiff", width = 6, height = 4.5, units = 'in', res = 1000)
multiplot(Countplot,CPUEplot,cols=2)
#dev.off()
################################################################################
################################################################################
#################### Summarize taxonomic diversity #############################
################################################################################
################################################################################
length(unique(Fish.traits$GENUS))
length(unique(Fish.traits$FAMILY))
# Summarize abundance of species
colnames(Fish.comm)
colSums(Fish.comm[c(10:74)]) #species specific catch
# Introduced, reintroduced, reportedly introduced, probably introduced
Introduced<-colnames(Fish.comm[c(10,12,13,22,25,26,27,37,55,56,58,59,60,71)])
Introduced
# Total number caught
sum(Fish.comm[c(10,12,13,22,25,26,27,37,55,56,58,59,60,71)]) #3568
# Proportion of catch
sum(Fish.comm[c(10,12,13,22,25,26,27,37,55,56,58,59,60,71)])/sum(Fish.comm[c(10:74)])
# 0.086
# Number of observations for each species that was caught
colnames(Fishagg)
Fish.agg.PA <- Fishagg[5:69]
Fish.agg.PA[Fish.agg.PA > 0] <- 1
Fish.agg.PA <- cbind(Fish.agg.PA, Site.No = Fishagg$Site.No)
# Number of sites present
colSums(aggregate(Fish.agg.PA[1:65], list(Site.No = Fish.agg.PA$Site.No), sum))
# Total number of white sucker captured
sum(Fish.comm$White.Sucker)
# Proportion of sites white sucker captured
84/88 #95.5%
# Emerald Shiner
sum(Fish.comm$Emerald.Shiner)
77/88 #87.5
# Yellow Perch
sum(Fish.comm$Yellow.Perch)
79/88 #89.8
# Seasonal species catch
Seasonal<-aggregate(Fish.comm[c(10:74)], by = list(Year = Fish.comm$Year,
Season = Fish.comm$Season,
Section = Fish.comm$Section),
FUN = sum)
Seasonal
z<-aggregate(Fish.comm[c(10:74)], by = list(Season=Fish.comm$Section), FUN = sum)
rowSums(z[2:66])
z<-(aggregate(Fish.comm[c(10:74)], by = list(Season=Fish.comm$Year), FUN = sum))
rowSums(z[2:66])
z<-aggregate(Fish.comm[c(10:74)], by = list(Season=Fish.comm$Season), FUN = sum)
rowSums(z[2:66])
rowSums(Seasonal[4:68])
# Number of species per section
Section2<-aggregate(Fish.comm[c(10:74)], by = list(Season=Fish.comm$Section),
FUN = sum)
Section2[Section2>0] <-1
rowSums(Section2[2:66])
#########################################################################
#########################################################################
##################### Prepare data for RDA ##############################
#########################################################################
#########################################################################
colnames(Habitat)
Habitat1<-as.data.frame(cbind(Site.No = Habitat$Site.No,
Season = as.character(Habitat$Season),
Year = as.character(Habitat$Year),
Section = as.character(Habitat$Section),
Temp = Habitat$WaterTemp,
Cond = Habitat$Conductivity,
DO = Habitat$DO,
Turb = Habitat$Turbidity,
Depth = Habitat$AvDepth,
WV = Habitat$AvWaterVelocity,
Veg = Habitat$Submerged,
dMouth = Habitat$dMouth))
str(Habitat1)
# Convert back to numeric variables
Columns<-colnames(Habitat1[5:12])
Habitat1[Columns] <- sapply(Habitat1[Columns],as.numeric)
# Calculate pearson correlations
cor_mat <- cor(Habitat1[,c(5:12)], method='pearson')
###############################################################################
# Figure S2 ###################################################################
###############################################################################
par(xpd=T)
corrplot.mixed(cor_mat, tl.pos='lt', tl.cex=1, number.cex=1, addCoefasPercent=T,
mar = c(1, 1, 4, 1), tl.col="black")
################################################################################
# Table 1 ######################################################################
################################################################################
length(Habitat1$Section[Habitat1$Section=="Lower"])
length(Habitat1$Section[Habitat1$Section=="Upper"])
aggregate(.~Section, Habitat1[4:12], mean)
aggregate(.~Section, Habitat1[4:12], min)
aggregate(.~Section, Habitat1[4:12], max)
# Aggregate per site
head(Habitat1)
Hab.agg <- aggregate(Habitat1[c(1,5:12)], list(Site.No = Habitat1$Site.No,
Year = Habitat1$Year,
Season = Habitat1$Season), mean)
head(Hab.agg)
Hab.agg <- Hab.agg[-c(4)] # Remove aggregated site variable
# Order the data by Site No
Hab.agg$Site.No<-as.numeric(Hab.agg$Site.No)
Hab.agg <- Hab.agg[order(Hab.agg$Site.No),]
# Scaling continuous covariates to improve model fit and interpretation
Habitat.RDA <- as.data.frame(scale(Hab.agg[4:11], center = TRUE))
head(Habitat.RDA)
################################################################################
################################################################################
#################### Redundancy Analysis (RDA) #################################
################################################################################
################################################################################
#Transform fish data to reduce effects of abundant species
FishesTransformed <- decostand(Fish.RDA, method = "hellinger")
#reproducible results (unnecessary for performing analysis)
set.seed(2336)
# Stepwise model selection
head(Habitat.RDA)
mod0<-rda(FishesTransformed ~ 1, Habitat.RDA)
mod1<-rda(FishesTransformed ~ ., Habitat.RDA)
rda_select.r <-ordistep(mod0, scope = formula(mod1), direction = "both",
Pin = 0.05, Pout = 0.10, perm.max = 9999)
# Run final model
NR.rda <-rda(FishesTransformed ~ Depth + Temp + dMouth + Veg,
data = Habitat.RDA)
summary(NR.rda)
################################################################################
############################### Figure 2: Triplot ##############################
################################################################################
# Observation scores (site scores)
scores <- data.frame(Habitat.RDA,NR.rda$CCA$u)
# Species scores
vscores <- data.frame(NR.rda$CCA$v)
# Covariate scores
var.score <- data.frame(NR.rda$CCA$biplot[,1:2])
var.score.sc <- var.score * 0.8 # Scaling covariates for plotting purposes
var.score.sc$variables <- c("Depth", "Temp", "dMouth", "Veg")
# Only plotting the most abundant species for visualization purposes
rownames(vscores)
vscores2.sc <- vscores[c(6,9,18,21,25,30,35,46,54,56,63,65),]
Section <- c(rep("Upper", 52), rep("Lower", 36))
# Create plot of model
ggRDA <- ggplot(scores, aes(x = RDA1, y = RDA2)) +
geom_hline(yintercept=0,linetype="dashed",col="black")+
geom_vline(xintercept=0,linetype="dashed",col="black")+
geom_point(aes(shape=Section, color=Hab.agg$Season)) +
scale_shape_manual(name = "River Section", values = c(15:17))+
scale_color_manual(name = "Season",
values=c("black","lightgrey","darkgrey"),
labels = c("Fall","Spring","Summer"))+
geom_segment(data = vscores2.sc,
aes(x = 0, y = 0, xend = RDA1, yend = RDA2),
arrow=arrow(length=unit(0.2,"cm")),
color = "black",inherit.aes = FALSE,lwd=0.25) +
geom_text(data = vscores2.sc,
aes(x = RDA1, y = RDA2, label = rownames(vscores2.sc)),
col = 'black', inherit.aes = FALSE,
nudge_y = ifelse(vscores2.sc$RDA2 > 0, 0.02, -0.02),
nudge_x = ifelse(vscores2.sc$RDA1 > 0, 0.02, -0.02),size=3)+
geom_segment(data = var.score.sc,
aes(x = 0, y = 0, xend = RDA1, yend = RDA2),
arrow = arrow(length=unit(0.2,"cm")),
color = 'black', inherit.aes = FALSE, lwd=0.25) +
geom_text(data = var.score.sc,
aes(x = RDA1, y = RDA2, label = variables),
col = 'black', inherit.aes = FALSE,
nudge_y = ifelse(var.score.sc$RDA2 > 0, 0.02, -0.02),
nudge_x = ifelse(var.score.sc$RDA1 > 0, 0.02, -0.02),size=3) +
labs(x = "RDA Axis 1", y = "RDA Axis 2") +
theme_me + theme(legend.justification = c(1,0),
legend.position = c(1,0),
legend.background = element_blank(),
legend.box = 'horizontal')
ggRDA
#tiff("ggRDA.tiff", width = 6, height = 4, units = 'in', res = 1000)
#ggRDA
#dev.off()
################################################################################
################################################################################
############ Non-metric multidimensional scaling (NMDS) ########################
################################################################################
################################################################################
# Prepare data
colnames(Fish.RDA)
#habitat data
colnames(Habitat.RDA)
Habitat.NMDS<-Habitat.RDA[c(1,5,7,8)]
#comm data
NMDSdist<-decostand(Fish.RDA, method="hellinger")
#Final
NMDSord <- metaMDS(NMDSdist,k=2, try=20, trymax=1000) #final used
NMDSord
# Stressplot
stressplot(NMDSord)
# Shepards test/goodness of fit
goodness(NMDSord) # Produces a results of test statistics for goodness of fit for each point
# fit environmental variables
en = envfit(NMDSord, Habitat.NMDS, permutations = 9999, na.rm = TRUE,
choices=c(1,2))
en
# data
data.scores = as.data.frame(scores(NMDSord))
head(data.scores)
data.scores$season = Hab.agg$Season
en_coord_cont = as.data.frame(scores(en, "vectors"))
# for plotting species
Species<-as.data.frame(NMDSord$species)
Spec<-rownames(Species)
Count<-Fish.Counts$Count
Species<-cbind(Species, Spec,Count)
Species2<-Species[Species$Count>25,]
Species3<-Species[Species$Count>600,] #only plotting abundant species
################################################################################
############################ Figure S3 #########################################
################################################################################
ggNMDSENV <- ggplot(data.scores, aes(x = NMDS1, y = NMDS2)) +
geom_hline(yintercept=0,linetype="dashed",col="black")+
geom_vline(xintercept=0,linetype="dashed",col="black")+
geom_point(aes(color=Hab.agg$Season, shape=Section),
size=3, alpha=0.5) +
scale_shape_manual(name = "River Section", values = c(15:17))+
scale_colour_manual(values = c("orange", "violet","green"),
labels = c("Fall","Spring","Summer")) +
geom_segment(data=Species3, aes(x=0,y=0,xend=MDS1, yend=MDS2),
arrow=arrow(length=unit(0.2,"cm")),
size =0.5, colour = "black") +
geom_text(data=Species3, aes(x=MDS1, y=MDS2),
label=Species3$Spec, check_overlap = F,
nudge_y = ifelse(Species3$MDS2 > 0, 0.03, -0.03),
nudge_x = ifelse(Species3$MDS1 > 0, 0.03, -0.03))+
geom_segment(aes(x = 0, y = 0,
xend = NMDS1, yend = NMDS2),
arrow=arrow(length=unit(0.2,"cm")),
data = en_coord_cont, size =0.5, colour = "black") +
geom_text(data = en_coord_cont, aes(x = NMDS1, y = NMDS2),
colour = "black",
label = row.names(en_coord_cont),
nudge_y = ifelse(en_coord_cont$NMDS2 > 0, 0.03, -0.03),
nudge_x = ifelse(en_coord_cont$NMDS1 > 0, 0.03, -0.03)) +
labs(colour = "Season")+
theme_me+
theme(legend.position = c(.95, 0.75),
legend.justification = c("right", "top"),
legend.box.just = "right",
legend.margin = margin(6, 6, 6, 6))
ggNMDSENV
################################################################################
################################################################################
################ Functional Diversity Analysis #################################
################################################################################
################################################################################
# Provide correlation of trait data
head(Fish.traits)
Traitscorr<-Fish.traits[-c(1:8)]
colSums(Traitscorr[2:20])/65
str(Traitscorr)
################################################################################
########################## Figure S4 ###########################################
################################################################################
cor_mat <- cor(Traitscorr, method='spearman')
corrplot.mixed(cor_mat, tl.pos='lt', tl.cex=1, number.cex=1, addCoefasPercent=T,
mar = c(1, 1, 4, 1), tl.col="black")
# Reduce three trait categories into respective trait dimensions
# Diet analysis - what the species eat
# Removed correlated variables and variables without variation
Diet.data <- as.data.frame(cbind(Algae = Fish.traits$ALGPHYTO,
Macrophyte = Fish.traits$MACVASCU,
Fish = Fish.traits$FSHCRCRB,
Eggs = Fish.traits$EGGS))
# PCA of diet preference
F.transformed1 <- decostand(Diet.data, method = "hellinger")
PCA1 <- princomp(F.transformed1, cor=FALSE, scores=TRUE)
summary(PCA1)
# Quick plots
par(xpd=F)
plot(PCA1)
biplot(PCA1, xlim = c(-.4,.4), ylim = c(-.4,.3), cex = 0.8)
abline(v=0,h=0,lty="dashed")
# Substrate analysis
Habitat.data <- as.data.frame(cbind(CLAYSILT = Fish.traits$CLAYSILT,
SAND = Fish.traits$SAND,
GRAVEL = Fish.traits$GRAVEL,
COBBLE = Fish.traits$COBBLE,
BOULDER = Fish.traits$BOULDER,
BEDROCK = Fish.traits$BEDROCK,
VEGETAT = Fish.traits$VEGETAT,
LWD = Fish.traits$LWD,
DEBRDETR = Fish.traits$DEBRDETR))
# PCA on Substrate data
F.transformed2 <- decostand(Habitat.data, method = "hellinger")
PCA2 <- princomp(F.transformed2, cor = FALSE, scores = TRUE)
summary(PCA2)
# Quick plots
plot(PCA2)
biplot(PCA2, xlim = c(-.4,.4), ylim = c(-.4,.3), cex = 0.8)
abline(v=0,h=0,lty="dashed")
# Reproduction analysis
Reprod<-Fish.traits[c(17,18)]
F.transformed3 <- decostand(Reprod, method="hellinger")
PCA3<-princomp(F.transformed3, cor=FALSE, scores = TRUE)
summary(PCA3)
# Quick plots
plot(PCA3)
biplot(PCA3, xlim = c(-.4,.4), ylim = c(-.4,.3), cex = 0.8)
abline(v=0,h=0,lty="dashed")
# Fuction to assess significance of the principal components.
sign.pc <-function(x, R=9999, s=10, cor=T,...){
pc.out <- princomp(x, cor=cor,...) # run PCA
# the proportion of variance of each PC
pve=(pc.out$sdev^2/sum(pc.out$sdev^2))[1:s]
pve.perm <- matrix(NA,ncol=s,nrow=R)
for(i in 1:R){
x.perm <- apply(x,2,sample)# permutate each column
pc.perm.out <- princomp(x.perm,cor=cor,...)# run PCA
# the proportion of variance of each PC.perm
pve.perm[i,]=(pc.perm.out$sdev^2/sum(pc.perm.out$sdev^2))[1:s]
}
pval<-apply(t(pve.perm)>pve,1,sum)/R # calcalute the p-values
return(list(pve=pve,pval=pval))
}
# Apply the significance function
sign.pc(F.transformed1, cor = FALSE) #Axis 1 is significant
sign.pc(F.transformed2, cor = FALSE) #Axes 1 + 2 are significant
sign.pc(F.transformed3, cor = FALSE) #Axis 1 is significant
################################################################################
# Create full data frame for final ordination analysis
Fish.traits.reduced<-data.frame(Spp = Fish.traits$CODE,
Habitat1 = PCA2$scores[,1],
Habitat2 = PCA2$scores[,2],
Diet = PCA1$scores[,1],
Reproduction = PCA3$scores[,1],
Size = scale(Fish.traits$AV.TL.CM,
scale = TRUE, center = TRUE))
rownames(Fish.traits.reduced)<-Fish.traits$CODE
# Look at the variability across data axes
sd(Fish.traits.reduced$Habitat1)
sd(Fish.traits.reduced$Habitat2)
sd(Fish.traits.reduced$Diet)
sd(Fish.traits.reduced$Reproduction)
sd(Fish.traits.reduced$Size)
summary(Fish.traits.reduced$Habitat1)
summary(Fish.traits.reduced$Habitat2)
summary(Fish.traits.reduced$Diet)
summary(Fish.traits.reduced$Reproduction)
summary(Fish.traits.reduced$Size)
################################################################################
# Calculate Functional Diversity Measures
################################################################################
Fishfunction<-dbFD(x = Fish.traits.reduced[2:6], a = Fish.RDA,
w.abun = TRUE, stand.x = TRUE, calc.FRic = TRUE, m = "max",
stand.FRic = FALSE, scale.RaoQ = FALSE,
print.pco = TRUE, calc.FGR = FALSE, messages = TRUE)
# Extract diversity measures per fish community
SpeciesRichness <- Fishfunction$nbsp # Species Richness
FunctionalDivergence <- Fishfunction$FDiv # Functional divergences
FunctionalDispersion <- Fishfunction$FDis # Functional dispersion
Eigen <- Fishfunction$x.values # Eigenvalues
Axes <- Fishfunction$x.axes
Eigen[1]/sum(Eigen) # 29.3%
Eigen[2]/sum(Eigen) # 23.7%
Eigen[3]/sum(Eigen) # 20.0%
################################################################################
################# Figure 3 - Functional Trait PCOA #############################
################################################################################
Ord1<-ggplot(Axes, aes(x = A1, y = A2, label=rownames(Axes))) +
geom_hline(yintercept=0,linetype="dashed",col="black")+
geom_vline(xintercept=0,linetype="dashed",col="black")+
geom_point(pch=20) +
geom_text_repel(min.segment.length = Inf, seed = 42, box.padding = 0.2, size=2) +
xlab("Component 1 (29.3%)")+
ylab("Component 2 (23.7%)")+
theme_me
Ord1
Ord2<-ggplot(Axes, aes(x = A2, y = A3,label=rownames(Axes))) +
geom_hline(yintercept=0,linetype="dashed",col="black")+
geom_vline(xintercept=0,linetype="dashed",col="black")+
geom_point(pch=20) +
geom_text_repel(min.segment.length = Inf, seed = 42, box.padding = 0.2, size=2) +
xlab("Component 2 (23.7%)")+
ylab("Component 3 (20.0%)")+
theme_me
Ord2
#tiff("Figure3.tiff", width = 6.5, height = 4, units = 'in', res = 1000)
multiplot(Ord1,Ord2,cols=2)
#dev.off()
################################################################################
# Create data frame for post-analyses
Gradient.Frame<-data.frame(Site = Hab.agg$Site.No,
Year = Hab.agg$Year,
Season = Hab.agg$Season,
FDis = FunctionalDispersion,
FDiv = FunctionalDivergence,
SpRich = SpeciesRichness,
Section = Section)
head(Gradient.Frame)
str(Gradient.Frame)
{Gradient.Frame$Year <- as.character(Gradient.Frame$Year)
Gradient.Frame$Year <- as.factor(Gradient.Frame$Year)}
# Aggregate functional diversity measures
aggregate(Gradient.Frame[4], list(Gradient.Frame$Season, Gradient.Frame$Section, Gradient.Frame$Year), mean)
aggregate(Gradient.Frame[5], list(Gradient.Frame$Season, Gradient.Frame$Section, Gradient.Frame$Year), mean)
aggregate(Gradient.Frame[4], list(Gradient.Frame$Season, Gradient.Frame$Section, Gradient.Frame$Year), sd)
aggregate(Gradient.Frame[5], list(Gradient.Frame$Season, Gradient.Frame$Section, Gradient.Frame$Year), sd)
###############################################################################
# Permanova to look at differences in functional metrics
###############################################################################
# Functional dispersion
perm.fdis <- adonis(FunctionalDispersion ~ Season + Year + Section,
data = Gradient.Frame, permutations = 9999,
method = "euclidean")
perm.fdis
# Functional divergence
perm.fdiv <- adonis(FunctionalDivergence ~ Season + Year + Section,
data = Gradient.Frame, permutations = 9999,
method = "euclidean")
perm.fdiv
################################################################################
# Summary statistics
################################################################################
aggregate(Gradient.Frame$FDis, by = list(Gradient.Frame$Section), FUN = mean)
aggregate(Gradient.Frame$FDis, by = list(Gradient.Frame$Section), FUN = sd)
aggregate(Gradient.Frame$FDis, by = list(Gradient.Frame$Year), FUN = mean)
aggregate(Gradient.Frame$FDis, by = list(Gradient.Frame$Year), FUN = sd)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Section), FUN = mean)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Section), FUN = sd)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Season), FUN = mean)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Season), FUN = sd)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Year), FUN = mean)
aggregate(Gradient.Frame$FDiv, by = list(Gradient.Frame$Year), FUN = sd)
################################################################################
# Figure 4: Plotting Functional diversity difference
################################################################################
Fdis.year.box <- ggplot(data = Gradient.Frame,
aes(x = Year, y = FunctionalDispersion)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional dispersion") + theme_me +
theme(panel.background = element_rect(fill = "lightgrey"),
axis.text.x = element_text(angle = 35, hjust = 1))
Gradient.Frame$Season <- factor(Gradient.Frame$Season , levels=c("SPRING","SUMMER","FALL"))
Fdis.season.box <- ggplot(data = Gradient.Frame,
aes(x = Season, y = FunctionalDispersion)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional dispersion") + theme_me +
theme(axis.text.x = element_text(angle = 35, hjust = 1))
Fdis.section.box <- ggplot(data = Gradient.Frame,
aes(x = Section, y = FunctionalDispersion)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional dispersion") + theme_me+
theme(panel.background = element_rect(fill = "lightgrey"),
axis.text.x = element_text(angle = 35, hjust = 1))
Fdiv.year.box <- ggplot(data = Gradient.Frame,
aes(x = Year, y = FunctionalDivergence)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional divergence") + theme_me+
theme(panel.background = element_rect(fill = "lightgrey"),
axis.text.x = element_text(angle = 35, hjust = 1))
Fdiv.season.box <- ggplot(data = Gradient.Frame,
aes(x = Season, y = FunctionalDivergence)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional divergence") + theme_me+
theme(panel.background = element_rect(fill = "lightgrey"),
axis.text.x = element_text(angle = 35, hjust = 1))
Fdiv.section.box <- ggplot(data = Gradient.Frame,
aes(x = Section, y = FunctionalDivergence)) +
geom_boxplot() +
geom_jitter(shape = 16, position = position_jitter(0.2)) +
xlab("") + ylab("Functional divergence") + theme_me+
theme(panel.background = element_rect(fill = "lightgrey"),
axis.text.x = element_text(angle = 35, hjust = 1))
###############################################################################
################ Figure 4 Functional Diversity Metrics ########################
###############################################################################
#tiff("Figure4.tiff", width = 6.5, height = 5, units = 'in', res = 1000)
multiplot(Fdis.year.box,Fdiv.year.box,
Fdis.season.box,Fdiv.season.box,
Fdis.section.box,Fdiv.section.box,cols=3)
#dev.off()
###############################################################################
################# Figure 5 Functional dispersion x Functional divergence ######
###############################################################################
fdisfdivplot<-ggplot(Gradient.Frame, aes(x=FDiv, y=FDis, shape=Section,
color=Season, linetype=Section))+
geom_point() +
scale_shape_manual(name = "River Section", values = c(15:17))+
scale_color_manual(name = "Season",
values=c("black","darkgrey","lightgrey"),
labels = c("Fall","Spring","Summer"))+
geom_smooth(method='lm', se=F) +
labs(y="Functional Dispersion",x="Functional Divergence")+
scale_linetype_discrete(name="Season",
breaks=c("Fall","Spring","Summer"),
labels = c("Fall", "Spring", "Summer"))+
theme_me + theme(legend.justification = c("left", "top"),
legend.position = c(0,1),
legend.background = element_blank(),
legend.box = 'vertical',
legend.key = element_rect(fill = NA, colour = NA, size = 0.25))
fdisfdivplot
#tiff("Figure5.tiff", width = 5, height = 3.5, units = 'in', res = 1000)
#fdisfdivplot
#dev.off()
################################################################################
# Plot relationship between functional diversity and habitat variables
plot(Gradient.Frame$FDis~Hab.agg$Temp, pch=20, las=1)
plot(Gradient.Frame$FDis~Hab.agg$Cond, pch=20, las=1)
plot(Gradient.Frame$FDis~Hab.agg$DO, pch=20, las=1)
plot(Gradient.Frame$FDis~Hab.agg$Turb, pch=20, las=1)
plot(Gradient.Frame$FDis~Hab.agg$Depth, pch=20, las=1)
plot(Gradient.Frame$FDis~Hab.agg$WV, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$Temp, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$Cond, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$DO, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$Turb, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$Depth, pch=20, las=1)
plot(Gradient.Frame$FDiv~Hab.agg$WV, pch=20, las=1)
################################################################################
# Upper versus lower unique species
################################################################################
Fishagg<- cbind(Fishagg,
Section=Gradient.Frame$Section,
FDis=Gradient.Frame$FDis,
FDiv=Gradient.Frame$FDiv,
SpRich=Gradient.Frame$SpRich)
str(Fishagg)
Fishagg$Section<-as.factor(Fishagg$Section)
#Upper
Fish.Upper<-Fishagg[1:52,]
summary(Fish.Upper$Section)
colnames(Fish.Upper)
Fish.Upper<-Fish.Upper[c(1:4,6,18,19,24,26,27,33,49,62,65,71,72,73)]
head(Fish.Upper)
Abund.Upper<-rowSums(Fish.Upper[5:14])
#lower
Fish.Lower<-Fishagg[53:88,]
summary(Fish.Lower$Section)
colnames(Fish.Lower)
Fish.Lower<-Fish.Lower[c(1:4,7,8,20,21,38,41,55,57,71,72,73)]
head(Fish.Lower)
Abund.Lower<-rowSums(Fish.Lower[5:12])
################################################################################
###########Figure 6 Functional dispersion and unique sp abundance ##############
################################################################################
Dis<-ggplot()+
geom_smooth(aes(x=Fish.Upper$FDis, y=Abund.Upper),method="lm", col="black", lwd=0.5)+
geom_point(aes(x=Fish.Upper$FDis, y=Abund.Upper))+
geom_smooth(aes(x=Fish.Lower$FDis, y=Abund.Lower), method="lm", col="grey", lwd=0.5)+
geom_point(aes(x=Fish.Lower$FDis, y=Abund.Lower), col="grey")+ylim(-10,50)+theme_me+
scale_x_continuous(expand=c(0,0), limits=c(0,2.5)) +
scale_y_continuous(expand=c(0,0), limits=c(-50,50)) +
coord_cartesian(xlim=c(0.8,2.5), ylim=c(0,50))+
ylab("Abundance")+xlab("Functional Dispersion")
Dis
Div<-ggplot()+
geom_smooth(aes(x=Fish.Upper$FDiv, y=Abund.Upper), method="lm", col="black", lwd=0.5)+
geom_point(aes(x=Fish.Upper$FDiv, y=Abund.Upper))+
geom_smooth(aes(x=Fish.Lower$FDiv, y=Abund.Lower), method="lm", col="grey", lwd=0.5)+
geom_point(aes(x=Fish.Lower$FDiv, y=Abund.Lower), col="grey")+ylim(-10,50)+
theme_me+
scale_x_continuous(expand=c(0,0), limits=c(0,1.2)) +
scale_y_continuous(expand=c(0,0), limits=c(-50,50)) +
coord_cartesian(xlim=c(0.3,1), ylim=c(0,50))+
ylab("Abundance")+xlab("Functional Divergence")
#tiff("Figure6.tiff", width = 5, height = 3, units = 'in', res = 1000)
multiplot(Dis, Div, cols=2)
#dev.off()
################################################################################
# Calculate distance between Rainbow Smelt and other species
################################################################################
D.RS<-matrix(0)
for(x in 1:(length(Axes$A1))){
D.RS[x]<-sqrt((Axes$A1[x] - Axes$A1[46])^2 +
(Axes$A2[x] - Axes$A2[46])^2 +
(Axes$A3[x] - Axes$A3[46])^2)
}
D.RS <- data.frame(cbind(D.RS, as.character(Fish.traits$COMMONNAME)))
D.RS$D.RS <- as.character(D.RS$D.RS)
D.RS$D.RS <- as.numeric(D.RS$D.RS)
#calculate distance between Rainbow Smelt and other species in RDA
D.RS<-matrix(0)
for(x in 1:(length(vscores$RDA1))){
D.RS[x]<-sqrt((vscores$RDA1[x] - vscores$RDA1[46])^2 +
(vscores$RDA2[x] - vscores$RDA2[46])^2)
}
D.RS <- data.frame(cbind(D.RS, as.character(Fish.traits$COMMONNAME)))
D.RS
D.RS$D.RS <- as.character(D.RS$D.RS)
D.RS$D.RS <- as.numeric(D.RS$D.RS)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/contract.scc.R
\name{contract.scc}
\alias{contract.scc}
\title{contract.scc}
\usage{
contract.scc(g)
}
\arguments{
\item{g}{Must be an igraph object all vertices must have an attributes called "KE_KED" (Key Event Designator), with values of "MIE", "KE", or "AO" [igraph object]}
}
\value{
New condensed igraph object where each strongly connected component has been contracted to a single node [igraph object]
}
\description{
Condense all strongly connected components in a graph
}
| /man/contract.scc.Rd | no_license | npollesch/AOPNet | R | false | true | 561 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/contract.scc.R
\name{contract.scc}
\alias{contract.scc}
\title{contract.scc}
\usage{
contract.scc(g)
}
\arguments{
\item{g}{Must be an igraph object all vertices must have an attributes called "KE_KED" (Key Event Designator), with values of "MIE", "KE", or "AO" [igraph object]}
}
\value{
New condensed igraph object where each strongly connected component has been contracted to a single node [igraph object]
}
\description{
Condense all strongly connected components in a graph
}
|
########## Neural network ############
library(nnet)
library(caret)
ptm <- proc.time()
x.modelNNet <- train(BaseFormula, data=x.train, method='nnet', trControl=trainControl(method='cv'))
x.evaluate$predictionNNet <- predict(x.modelNNet, newdata = x.evaluate, type="raw")
x.evaluate$correctNNet <- x.evaluate$predictionNNet == x.evaluate$SaleString
print(paste("% of predicted classifications correct", mean(x.evaluate$correctNNet)))
x.evaluate$probabilitiesNNet <- predict(x.modelNNet, newdata = x.evaluate, type='prob')[,1]
NNetOutput <- makeLiftPlot(x.evaluate$probabilitiesNNet,x.evaluate,"Neural Network")
TimeAux <- proc.time() - ptm
NNetOutput$TimeElapsed <- TimeAux[3]
NNetOutput$PercCorrect <- mean(x.evaluate$correctNNet)*100
rm(TimeAux)
#update machine laerning properties
newmachinelearningproperties <- getMachineLearningProperties("Neural Network",NNetOutput)
machinelearning.properties <- rbind(machinelearning.properties,newmachinelearningproperties)
#Save again the training and evaluation set so the output of your model can be loaded later
write.csv(machinelearning.properties, file = "datasets/ml_performances")
| /Semester 3/Data Science and Marketing Analysis/Assignment2/project/project/final_code/06_neuralnetworks.R | no_license | fsimanjuntak/kuliah | R | false | false | 1,139 | r | ########## Neural network ############
library(nnet)
library(caret)
ptm <- proc.time()
x.modelNNet <- train(BaseFormula, data=x.train, method='nnet', trControl=trainControl(method='cv'))
x.evaluate$predictionNNet <- predict(x.modelNNet, newdata = x.evaluate, type="raw")
x.evaluate$correctNNet <- x.evaluate$predictionNNet == x.evaluate$SaleString
print(paste("% of predicted classifications correct", mean(x.evaluate$correctNNet)))
x.evaluate$probabilitiesNNet <- predict(x.modelNNet, newdata = x.evaluate, type='prob')[,1]
NNetOutput <- makeLiftPlot(x.evaluate$probabilitiesNNet,x.evaluate,"Neural Network")
TimeAux <- proc.time() - ptm
NNetOutput$TimeElapsed <- TimeAux[3]
NNetOutput$PercCorrect <- mean(x.evaluate$correctNNet)*100
rm(TimeAux)
#update machine laerning properties
newmachinelearningproperties <- getMachineLearningProperties("Neural Network",NNetOutput)
machinelearning.properties <- rbind(machinelearning.properties,newmachinelearningproperties)
#Save again the training and evaluation set so the output of your model can be loaded later
write.csv(machinelearning.properties, file = "datasets/ml_performances")
|
#------ Load the main dataset
load("Master.RData")
#------ Load R functions
source("Correlation_Alt.R")
source("MetropolisHastingsAlgorithm.R")
#------ Set Treatment (TRT), Outcome (OUT), Mediators (M) and Covariates (X)
Data <- Master
OUT <- Data$PM.2.5
TRT <- Data$SO2.SC
M <- cbind(Data$SO2_Annual, Data$NOx_Annual, Data$CO2_Annual)
XX <- cbind(Data$S_n_CR, Data$NumNOxControls, Data$Heat_Input/100000, Data$Barometric_Pressure, Data$Temperature, Data$PctCapacity, Data$sulfur_Content, Data$Phase2_Indicator, Data$Operating_Time/1000)
dim.cov <- dim(XX)[2] #<--------- Num. of Covariates
dimx <- dim.cov+1
#------ Variables by treatments
x0 <- XX[which(TRT==0),]
x1 <- XX[which(TRT==1),]
y0 <- OUT[which(TRT==0)]
y1 <- OUT[which(TRT==1)]
m0 <- log(M[which(TRT==0),])
m1 <- log(M[which(TRT==1),])
n0 <- dim(x0)[1]
n1 <- dim(x1)[1]
#------- load required libraries
library(mnormt)
library(gtools)
library(numDeriv)
library(matrixcalc)
library(corpcor)
library(rootSolve)
P <- 8 # number of marginal distributions
K <- 9 # numner of clusters
#-------- Initial Settings
MCMC <- 100000 # Num. of Iterations
### Set matrices to place posteriors ###
para.y1 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # Y(1)
# Set initial values
para.y1[1,] <- para.y1[2,] <- c(NA,rep(0.5,(K-1)),rep(-6,K),coefficients(lm(y1~x1))[-1],rep(var(y1)/4,K),2,2,2,mean(y1),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.y0 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # Y(0)
para.y0[1,] <- para.y0[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(y0~x0))[1],K),coefficients(lm(y0~x0))[-1],rep(var(y0)/4,K),2,2,2,mean(y0),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m11 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # Y(0)
para.m11[1,] <- para.m11[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m1[,1]~x1))[1],K),coefficients(lm(m1[,1]~x1))[-1],rep(var(m1[,1])/4,K),2,2,2,mean(m1[,1]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m21 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # m2(1)
para.m21[1,] <- para.m21[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m1[,2]~x1))[1],K),coefficients(lm(m1[,2]~x1))[-1],rep(var(m1[,2])/4,K),2,2,2,mean(m1[,2]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m31 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # m3(1)
para.m31[1,] <- para.m31[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m1[,3]~x1))[1],K),coefficients(lm(m1[,3]~x1))[-1],rep(var(m1[,3])/4,K),2,2,2,mean(m1[,3]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m10 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # m1(0)
para.m10[1,] <- para.m10[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m0[,1]~x0))[1],K),coefficients(lm(m0[,1]~x0))[-1],rep(var(m0[,1])/4,K),2,2,2,mean(m0[,1]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m20 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # m2(0)
para.m20[1,] <- para.m20[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m0[,2]~x0))[1],K),coefficients(lm(m0[,2]~x0))[-1],rep(var(m0[,2])/4,K),2,2,2,mean(m0[,2]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m30 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # m3(0)
para.m30[1,] <- para.m30[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m0[,3]~x0))[1],K),coefficients(lm(m0[,3]~x0))[-1],rep(var(m0[,3])/4,K),2,2,2,mean(m0[,3]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.C <- matrix(nrow = MCMC, ncol = (28*2+3)) # Correlations
para.C[1,] <- para.C[2,] <- c(rep(NA,28),c(0.130123426029935, -0.0854405048744152, -0.0837929602888095,
0, 0, 0, 0, 0.528898227751186, 0.517242870241654, 0, 0, 0, 0,
0.804514579489972, 0, 0, 0, 0, 0, 0, 0, 0, 0.125181447538096,
-0.0769838292735945, 0.00400666063036421, 0.689859929372401,
0.701074907893295, 0.835553284184042),c(0.001,0.001,0.001))
# Indices of parameters
ind1 <- (K+1):(2*K) # intercept
ind2 <- (2*K+1):(2*K+dim.cov) # regression coefficient except the intercept
ind3 <- (2*K+dim.cov+1):(3*K+dim.cov) # variance
ind4 <- 3*K+dim.cov+1 # alpha
ind5 <- ind4+1 # alpha_beta0
ind6 <- ind5+1 # alpha_sigma
ind7 <- ind6+1 # mu_beta0
ind8 <- ind7+1 # sigma_beta0
# Initial values for Gaussian variables for the Copula model
h <- rbind(cbind(y1,m1[,1:3],0,0,0,0),
cbind(0,0,0,0,y0,m0[,1:3]))
# Initial setting for R
R <- diag(1,P)
# Starting values for variances in adaptive sampler (1)
cov.y1 <- log(sqrt(diag(vcov(lm(y1~x1))[1,1],K)/4))
cov.m11 <- log(sqrt(diag(vcov(lm(m1[,1]~x1))[1,1],K)/4))
cov.m21 <- log(sqrt(diag(vcov(lm(m1[,2]~x1))[1,1],K)/4))
cov.m31 <- log(sqrt(diag(vcov(lm(m1[,3]~x1))[1,1],K)/4))
cov.y0 <- log(sqrt(diag(vcov(lm(y0~x0))[1,1],K)/4))
cov.m10 <- log(sqrt(diag(vcov(lm(m0[,1]~x0))[1,1],K)/4))
cov.m20 <- log(sqrt(diag(vcov(lm(m0[,2]~x0))[1,1],K)/4))
cov.m30 <- log(sqrt(diag(vcov(lm(m0[,3]~x0))[1,1],K)/4))
# Starting values for variances in adaptive sampler (2)
cov2.y1 <- log(sqrt(diag(diag(vcov(lm(y1~x1))[-1,-1]),K)/8))
cov2.m11 <- log(sqrt(diag(diag(vcov(lm(m1[,1]~x1))[-1,-1]),K)/8))
cov2.m21 <- log(sqrt(diag(diag(vcov(lm(m1[,2]~x1))[-1,-1]),K)/8))
cov2.m31 <- log(sqrt(diag(diag(vcov(lm(m1[,3]~x1))[-1,-1]),K)/8))
cov2.y0 <- log(sqrt(diag(diag(vcov(lm(y0~x0))[-1,-1]),K)/8))
cov2.m10 <- log(sqrt(diag(diag(vcov(lm(m0[,1]~x0))[-1,-1]),K)/8))
cov2.m20 <- log(sqrt(diag(diag(vcov(lm(m0[,2]~x0))[-1,-1]),K)/8))
cov2.m30 <- log(sqrt(diag(diag(vcov(lm(m0[,3]~x0))[-1,-1]),K)/8))
# Initial values for complete data: Y(1),Y(0),M(1,1,1),M(0,0,0)
y1 <- c(y1, rnorm(n0, mean(y1), sd(y1)))
y0 <- c(rnorm(n1, mean(y0), sd(y0)), y0)
m1 <- rbind(m1, rmnorm(n0, apply(m1, 2, mean), var(m1)))
m0 <- rbind(rmnorm(n1, apply(m0, 2, mean), var(m0)), m0)
#-------- Run MCMC
pb <- txtProgressBar(min = 0, max = MCMC, style = 3)
for (t in 3:MCMC){
# Break up the MCMC run into several batches (50 iterations each)
# to monitor and manipulate the acceptance rates for the adaptive samplers
SEQ <- seq(54, MCMC, by=50)
#### Y(1) ####
if(t %in% SEQ){
for(c in 1:K){
if(mean(para.y1[(t-51):(t-1),(dim(para.y1)[2]-3*K+c)]) < 0.44 ){
cov.y1[c,c] <- cov.y1[c,c]-min(0.01, 1/sqrt(t)) # reduce the variance by min(0.01, 1/sqrt(t))
}else{
cov.y1[c,c] <- cov.y1[c,c]+min(0.01, 1/sqrt(t)) # increase the variance by min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if(mean(para.y1[(t-51):(t-1),(dim(para.y1)[2]-1*K+c)]) < 0.44 ){
cov2.y1[c,c] <- cov2.y1[c,c]-min(0.01, 1/sqrt(t)) # reduce the variance by min(0.01, 1/sqrt(t))
}else{
cov2.y1[c,c] <- cov2.y1[c,c]+min(0.01, 1/sqrt(t)) # increase the variance by min(0.01, 1/sqrt(t))
}
}
}
para.y1[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=y1, R=R, w_pre=para.y1[t-1,2:K],
beta0_pre=para.y1[t-1,ind1], beta_pre=para.y1[t-1,ind2],sigma_pre=para.y1[t-1,ind3],
alpha_pre=para.y1[t-1,ind4], alpha_beta0_pre=para.y1[t-1,ind5], alpha_sigma_pre=para.y1[t-1,ind6],
mu_beta0_pre=para.y1[t-1,ind7], sigma_beta0_pre=para.y1[t-1,ind8],K=K, eps=0.1,
del1=15, del2=10, del3=30, index=1, cov1=cov.y1,cov2=cov2.y1, zz=1)
# Update a Gaussian variable for the Copula model
prop1 <- para.y1[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.y1 <- pprop1
h[,1] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(y1),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.y1[t,ind1]+sum(para.y1[t,ind2]*z[2:(dim(x0)[2]+1)]), sqrt(para.y1[t,ind3])))))))
#### Y(0) ####
if(t %in% SEQ){
for(c in 1:K){
if(mean(para.y0[(t-51):(t-1),(dim(para.y0)[2]-3*K+c)]) < 0.44 ){
cov.y0[c,c] <- cov.y0[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.y0[c,c] <- cov.y0[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if(mean(para.y0[(t-51):(t-1),(dim(para.y0)[2]-1*K+c)]) < 0.44 ){
cov2.y0[c,c] <- cov2.y0[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.y0[c,c] <- cov2.y0[c,c]+min(0.01, 1/sqrt(t)) }
}
}
para.y0[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=y0, R=R, w_pre=para.y0[t-1,2:K],
beta0_pre=para.y0[t-1,ind1], beta_pre=para.y0[t-1,ind2], sigma_pre=para.y0[t-1,ind3],
alpha_pre=para.y0[t-1,ind4], alpha_beta0_pre=para.y0[t-1,ind5], alpha_sigma_pre=para.y0[t-1,ind6],
mu_beta0_pre=para.y0[t-1,ind7], sigma_beta0_pre=para.y0[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=30, index=5, cov1=cov.y0, cov2=cov2.y0, zz=0)
prop1 <- para.y0[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.y0 <- pprop1
h[,5] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(y0),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.y0[t,ind1]+sum(para.y0[t,ind2]*z[2:(dim(x0)[2]+1)]),sqrt(para.y0[t,ind3])))))))
#### M1(0) ####
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m10[(t-51):(t-1),(dim(para.m10)[2]-3*K+c)]) < 0.44 ){
cov.m10[c,c] <- cov.m10[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m10[c,c] <- cov.m10[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m10[(t-51):(t-1),(dim(para.m10)[2]-1*K+c)]) < 0.44 ){
cov2.m10[c,c] <- cov2.m10[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m10[c,c] <- cov2.m10[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m10[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m0[,1], R=R, w_pre=para.m10[t-1,2:K],
beta0_pre=para.m10[t-1,ind1], beta_pre=para.m10[t-1,ind2], sigma_pre=para.m10[t-1,ind3],
alpha_pre=para.m10[t-1,ind4], alpha_beta0_pre=para.m10[t-1,ind5], alpha_sigma_pre=para.m10[t-1,ind6],
mu_beta0_pre=para.m10[t-1,ind7], sigma_beta0_pre=para.m10[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=6, cov1=cov.m10, cov2=cov2.m10, zz=0)
prop1 <- para.m10[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m10 <- pprop1
h[ ,6]<- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m0[,1]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m10[t,ind1]+sum(para.m10[t,ind2]*z[2:(dim(x0)[2]+1)]),sqrt(para.m10[t,ind3])))))))
#### M2(0) ####
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m20[(t-51):(t-1),(dim(para.m20)[2]-3*K+c)]) < 0.44 ){
cov.m20[c,c] <- cov.m20[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m20[c,c] <- cov.m20[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m20[(t-51):(t-1),(dim(para.m20)[2]-1*K+c)]) < 0.44 ){
cov2.m20[c,c] <- cov2.m20[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m20[c,c] <- cov2.m20[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m20[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m0[,2], R=R, w_pre=para.m20[t-1,2:K],
beta0_pre=para.m20[t-1,ind1], beta_pre=para.m20[t-1,ind2], sigma_pre=para.m20[t-1,ind3],
alpha_pre=para.m20[t-1,ind4], alpha_beta0_pre=para.m20[t-1,ind5], alpha_sigma_pre=para.m20[t-1,ind6],
mu_beta0_pre=para.m20[t-1,ind7], sigma_beta0_pre=para.m20[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=7, cov1=cov.m20, cov2=cov2.m20, zz=0)
prop1 <- para.m20[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m20 <- pprop1
h[ ,7] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m0[,2]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m20[t,ind1]+sum(para.m20[t,ind2]*z[2:(dim(x0)[2]+1)]),sqrt(para.m20[t,ind3])))))))
#### M3(0) ####
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m30[(t-51):(t-1),(dim(para.m30)[2]-3*K+c)]) < 0.44 ){
cov.m30[c,c] <- cov.m30[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m30[c,c] <- cov.m30[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m30[(t-51):(t-1),(dim(para.m30)[2]-1*K+c)]) < 0.44 ){
cov2.m30[c,c] <- cov2.m30[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m30[c,c] <- cov2.m30[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m30[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m0[,3], R=R, w_pre=para.m30[t-1,2:K],
beta0_pre=para.m30[t-1,ind1], beta_pre=para.m30[t-1,ind2], sigma_pre=para.m30[t-1,ind3],
alpha_pre=para.m30[t-1,ind4], alpha_beta0_pre=para.m30[t-1,ind5], alpha_sigma_pre=para.m30[t-1,ind6],
mu_beta0_pre=para.m30[t-1,ind7], sigma_beta0_pre=para.m30[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=8, cov1=cov.m30, cov2=cov2.m30, zz=0)
prop1 <- para.m30[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m30 <- pprop1
h[ ,8] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m0[,3]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m30[t,ind1]+sum(para.m30[t,ind2]*z[2:(dim(x0)[2]+1)]),sqrt(para.m30[t,ind3])))))))
#### M1(1) ####
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m11[(t-51):(t-1),(dim(para.m11)[2]-3*K+c)]) < 0.44 ){
cov.m11[c,c] <- cov.m11[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m11[c,c] <- cov.m11[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m11[(t-51):(t-1),(dim(para.m11)[2]-1*K+c)]) < 0.44 ){
cov2.m11[c,c] <- cov2.m11[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m11[c,c] <- cov2.m11[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m11[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m1[,1], R=R, w_pre=para.m11[t-1,2:K],
beta0_pre=para.m11[t-1,ind1], beta_pre=para.m11[t-1,ind2], sigma_pre=para.m11[t-1,ind3],
alpha_pre=para.m11[t-1,ind4], alpha_beta0_pre=para.m11[t-1,ind5], alpha_sigma_pre=para.m11[t-1,ind6],
mu_beta0_pre=para.m11[t-1,ind7], sigma_beta0_pre=para.m11[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=2, cov1=cov.m11, cov2=cov2.m11, zz=1)
prop1 <- para.m11[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m11 <- pprop1
h[ ,2] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m1[,1]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m11[t,ind1]+sum(para.m11[t,ind2]*z[2:(dim(x1)[2]+1)]),sqrt(para.m11[t,ind3])))))))
#### M2(1) ####
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m21[(t-51):(t-1),(dim(para.m21)[2]-3*K+c)]) < 0.44 ){
cov.m21[c,c] <- cov.m21[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m21[c,c] <- cov.m21[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m21[(t-51):(t-1),(dim(para.m21)[2]-1*K+c)]) < 0.44 ){
cov2.m21[c,c] <- cov2.m21[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m21[c,c] <- cov2.m21[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m21[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m1[,2], R=R, w_pre=para.m21[t-1,2:K],
beta0_pre=para.m21[t-1,ind1], beta_pre=para.m21[t-1,ind2], sigma_pre=para.m21[t-1,ind3],
alpha_pre=para.m21[t-1,ind4], alpha_beta0_pre=para.m21[t-1,ind5], alpha_sigma_pre=para.m21[t-1,ind6],
mu_beta0_pre=para.m21[t-1,ind7], sigma_beta0_pre=para.m21[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=3, cov1=cov.m21, cov2=cov2.m21,zz=1)
prop1 <- para.m21[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m21 <- pprop1
h[ ,3] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m1[,2]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m21[t,ind1]+sum(para.m21[t,ind2]*z[2:(dim(x1)[2]+1)]),sqrt(para.m21[t,ind3])))))))
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m31[(t-51):(t-1),(dim(para.m31)[2]-3*K+c)]) < 0.44 ){
cov.m31[c,c] <- cov.m31[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m31[c,c] <- cov.m31[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m31[(t-51):(t-1),(dim(para.m31)[2]-1*K+c)]) < 0.44 ){
cov2.m31[c,c] <- cov2.m31[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m31[c,c] <- cov2.m31[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m31[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m1[,3], R=R, w_pre=para.m31[t-1,2:K],
beta0_pre=para.m31[t-1,ind1], beta_pre=para.m31[t-1,ind2], sigma_pre=para.m31[t-1,ind3],
alpha_pre=para.m31[t-1,ind4], alpha_beta0_pre=para.m31[t-1,ind5], alpha_sigma_pre=para.m31[t-1,ind6],
mu_beta0_pre=para.m31[t-1,ind7], sigma_beta0_pre=para.m31[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=4, cov1=cov.m31, cov2=cov2.m31, zz=1)
prop1 <- para.m31[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m31 <- pprop1
h[,4] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m1[,3]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m31[t,ind1]+sum(para.m31[t,ind2]*z[2:(dim(x1)[2]+1)]),sqrt(para.m31[t,ind3])))))))
# Correlation parameters
para.C[t,1:59] <- metropolisC(h=h, rho=para.C[t-1,29:56], prho=para.C[t-1,57:59])
prop1 <- para.C[t,29:56]
# Update the correlation matrix R
R <- matrix(c(1,prop1[1:7],prop1[1],1,prop1[8:13],prop1[2],prop1[8],1,prop1[14:18],prop1[3],
prop1[9],prop1[14],1,prop1[19:22],prop1[4],prop1[10],prop1[15],prop1[19],1,
prop1[1:3],prop1[5],prop1[11],prop1[16],prop1[20],prop1[1],1,prop1[26:27],
prop1[6],prop1[12],prop1[17],prop1[21],prop1[2],prop1[26],1,prop1[28],prop1[7],
prop1[13],prop1[18],prop1[22],prop1[3],prop1[27],prop1[28],1),8,8,byrow=TRUE)
# Impute missing part of the Copula model based on R
h[(1+n1):(n1+n0),1:4] <- t(apply(h[(1+n1):(n1+n0),5:8], 1, function(x)
rmnorm(1, R[1:4,5:8]%*%solve(R[5:8,5:8])%*%c(x[1],x[2],x[3],x[4]), R[1:4,1:4]-R[1:4,5:8]%*%solve(R[5:8,5:8])%*%t(R[1:4,5:8]))))
h[1:n1,5:8] <- t(apply(h[1:n1,1:4], 1, function(x)
rmnorm(1, R[5:8,1:4]%*%solve(R[1:4,1:4])%*%c(x[1],x[2],x[3],x[4]), R[5:8,5:8]-R[5:8,1:4]%*%solve(R[1:4,1:4])%*%t(R[5:8,1:4]))))
# Update missing part of Y(1), Y(0), M(1,1,1) and M(0,0,0) from the above
clus.y1 <- apply(rmultinom(n0, 1, pprop.y1), 2, function(x) which(x==1)) # cluster membership
y1[(n1+1):(n1+n0)] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1+n1):(n1+n0),1]))), mean = para.y1[t,ind1][clus.y1]+x0%*%para.y1[t,ind2], sd=sqrt(para.y1[t,ind3][clus.y1]) )
clus.y0 <- apply(rmultinom(n1, 1, pprop.y0), 2, function(x) which(x==1)) # cluster membership
y0[(1):(n1)] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1):(n1),5]))), mean = para.y0[t,ind1][clus.y0]+x1%*%para.y0[t,ind2], sd=sqrt(para.y0[t,ind3][clus.y0]) )
clus.m11 <- apply(rmultinom(n0, 1, pprop.m11), 2, function(x) which(x==1)) # cluster membership
m1[(n1+1):(n1+n0),1] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1+n1):(n1+n0),2]))), mean = para.m11[t,ind1][clus.m11]+x0%*%para.m11[t,ind2], sd=sqrt(para.m11[t,ind3][clus.m11]) )
clus.m21 <- apply(rmultinom(n0, 1, pprop.m21), 2, function(x) which(x==1)) # cluster membership
m1[(n1+1):(n1+n0),2] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1+n1):(n1+n0),3]))), mean = para.m21[t,ind1][clus.m21]+x0%*%para.m21[t,ind2], sd=sqrt(para.m21[t,ind3][clus.m21]) )
clus.m31 <- apply(rmultinom(n0, 1, pprop.m31), 2, function(x) which(x==1)) # cluster membership
m1[(n1+1):(n1+n0),3] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1+n1):(n1+n0),4]))), mean = para.m31[t,ind1][clus.m31]+x0%*%para.m31[t,ind2], sd=sqrt(para.m31[t,ind3][clus.m31]) )
clus.m10 <- apply(rmultinom(n1, 1, pprop.m10), 2, function(x) which(x==1)) # cluster membership
m0[(1):(n1),1] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1):(n1),6]))), mean = para.m10[t,ind1][clus.m10]+x1%*%para.m10[t,ind2], sd=sqrt(para.m10[t,ind3][clus.m10]) )
clus.m20 <- apply(rmultinom(n1, 1, pprop.m20), 2, function(x) which(x==1)) # cluster membership
m0[(1):(n1),2] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1):(n1),7]))), mean = para.m20[t,ind1][clus.m20]+x1%*%para.m20[t,ind2], sd=sqrt(para.m20[t,ind3][clus.m20]) )
clus.m30 <- apply(rmultinom(n1, 1, pprop.m30), 2, function(x) which(x==1)) # cluster membership
m0[(1):(n1),3] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1):(n1),8]))), mean = para.m30[t,ind1][clus.m30]+x1%*%para.m30[t,ind2], sd=sqrt(para.m30[t,ind3][clus.m30]) )
Sys.sleep(0.001)
setTxtProgressBar(pb, t)
}
save.image("MCMCsamples.RData")
| /MCMC.R | no_license | guhjy/MultipleMediators | R | false | false | 21,710 | r | #------ Load the main dataset
load("Master.RData")
#------ Load R functions
source("Correlation_Alt.R")
source("MetropolisHastingsAlgorithm.R")
#------ Set Treatment (TRT), Outcome (OUT), Mediators (M) and Covariates (X)
Data <- Master
OUT <- Data$PM.2.5
TRT <- Data$SO2.SC
M <- cbind(Data$SO2_Annual, Data$NOx_Annual, Data$CO2_Annual)
XX <- cbind(Data$S_n_CR, Data$NumNOxControls, Data$Heat_Input/100000, Data$Barometric_Pressure, Data$Temperature, Data$PctCapacity, Data$sulfur_Content, Data$Phase2_Indicator, Data$Operating_Time/1000)
dim.cov <- dim(XX)[2] #<--------- Num. of Covariates
dimx <- dim.cov+1
#------ Variables by treatments
x0 <- XX[which(TRT==0),]
x1 <- XX[which(TRT==1),]
y0 <- OUT[which(TRT==0)]
y1 <- OUT[which(TRT==1)]
m0 <- log(M[which(TRT==0),])
m1 <- log(M[which(TRT==1),])
n0 <- dim(x0)[1]
n1 <- dim(x1)[1]
#------- load required libraries
library(mnormt)
library(gtools)
library(numDeriv)
library(matrixcalc)
library(corpcor)
library(rootSolve)
P <- 8 # number of marginal distributions
K <- 9 # numner of clusters
#-------- Initial Settings
MCMC <- 100000 # Num. of Iterations
### Set matrices to place posteriors ###
para.y1 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # Y(1)
# Set initial values
para.y1[1,] <- para.y1[2,] <- c(NA,rep(0.5,(K-1)),rep(-6,K),coefficients(lm(y1~x1))[-1],rep(var(y1)/4,K),2,2,2,mean(y1),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.y0 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # Y(0)
para.y0[1,] <- para.y0[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(y0~x0))[1],K),coefficients(lm(y0~x0))[-1],rep(var(y0)/4,K),2,2,2,mean(y0),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m11 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # Y(0)
para.m11[1,] <- para.m11[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m1[,1]~x1))[1],K),coefficients(lm(m1[,1]~x1))[-1],rep(var(m1[,1])/4,K),2,2,2,mean(m1[,1]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m21 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # m2(1)
para.m21[1,] <- para.m21[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m1[,2]~x1))[1],K),coefficients(lm(m1[,2]~x1))[-1],rep(var(m1[,2])/4,K),2,2,2,mean(m1[,2]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m31 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # m3(1)
para.m31[1,] <- para.m31[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m1[,3]~x1))[1],K),coefficients(lm(m1[,3]~x1))[-1],rep(var(m1[,3])/4,K),2,2,2,mean(m1[,3]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m10 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # m1(0)
para.m10[1,] <- para.m10[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m0[,1]~x0))[1],K),coefficients(lm(m0[,1]~x0))[-1],rep(var(m0[,1])/4,K),2,2,2,mean(m0[,1]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m20 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # m2(0)
para.m20[1,] <- para.m20[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m0[,2]~x0))[1],K),coefficients(lm(m0[,2]~x0))[-1],rep(var(m0[,2])/4,K),2,2,2,mean(m0[,2]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.m30 <- matrix(nrow = MCMC, ncol = 6+6*K+2*dim.cov) # m3(0)
para.m30[1,] <- para.m30[2,] <- c(NA,rep(0.5,(K-1)),rep(coefficients(lm(m0[,3]~x0))[1],K),coefficients(lm(m0[,3]~x0))[-1],rep(var(m0[,3])/4,K),2,2,2,mean(m0[,3]),1,NA,rep(NA,dim.cov),rep(NA,K),rep(NA,K),rep(NA,K))
para.C <- matrix(nrow = MCMC, ncol = (28*2+3)) # Correlations
para.C[1,] <- para.C[2,] <- c(rep(NA,28),c(0.130123426029935, -0.0854405048744152, -0.0837929602888095,
0, 0, 0, 0, 0.528898227751186, 0.517242870241654, 0, 0, 0, 0,
0.804514579489972, 0, 0, 0, 0, 0, 0, 0, 0, 0.125181447538096,
-0.0769838292735945, 0.00400666063036421, 0.689859929372401,
0.701074907893295, 0.835553284184042),c(0.001,0.001,0.001))
# Indices of parameters
ind1 <- (K+1):(2*K) # intercept
ind2 <- (2*K+1):(2*K+dim.cov) # regression coefficient except the intercept
ind3 <- (2*K+dim.cov+1):(3*K+dim.cov) # variance
ind4 <- 3*K+dim.cov+1 # alpha
ind5 <- ind4+1 # alpha_beta0
ind6 <- ind5+1 # alpha_sigma
ind7 <- ind6+1 # mu_beta0
ind8 <- ind7+1 # sigma_beta0
# Initial values for Gaussian variables for the Copula model
h <- rbind(cbind(y1,m1[,1:3],0,0,0,0),
cbind(0,0,0,0,y0,m0[,1:3]))
# Initial setting for R
R <- diag(1,P)
# Starting values for variances in adaptive sampler (1)
cov.y1 <- log(sqrt(diag(vcov(lm(y1~x1))[1,1],K)/4))
cov.m11 <- log(sqrt(diag(vcov(lm(m1[,1]~x1))[1,1],K)/4))
cov.m21 <- log(sqrt(diag(vcov(lm(m1[,2]~x1))[1,1],K)/4))
cov.m31 <- log(sqrt(diag(vcov(lm(m1[,3]~x1))[1,1],K)/4))
cov.y0 <- log(sqrt(diag(vcov(lm(y0~x0))[1,1],K)/4))
cov.m10 <- log(sqrt(diag(vcov(lm(m0[,1]~x0))[1,1],K)/4))
cov.m20 <- log(sqrt(diag(vcov(lm(m0[,2]~x0))[1,1],K)/4))
cov.m30 <- log(sqrt(diag(vcov(lm(m0[,3]~x0))[1,1],K)/4))
# Starting values for variances in adaptive sampler (2)
cov2.y1 <- log(sqrt(diag(diag(vcov(lm(y1~x1))[-1,-1]),K)/8))
cov2.m11 <- log(sqrt(diag(diag(vcov(lm(m1[,1]~x1))[-1,-1]),K)/8))
cov2.m21 <- log(sqrt(diag(diag(vcov(lm(m1[,2]~x1))[-1,-1]),K)/8))
cov2.m31 <- log(sqrt(diag(diag(vcov(lm(m1[,3]~x1))[-1,-1]),K)/8))
cov2.y0 <- log(sqrt(diag(diag(vcov(lm(y0~x0))[-1,-1]),K)/8))
cov2.m10 <- log(sqrt(diag(diag(vcov(lm(m0[,1]~x0))[-1,-1]),K)/8))
cov2.m20 <- log(sqrt(diag(diag(vcov(lm(m0[,2]~x0))[-1,-1]),K)/8))
cov2.m30 <- log(sqrt(diag(diag(vcov(lm(m0[,3]~x0))[-1,-1]),K)/8))
# Initial values for complete data: Y(1),Y(0),M(1,1,1),M(0,0,0)
y1 <- c(y1, rnorm(n0, mean(y1), sd(y1)))
y0 <- c(rnorm(n1, mean(y0), sd(y0)), y0)
m1 <- rbind(m1, rmnorm(n0, apply(m1, 2, mean), var(m1)))
m0 <- rbind(rmnorm(n1, apply(m0, 2, mean), var(m0)), m0)
#-------- Run MCMC
pb <- txtProgressBar(min = 0, max = MCMC, style = 3)
for (t in 3:MCMC){
# Break up the MCMC run into several batches (50 iterations each)
# to monitor and manipulate the acceptance rates for the adaptive samplers
SEQ <- seq(54, MCMC, by=50)
#### Y(1) ####
if(t %in% SEQ){
for(c in 1:K){
if(mean(para.y1[(t-51):(t-1),(dim(para.y1)[2]-3*K+c)]) < 0.44 ){
cov.y1[c,c] <- cov.y1[c,c]-min(0.01, 1/sqrt(t)) # reduce the variance by min(0.01, 1/sqrt(t))
}else{
cov.y1[c,c] <- cov.y1[c,c]+min(0.01, 1/sqrt(t)) # increase the variance by min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if(mean(para.y1[(t-51):(t-1),(dim(para.y1)[2]-1*K+c)]) < 0.44 ){
cov2.y1[c,c] <- cov2.y1[c,c]-min(0.01, 1/sqrt(t)) # reduce the variance by min(0.01, 1/sqrt(t))
}else{
cov2.y1[c,c] <- cov2.y1[c,c]+min(0.01, 1/sqrt(t)) # increase the variance by min(0.01, 1/sqrt(t))
}
}
}
para.y1[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=y1, R=R, w_pre=para.y1[t-1,2:K],
beta0_pre=para.y1[t-1,ind1], beta_pre=para.y1[t-1,ind2],sigma_pre=para.y1[t-1,ind3],
alpha_pre=para.y1[t-1,ind4], alpha_beta0_pre=para.y1[t-1,ind5], alpha_sigma_pre=para.y1[t-1,ind6],
mu_beta0_pre=para.y1[t-1,ind7], sigma_beta0_pre=para.y1[t-1,ind8],K=K, eps=0.1,
del1=15, del2=10, del3=30, index=1, cov1=cov.y1,cov2=cov2.y1, zz=1)
# Update a Gaussian variable for the Copula model
prop1 <- para.y1[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.y1 <- pprop1
h[,1] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(y1),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.y1[t,ind1]+sum(para.y1[t,ind2]*z[2:(dim(x0)[2]+1)]), sqrt(para.y1[t,ind3])))))))
#### Y(0) ####
if(t %in% SEQ){
for(c in 1:K){
if(mean(para.y0[(t-51):(t-1),(dim(para.y0)[2]-3*K+c)]) < 0.44 ){
cov.y0[c,c] <- cov.y0[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.y0[c,c] <- cov.y0[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if(mean(para.y0[(t-51):(t-1),(dim(para.y0)[2]-1*K+c)]) < 0.44 ){
cov2.y0[c,c] <- cov2.y0[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.y0[c,c] <- cov2.y0[c,c]+min(0.01, 1/sqrt(t)) }
}
}
para.y0[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=y0, R=R, w_pre=para.y0[t-1,2:K],
beta0_pre=para.y0[t-1,ind1], beta_pre=para.y0[t-1,ind2], sigma_pre=para.y0[t-1,ind3],
alpha_pre=para.y0[t-1,ind4], alpha_beta0_pre=para.y0[t-1,ind5], alpha_sigma_pre=para.y0[t-1,ind6],
mu_beta0_pre=para.y0[t-1,ind7], sigma_beta0_pre=para.y0[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=30, index=5, cov1=cov.y0, cov2=cov2.y0, zz=0)
prop1 <- para.y0[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.y0 <- pprop1
h[,5] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(y0),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.y0[t,ind1]+sum(para.y0[t,ind2]*z[2:(dim(x0)[2]+1)]),sqrt(para.y0[t,ind3])))))))
#### M1(0) ####
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m10[(t-51):(t-1),(dim(para.m10)[2]-3*K+c)]) < 0.44 ){
cov.m10[c,c] <- cov.m10[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m10[c,c] <- cov.m10[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m10[(t-51):(t-1),(dim(para.m10)[2]-1*K+c)]) < 0.44 ){
cov2.m10[c,c] <- cov2.m10[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m10[c,c] <- cov2.m10[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m10[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m0[,1], R=R, w_pre=para.m10[t-1,2:K],
beta0_pre=para.m10[t-1,ind1], beta_pre=para.m10[t-1,ind2], sigma_pre=para.m10[t-1,ind3],
alpha_pre=para.m10[t-1,ind4], alpha_beta0_pre=para.m10[t-1,ind5], alpha_sigma_pre=para.m10[t-1,ind6],
mu_beta0_pre=para.m10[t-1,ind7], sigma_beta0_pre=para.m10[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=6, cov1=cov.m10, cov2=cov2.m10, zz=0)
prop1 <- para.m10[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m10 <- pprop1
h[ ,6]<- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m0[,1]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m10[t,ind1]+sum(para.m10[t,ind2]*z[2:(dim(x0)[2]+1)]),sqrt(para.m10[t,ind3])))))))
#### M2(0) ####
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m20[(t-51):(t-1),(dim(para.m20)[2]-3*K+c)]) < 0.44 ){
cov.m20[c,c] <- cov.m20[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m20[c,c] <- cov.m20[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m20[(t-51):(t-1),(dim(para.m20)[2]-1*K+c)]) < 0.44 ){
cov2.m20[c,c] <- cov2.m20[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m20[c,c] <- cov2.m20[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m20[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m0[,2], R=R, w_pre=para.m20[t-1,2:K],
beta0_pre=para.m20[t-1,ind1], beta_pre=para.m20[t-1,ind2], sigma_pre=para.m20[t-1,ind3],
alpha_pre=para.m20[t-1,ind4], alpha_beta0_pre=para.m20[t-1,ind5], alpha_sigma_pre=para.m20[t-1,ind6],
mu_beta0_pre=para.m20[t-1,ind7], sigma_beta0_pre=para.m20[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=7, cov1=cov.m20, cov2=cov2.m20, zz=0)
prop1 <- para.m20[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m20 <- pprop1
h[ ,7] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m0[,2]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m20[t,ind1]+sum(para.m20[t,ind2]*z[2:(dim(x0)[2]+1)]),sqrt(para.m20[t,ind3])))))))
#### M3(0) ####
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m30[(t-51):(t-1),(dim(para.m30)[2]-3*K+c)]) < 0.44 ){
cov.m30[c,c] <- cov.m30[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m30[c,c] <- cov.m30[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m30[(t-51):(t-1),(dim(para.m30)[2]-1*K+c)]) < 0.44 ){
cov2.m30[c,c] <- cov2.m30[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m30[c,c] <- cov2.m30[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m30[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m0[,3], R=R, w_pre=para.m30[t-1,2:K],
beta0_pre=para.m30[t-1,ind1], beta_pre=para.m30[t-1,ind2], sigma_pre=para.m30[t-1,ind3],
alpha_pre=para.m30[t-1,ind4], alpha_beta0_pre=para.m30[t-1,ind5], alpha_sigma_pre=para.m30[t-1,ind6],
mu_beta0_pre=para.m30[t-1,ind7], sigma_beta0_pre=para.m30[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=8, cov1=cov.m30, cov2=cov2.m30, zz=0)
prop1 <- para.m30[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m30 <- pprop1
h[ ,8] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m0[,3]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m30[t,ind1]+sum(para.m30[t,ind2]*z[2:(dim(x0)[2]+1)]),sqrt(para.m30[t,ind3])))))))
#### M1(1) ####
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m11[(t-51):(t-1),(dim(para.m11)[2]-3*K+c)]) < 0.44 ){
cov.m11[c,c] <- cov.m11[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m11[c,c] <- cov.m11[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m11[(t-51):(t-1),(dim(para.m11)[2]-1*K+c)]) < 0.44 ){
cov2.m11[c,c] <- cov2.m11[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m11[c,c] <- cov2.m11[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m11[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m1[,1], R=R, w_pre=para.m11[t-1,2:K],
beta0_pre=para.m11[t-1,ind1], beta_pre=para.m11[t-1,ind2], sigma_pre=para.m11[t-1,ind3],
alpha_pre=para.m11[t-1,ind4], alpha_beta0_pre=para.m11[t-1,ind5], alpha_sigma_pre=para.m11[t-1,ind6],
mu_beta0_pre=para.m11[t-1,ind7], sigma_beta0_pre=para.m11[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=2, cov1=cov.m11, cov2=cov2.m11, zz=1)
prop1 <- para.m11[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m11 <- pprop1
h[ ,2] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m1[,1]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m11[t,ind1]+sum(para.m11[t,ind2]*z[2:(dim(x1)[2]+1)]),sqrt(para.m11[t,ind3])))))))
#### M2(1) ####
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m21[(t-51):(t-1),(dim(para.m21)[2]-3*K+c)]) < 0.44 ){
cov.m21[c,c] <- cov.m21[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m21[c,c] <- cov.m21[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m21[(t-51):(t-1),(dim(para.m21)[2]-1*K+c)]) < 0.44 ){
cov2.m21[c,c] <- cov2.m21[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m21[c,c] <- cov2.m21[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m21[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m1[,2], R=R, w_pre=para.m21[t-1,2:K],
beta0_pre=para.m21[t-1,ind1], beta_pre=para.m21[t-1,ind2], sigma_pre=para.m21[t-1,ind3],
alpha_pre=para.m21[t-1,ind4], alpha_beta0_pre=para.m21[t-1,ind5], alpha_sigma_pre=para.m21[t-1,ind6],
mu_beta0_pre=para.m21[t-1,ind7], sigma_beta0_pre=para.m21[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=3, cov1=cov.m21, cov2=cov2.m21,zz=1)
prop1 <- para.m21[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m21 <- pprop1
h[ ,3] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m1[,2]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m21[t,ind1]+sum(para.m21[t,ind2]*z[2:(dim(x1)[2]+1)]),sqrt(para.m21[t,ind3])))))))
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m31[(t-51):(t-1),(dim(para.m31)[2]-3*K+c)]) < 0.44 ){
cov.m31[c,c] <- cov.m31[c,c]-min(0.01, 1/sqrt(t))
}else{
cov.m31[c,c] <- cov.m31[c,c]+min(0.01, 1/sqrt(t))
}
}
}
if(t %in% SEQ){
for(c in 1:K){
if( mean(para.m31[(t-51):(t-1),(dim(para.m31)[2]-1*K+c)]) < 0.44 ){
cov2.m31[c,c] <- cov2.m31[c,c]-min(0.01, 1/sqrt(t))
}else{
cov2.m31[c,c] <- cov2.m31[c,c]+min(0.01, 1/sqrt(t))
}
}
}
para.m31[t,] <- metropolis(h=h, X=rbind(x1,x0), Y=m1[,3], R=R, w_pre=para.m31[t-1,2:K],
beta0_pre=para.m31[t-1,ind1], beta_pre=para.m31[t-1,ind2], sigma_pre=para.m31[t-1,ind3],
alpha_pre=para.m31[t-1,ind4], alpha_beta0_pre=para.m31[t-1,ind5], alpha_sigma_pre=para.m31[t-1,ind6],
mu_beta0_pre=para.m31[t-1,ind7], sigma_beta0_pre=para.m31[t-1,ind8], K=K, eps=0.1,
del1=15, del2=10, del3=20, index=4, cov1=cov.m31, cov2=cov2.m31, zz=1)
prop1 <- para.m31[t,2:K]
pprop1 <- NULL
pprop1[1] <- prop1[1]
pprop1[2:(K-1)] <- sapply(2:(K-1), function(i) prop1[i] * prod(1 - prop1[1:(i-1)]))
pprop1[K] <- prod(1-prop1[1:(K-1)])
pprop.m31 <- pprop1
h[,4] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,apply(cbind(c(m1[,3]),rbind(x1,x0)), 1, function(z)
sum(pprop1*pnorm(z[1],para.m31[t,ind1]+sum(para.m31[t,ind2]*z[2:(dim(x1)[2]+1)]),sqrt(para.m31[t,ind3])))))))
# Correlation parameters
para.C[t,1:59] <- metropolisC(h=h, rho=para.C[t-1,29:56], prho=para.C[t-1,57:59])
prop1 <- para.C[t,29:56]
# Update the correlation matrix R
R <- matrix(c(1,prop1[1:7],prop1[1],1,prop1[8:13],prop1[2],prop1[8],1,prop1[14:18],prop1[3],
prop1[9],prop1[14],1,prop1[19:22],prop1[4],prop1[10],prop1[15],prop1[19],1,
prop1[1:3],prop1[5],prop1[11],prop1[16],prop1[20],prop1[1],1,prop1[26:27],
prop1[6],prop1[12],prop1[17],prop1[21],prop1[2],prop1[26],1,prop1[28],prop1[7],
prop1[13],prop1[18],prop1[22],prop1[3],prop1[27],prop1[28],1),8,8,byrow=TRUE)
# Impute missing part of the Copula model based on R
h[(1+n1):(n1+n0),1:4] <- t(apply(h[(1+n1):(n1+n0),5:8], 1, function(x)
rmnorm(1, R[1:4,5:8]%*%solve(R[5:8,5:8])%*%c(x[1],x[2],x[3],x[4]), R[1:4,1:4]-R[1:4,5:8]%*%solve(R[5:8,5:8])%*%t(R[1:4,5:8]))))
h[1:n1,5:8] <- t(apply(h[1:n1,1:4], 1, function(x)
rmnorm(1, R[5:8,1:4]%*%solve(R[1:4,1:4])%*%c(x[1],x[2],x[3],x[4]), R[5:8,5:8]-R[5:8,1:4]%*%solve(R[1:4,1:4])%*%t(R[5:8,1:4]))))
# Update missing part of Y(1), Y(0), M(1,1,1) and M(0,0,0) from the above
clus.y1 <- apply(rmultinom(n0, 1, pprop.y1), 2, function(x) which(x==1)) # cluster membership
y1[(n1+1):(n1+n0)] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1+n1):(n1+n0),1]))), mean = para.y1[t,ind1][clus.y1]+x0%*%para.y1[t,ind2], sd=sqrt(para.y1[t,ind3][clus.y1]) )
clus.y0 <- apply(rmultinom(n1, 1, pprop.y0), 2, function(x) which(x==1)) # cluster membership
y0[(1):(n1)] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1):(n1),5]))), mean = para.y0[t,ind1][clus.y0]+x1%*%para.y0[t,ind2], sd=sqrt(para.y0[t,ind3][clus.y0]) )
clus.m11 <- apply(rmultinom(n0, 1, pprop.m11), 2, function(x) which(x==1)) # cluster membership
m1[(n1+1):(n1+n0),1] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1+n1):(n1+n0),2]))), mean = para.m11[t,ind1][clus.m11]+x0%*%para.m11[t,ind2], sd=sqrt(para.m11[t,ind3][clus.m11]) )
clus.m21 <- apply(rmultinom(n0, 1, pprop.m21), 2, function(x) which(x==1)) # cluster membership
m1[(n1+1):(n1+n0),2] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1+n1):(n1+n0),3]))), mean = para.m21[t,ind1][clus.m21]+x0%*%para.m21[t,ind2], sd=sqrt(para.m21[t,ind3][clus.m21]) )
clus.m31 <- apply(rmultinom(n0, 1, pprop.m31), 2, function(x) which(x==1)) # cluster membership
m1[(n1+1):(n1+n0),3] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1+n1):(n1+n0),4]))), mean = para.m31[t,ind1][clus.m31]+x0%*%para.m31[t,ind2], sd=sqrt(para.m31[t,ind3][clus.m31]) )
clus.m10 <- apply(rmultinom(n1, 1, pprop.m10), 2, function(x) which(x==1)) # cluster membership
m0[(1):(n1),1] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1):(n1),6]))), mean = para.m10[t,ind1][clus.m10]+x1%*%para.m10[t,ind2], sd=sqrt(para.m10[t,ind3][clus.m10]) )
clus.m20 <- apply(rmultinom(n1, 1, pprop.m20), 2, function(x) which(x==1)) # cluster membership
m0[(1):(n1),2] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1):(n1),7]))), mean = para.m20[t,ind1][clus.m20]+x1%*%para.m20[t,ind2], sd=sqrt(para.m20[t,ind3][clus.m20]) )
clus.m30 <- apply(rmultinom(n1, 1, pprop.m30), 2, function(x) which(x==1)) # cluster membership
m0[(1):(n1),3] <- qnorm(pmin(1-0.1^15,pmax(0.1^15,pnorm(h[(1):(n1),8]))), mean = para.m30[t,ind1][clus.m30]+x1%*%para.m30[t,ind2], sd=sqrt(para.m30[t,ind3][clus.m30]) )
Sys.sleep(0.001)
setTxtProgressBar(pb, t)
}
save.image("MCMCsamples.RData")
|
library(lubridate)
library(ggplot2)
library(dplyr)
source("plotit.R")
county_plot <- function(counties, countyname) {
county <- counties[counties$county %in% countyname,]
p <- plotit(county, paste0(countyname, " results"))
return(p)
}
plot_a_county <- function(counties, countyname) {
p <- county_plot(counties, countyname)
png(filename=paste0("images/", countyname, "_test_results.png"), width=1264, height=673)
print(p)
dev.off()
return(p)
}
raw <- read.csv("covid_test_data.csv")
# raw$Santa.Clara..Tests <- ifelse(is.na(raw$Santa.Clara..Tests), 0, raw$Santa.Clara..Tests)
# raw$Santa.Clara..Tests.1 <- ifelse(is.na(raw$Santa.Clara..Tests.1), 0, raw$Santa.Clara..Tests.1)
# some issues with the input data:
# column names are R-unfriendly, e.g. "Santa Clara +Tests", "Santa Clara -Tests"
# data is columnar, but I want row-wise
# plan: get the santa clara data into a usable format for plotting, then think about generalizing
# messy: relying on the mangled column names, e.g.
# "Santa Clara +Tests" became "Santa.Clara..Tests"
# "Santa Clara -Tests" became "Santa.Clara..Tests.1"
counties <- data.frame(
date=as.Date(character()),
county=character(),
result=character(),
count=integer(),
stringsAsFactors=F
)
county <- "Santa Clara"
colprefix <- gsub(" ", ".", county, fixed=T)
poscol <- paste0(colprefix, "..Tests")
negcol <- paste0(colprefix, "..Tests.1")
date <- as.Date(raw[,1])
count <- pull(raw, poscol)
count <- ifelse(is.na(count), 0, count)
pos <- data.frame(
date=date,
county=county,
result="positive",
count=count
)
pos$count <- cumsum(pos$count)
count <- pull(raw, negcol)
count <- ifelse(is.na(count), 0, count)
neg <- data.frame(
date=date,
county=county,
result="negative",
count=count
)
neg$count <- cumsum(neg$count)
counties <- rbind(pos, neg)
p <- plot_a_county(counties, county)
| /counties.R | no_license | aaronferrucci/c19_data | R | false | false | 1,862 | r | library(lubridate)
library(ggplot2)
library(dplyr)
source("plotit.R")
county_plot <- function(counties, countyname) {
county <- counties[counties$county %in% countyname,]
p <- plotit(county, paste0(countyname, " results"))
return(p)
}
plot_a_county <- function(counties, countyname) {
p <- county_plot(counties, countyname)
png(filename=paste0("images/", countyname, "_test_results.png"), width=1264, height=673)
print(p)
dev.off()
return(p)
}
raw <- read.csv("covid_test_data.csv")
# raw$Santa.Clara..Tests <- ifelse(is.na(raw$Santa.Clara..Tests), 0, raw$Santa.Clara..Tests)
# raw$Santa.Clara..Tests.1 <- ifelse(is.na(raw$Santa.Clara..Tests.1), 0, raw$Santa.Clara..Tests.1)
# some issues with the input data:
# column names are R-unfriendly, e.g. "Santa Clara +Tests", "Santa Clara -Tests"
# data is columnar, but I want row-wise
# plan: get the santa clara data into a usable format for plotting, then think about generalizing
# messy: relying on the mangled column names, e.g.
# "Santa Clara +Tests" became "Santa.Clara..Tests"
# "Santa Clara -Tests" became "Santa.Clara..Tests.1"
counties <- data.frame(
date=as.Date(character()),
county=character(),
result=character(),
count=integer(),
stringsAsFactors=F
)
county <- "Santa Clara"
colprefix <- gsub(" ", ".", county, fixed=T)
poscol <- paste0(colprefix, "..Tests")
negcol <- paste0(colprefix, "..Tests.1")
date <- as.Date(raw[,1])
count <- pull(raw, poscol)
count <- ifelse(is.na(count), 0, count)
pos <- data.frame(
date=date,
county=county,
result="positive",
count=count
)
pos$count <- cumsum(pos$count)
count <- pull(raw, negcol)
count <- ifelse(is.na(count), 0, count)
neg <- data.frame(
date=date,
county=county,
result="negative",
count=count
)
neg$count <- cumsum(neg$count)
counties <- rbind(pos, neg)
p <- plot_a_county(counties, county)
|
##### PHENOTYPE ASSOCIATION #####
library(ggplot2)
zscore<-c(1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1,1,1, 1,1 ,-1, -1, -1, -1, -1, -1, 1, 1)
genes<-c('RXFP3','PTPRT','PTPRT','IRF4','IRF4','IRF4','SLC45A2','SLC45A2','SLC45A2','SLC45A2','HERC2/OCA2','HERC2/OCA2','CCL13','HERC2/OCA2',
'HERC2/OCA2','HERC2/OCA2','MC1R','HERC2/OCA2','HERC2/OCA2','IRF4','IRF4','IRF4','IRF4','SLC45A2','SLC45A2','SLC45A2','SLC45A2','SLC45A2','HERC2/OCA2','HERC2/OCA2',
'HERC2/OCA2','HERC2/OCA2','RXFP3','RXFP3','RXFP3','RXFP3','RXFP3','GOLGA8F','GOLGA8F','GOLGA8F','GOLGA8F','GOLGA8F','GOLGA8F','GOLGA8F','GOLGA8F','ADAMTS12','ADAMTS12','ADAMTS12',
'ADAMTS12','TUBB3','TUBB3','MC1R','MC1R','TYRP1','TYRP1')
pheno<-c('dSunburn','qBrown hair','rBlack hair','rBlack hair','qBrown hair','cFreckles','hBrown skin','gWhite skin',
'fVery white skin','dSunburn','nBlack eyes','mBrown eyes','lLight brown eyes','kBlue/green eyes','jLight blue/green eyes',
'pBlond hair','oRed hair','bPhototype','aPhototype score','fVery white skin','kBlue/green eyes','mBrown eyes','dSunburn','bPhototype','aPhototype score','rBlack hair','qBrown hair',
'nBlack eyes','rBlack hair','gWhite skin','hBrown skin','dSunburn','hBrown skin','aPhototype score','bPhototype','gWhite skin','rBlack hair','nBlack eyes','mBrown eyes','kBlue/green eyes','jLight blue/green eyes',
'rBlack hair','pBlond hair','bPhototype','aPhototype score','aPhototype score','bPhototype','hBrown skin','rBlack hair','bPhototype','aPhototype score','bPhototype','aPhototype score','bPhototype',
'aPhototype score')
data<-data.frame(genes,pheno,zscore)
p<-ggplot(data,aes(x=genes,y=pheno,fill=factor(zscore)))+geom_tile(color='grey')+theme(axis.title.y = element_blank(), #Remove the y-axis title
axis.text.x = element_text(angle = 90, vjust = 0.5, face='italic'))
p <- p +theme(
panel.background = element_rect(fill = "transparent") #All rectangles
)
p<-p+scale_y_discrete(labels = c('Phototype score','Phototype','Freckles','Skin sensitivity','Very white skin','White skin','Brown skin','Light blue/green eyes','Blue/green eyes','Light brown eyes','Brown eyes',
'Black eyes','Red hair','Blond hair','Brown hair','Black hair'))
p + scale_fill_discrete(name = 'Z-score', labels = c('Negative','Positive')) #Legend
##### CHROMOSOME LOCATION #####
library(ggplot2)
gene<-c('aADAMTS12','bSLC45A2','cRXFP3','eIRF4','dEXOC2','gTYR','fNOX4','hKATNAL1','iOCA2','kHERC2','jGOLGA8F','mMC1R','lGAS8','nTUBB3','oPTPRT')
chr<-c('achr5q35','bchr5p13','cchr5p15','dchr6p25','dchr6p25','echr11q14','echr11q14','fchr13q12','gchr15q11','hchr15q13','hchr15q13','ichr16q24',
'ichr16q24','ichr16q24','jchr20q12')
data2<-data.frame(gene,chr)
p<-ggplot(data2,aes(x=chr,y=gene,fill='green'))+geom_tile(color='grey',show.legend=FALSE)
p<-p+theme(axis.title.y = element_blank(),axis.text.y = element_text(face = 'italic'),
axis.text.x = element_text(angle = 90, vjust = 0.5))
p <- p +theme(
panel.background = element_rect(fill = "transparent") #All rectangles
)
p<-p+scale_x_discrete(labels=c('chr5q35','chr5p13','chr5p15','chr6p25','chr11q14','chr13q12','chr15q11','chr15q13','chr16q24','chr20q12'))
p+scale_y_discrete(labels=c('ADAMTS12','SLC45A2','RXFP3','EXOC2','IRF4','NOX4','TYR',
'KATNAL1','OCA2','GOLGA8F','HERC2','GAS8','MC1R','TUBB3','PTPRT'))
| /heatmap.R | no_license | marrnavarro/FDP | R | false | false | 3,596 | r | ##### PHENOTYPE ASSOCIATION #####
library(ggplot2)
zscore<-c(1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1,1,1, 1,1 ,-1, -1, -1, -1, -1, -1, 1, 1)
genes<-c('RXFP3','PTPRT','PTPRT','IRF4','IRF4','IRF4','SLC45A2','SLC45A2','SLC45A2','SLC45A2','HERC2/OCA2','HERC2/OCA2','CCL13','HERC2/OCA2',
'HERC2/OCA2','HERC2/OCA2','MC1R','HERC2/OCA2','HERC2/OCA2','IRF4','IRF4','IRF4','IRF4','SLC45A2','SLC45A2','SLC45A2','SLC45A2','SLC45A2','HERC2/OCA2','HERC2/OCA2',
'HERC2/OCA2','HERC2/OCA2','RXFP3','RXFP3','RXFP3','RXFP3','RXFP3','GOLGA8F','GOLGA8F','GOLGA8F','GOLGA8F','GOLGA8F','GOLGA8F','GOLGA8F','GOLGA8F','ADAMTS12','ADAMTS12','ADAMTS12',
'ADAMTS12','TUBB3','TUBB3','MC1R','MC1R','TYRP1','TYRP1')
pheno<-c('dSunburn','qBrown hair','rBlack hair','rBlack hair','qBrown hair','cFreckles','hBrown skin','gWhite skin',
'fVery white skin','dSunburn','nBlack eyes','mBrown eyes','lLight brown eyes','kBlue/green eyes','jLight blue/green eyes',
'pBlond hair','oRed hair','bPhototype','aPhototype score','fVery white skin','kBlue/green eyes','mBrown eyes','dSunburn','bPhototype','aPhototype score','rBlack hair','qBrown hair',
'nBlack eyes','rBlack hair','gWhite skin','hBrown skin','dSunburn','hBrown skin','aPhototype score','bPhototype','gWhite skin','rBlack hair','nBlack eyes','mBrown eyes','kBlue/green eyes','jLight blue/green eyes',
'rBlack hair','pBlond hair','bPhototype','aPhototype score','aPhototype score','bPhototype','hBrown skin','rBlack hair','bPhototype','aPhototype score','bPhototype','aPhototype score','bPhototype',
'aPhototype score')
data<-data.frame(genes,pheno,zscore)
p<-ggplot(data,aes(x=genes,y=pheno,fill=factor(zscore)))+geom_tile(color='grey')+theme(axis.title.y = element_blank(), #Remove the y-axis title
axis.text.x = element_text(angle = 90, vjust = 0.5, face='italic'))
p <- p +theme(
panel.background = element_rect(fill = "transparent") #All rectangles
)
p<-p+scale_y_discrete(labels = c('Phototype score','Phototype','Freckles','Skin sensitivity','Very white skin','White skin','Brown skin','Light blue/green eyes','Blue/green eyes','Light brown eyes','Brown eyes',
'Black eyes','Red hair','Blond hair','Brown hair','Black hair'))
p + scale_fill_discrete(name = 'Z-score', labels = c('Negative','Positive')) #Legend
##### CHROMOSOME LOCATION #####
library(ggplot2)
gene<-c('aADAMTS12','bSLC45A2','cRXFP3','eIRF4','dEXOC2','gTYR','fNOX4','hKATNAL1','iOCA2','kHERC2','jGOLGA8F','mMC1R','lGAS8','nTUBB3','oPTPRT')
chr<-c('achr5q35','bchr5p13','cchr5p15','dchr6p25','dchr6p25','echr11q14','echr11q14','fchr13q12','gchr15q11','hchr15q13','hchr15q13','ichr16q24',
'ichr16q24','ichr16q24','jchr20q12')
data2<-data.frame(gene,chr)
p<-ggplot(data2,aes(x=chr,y=gene,fill='green'))+geom_tile(color='grey',show.legend=FALSE)
p<-p+theme(axis.title.y = element_blank(),axis.text.y = element_text(face = 'italic'),
axis.text.x = element_text(angle = 90, vjust = 0.5))
p <- p +theme(
panel.background = element_rect(fill = "transparent") #All rectangles
)
p<-p+scale_x_discrete(labels=c('chr5q35','chr5p13','chr5p15','chr6p25','chr11q14','chr13q12','chr15q11','chr15q13','chr16q24','chr20q12'))
p+scale_y_discrete(labels=c('ADAMTS12','SLC45A2','RXFP3','EXOC2','IRF4','NOX4','TYR',
'KATNAL1','OCA2','GOLGA8F','HERC2','GAS8','MC1R','TUBB3','PTPRT'))
|
\name{add_travis}
\alias{add_travis}
\title{Add basic travis template to a package}
\usage{
add_travis(pkg = ".")
}
\arguments{
\item{pkg}{package description, can be path or package
name. See \code{\link{as.package}} for more information}
}
\description{
Also adds \code{.travis.yml} to \code{.Rbuildignore} so it
isn't included in the built package
}
| /man/add_travis.Rd | no_license | 3sR/devtools | R | false | false | 359 | rd | \name{add_travis}
\alias{add_travis}
\title{Add basic travis template to a package}
\usage{
add_travis(pkg = ".")
}
\arguments{
\item{pkg}{package description, can be path or package
name. See \code{\link{as.package}} for more information}
}
\description{
Also adds \code{.travis.yml} to \code{.Rbuildignore} so it
isn't included in the built package
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/get_leverage_centrality.R
\name{get_leverage_centrality}
\alias{get_leverage_centrality}
\title{Get leverage centrality}
\usage{
get_leverage_centrality(graph)
}
\arguments{
\item{graph}{a graph object of class
\code{dgr_graph}.}
}
\value{
a data frame with leverage centrality
values for each of the nodes.
}
\description{
Get the leverage centrality values
for all nodes in the graph. Leverage centrality
is a measure of the relationship between the degree
of a given node and the degree of each of its
neighbors, averaged over all neighbors. A node
with negative leverage centrality is influenced
by its neighbors, as the neighbors connect and
interact with far more nodes. A node with positive
leverage centrality influences its neighbors since
the neighbors tend to have far fewer connections.
}
\examples{
# Create a random graph
graph <-
create_random_graph(
n = 10, m = 22,
set_seed = 23)
# Get leverage centrality values for
# all nodes in the graph
get_leverage_centrality(graph)
#> id leverage_centrality
#> 1 1 -0.16498316
#> 2 2 -0.05555556
#> 3 3 -0.16498316
#> 4 4 -0.30000000
#> 5 5 -0.05555556
#> 6 6 0.11111111
#> 7 7 -0.16498316
#> 8 8 -0.47089947
#> 9 9 -0.05555556
#> 10 10 -0.05555556
# Add the leverage centrality values
# to the graph as a node attribute
graph <-
graph \%>\%
join_node_attrs(
df = get_leverage_centrality(.)) \%>\%
drop_node_attrs(node_attr = value)
# Display the graph's node data frame
get_node_df(graph)
#> id type label leverage_centrality
#> 1 1 <NA> 1 -0.16498316
#> 2 2 <NA> 2 -0.05555556
#> 3 3 <NA> 3 -0.16498316
#> 4 4 <NA> 4 -0.30000000
#> 5 5 <NA> 5 -0.05555556
#> 6 6 <NA> 6 0.11111111
#> 7 7 <NA> 7 -0.16498316
#> 8 8 <NA> 8 -0.47089947
#> 9 9 <NA> 9 -0.05555556
#> 10 10 <NA> 10 -0.05555556
}
| /man/get_leverage_centrality.Rd | permissive | ktaranov/DiagrammeR | R | false | true | 2,093 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/get_leverage_centrality.R
\name{get_leverage_centrality}
\alias{get_leverage_centrality}
\title{Get leverage centrality}
\usage{
get_leverage_centrality(graph)
}
\arguments{
\item{graph}{a graph object of class
\code{dgr_graph}.}
}
\value{
a data frame with leverage centrality
values for each of the nodes.
}
\description{
Get the leverage centrality values
for all nodes in the graph. Leverage centrality
is a measure of the relationship between the degree
of a given node and the degree of each of its
neighbors, averaged over all neighbors. A node
with negative leverage centrality is influenced
by its neighbors, as the neighbors connect and
interact with far more nodes. A node with positive
leverage centrality influences its neighbors since
the neighbors tend to have far fewer connections.
}
\examples{
# Create a random graph
graph <-
create_random_graph(
n = 10, m = 22,
set_seed = 23)
# Get leverage centrality values for
# all nodes in the graph
get_leverage_centrality(graph)
#> id leverage_centrality
#> 1 1 -0.16498316
#> 2 2 -0.05555556
#> 3 3 -0.16498316
#> 4 4 -0.30000000
#> 5 5 -0.05555556
#> 6 6 0.11111111
#> 7 7 -0.16498316
#> 8 8 -0.47089947
#> 9 9 -0.05555556
#> 10 10 -0.05555556
# Add the leverage centrality values
# to the graph as a node attribute
graph <-
graph \%>\%
join_node_attrs(
df = get_leverage_centrality(.)) \%>\%
drop_node_attrs(node_attr = value)
# Display the graph's node data frame
get_node_df(graph)
#> id type label leverage_centrality
#> 1 1 <NA> 1 -0.16498316
#> 2 2 <NA> 2 -0.05555556
#> 3 3 <NA> 3 -0.16498316
#> 4 4 <NA> 4 -0.30000000
#> 5 5 <NA> 5 -0.05555556
#> 6 6 <NA> 6 0.11111111
#> 7 7 <NA> 7 -0.16498316
#> 8 8 <NA> 8 -0.47089947
#> 9 9 <NA> 9 -0.05555556
#> 10 10 <NA> 10 -0.05555556
}
|
# initialize random number generator
set.seed(NULL)
# read spectral soil data
soil_spec_data <- read.csv("../pro-files/data/soil-spec.csv", sep=";")
# define data dimensions
# number of wavelengths
wl_count <- dim(soil_spec_data)[2] - 3
# number of samples
sample_count <- dim(soil_spec_data)[1]
# number of observables
obs_count <- 3
# construct all wavelengths (only hard coded; future: has to be read from data)
wl_vec <- seq(1400, 2672, by = 4)
# get matrix of reflectance values
refl_mat <- as.matrix(soil_spec_data[,(obs_count+1):dim(soil_spec_data)[2]])
# get matrix of observables
obs_mat <- as.matrix(soil_spec_data[,1:obs_count])
# set vector of observables (easy to read and write)
soc_vec <- as.vector(obs_mat[,1])
n_vec <- as.vector(obs_mat[,2])
ph_vec <- as.vector(obs_mat[,3])
# design matrices
soc_design_mat <- cbind(1,refl_mat)
n_design_mat <- soc_design_mat
ph_design_mat <- cbind(1,log(refl_mat)) | /src/init.r | no_license | lyrahgames/nirs-soil-parameter-prediction | R | false | false | 920 | r | # initialize random number generator
set.seed(NULL)
# read spectral soil data
soil_spec_data <- read.csv("../pro-files/data/soil-spec.csv", sep=";")
# define data dimensions
# number of wavelengths
wl_count <- dim(soil_spec_data)[2] - 3
# number of samples
sample_count <- dim(soil_spec_data)[1]
# number of observables
obs_count <- 3
# construct all wavelengths (only hard coded; future: has to be read from data)
wl_vec <- seq(1400, 2672, by = 4)
# get matrix of reflectance values
refl_mat <- as.matrix(soil_spec_data[,(obs_count+1):dim(soil_spec_data)[2]])
# get matrix of observables
obs_mat <- as.matrix(soil_spec_data[,1:obs_count])
# set vector of observables (easy to read and write)
soc_vec <- as.vector(obs_mat[,1])
n_vec <- as.vector(obs_mat[,2])
ph_vec <- as.vector(obs_mat[,3])
# design matrices
soc_design_mat <- cbind(1,refl_mat)
n_design_mat <- soc_design_mat
ph_design_mat <- cbind(1,log(refl_mat)) |
\name{limmaPLM}
\alias{limmaPLM}
\title{
Adapt Additive Partially Linear Models for Testing via \code{\link{limma}}
}
\description{
Uses the methods of \code{\link{fitGAPLM}} to generate linear models of the class
\code{MArrayLM} so that the moderated t and F methods of \code{\link{limma}} may be used to test for differential gene expression. See \code{\link{fitGAPLM}} for more a more in-depth description of the inputs.
}
\usage{
limmaPLM(dataObject, intercept = TRUE,
indicators = as.character(unique(dataObject$sampleInfo[,2])[-1]),
continuousCovariates = NULL,
groups = as.character(unique(dataObject$sampleInfo[,2])[-1]),
groupFunctions = rep("AdditiveSpline", length(groups)),
fitSplineFromData = TRUE, splineDegrees = rep(3, length(groups)),
splineKnots = rep(0, length(groups)), splineKnotSpread = "quantile", ...)
}
\arguments{
\item{dataObject}{
An object of type \code{plmDE} which we wish to test for differential gene expression.
}
\item{intercept}{
Should an intercept term be included in the model?
}
\item{indicators}{
Same as \code{indicators.fullModel} in \code{\link{fitGAPLM}}. Note that choice of \code{intercept} should affect choice of \code{indicators}.
}
\item{continuousCovariates}{
Same as \code{continuousCovariates.fullModel} in \code{\link{fitGAPLM}}.
}
\item{groups}{
Same as \code{groups.fullModel} in \code{\link{fitGAPLM}}.
}
\item{groupFunctions}{
Same as \code{groupFunctions.fullModel} in \code{\link{fitGAPLM}}.
}
\item{fitSplineFromData}{
Same as \code{fitSplineFromData} in \code{\link{fitGAPLM}}.
}
\item{splineDegrees}{
Same as \code{splineDegrees.fullModel} in \code{\link{fitGAPLM}}.
}
\item{splineKnots}{
Same as \code{splineKnots.fullModel} in \code{\link{fitGAPLM}}.
}
\item{splineKnotSpread}{
Same as \code{splineKnotSpread} in \code{\link{fitGAPLM}}.
}
\item{\dots}{
parameters to be passed to \code{lmFit} in \code{\link{limma}}.
}
}
\value{
This method returns an \code{MarrayLM} object on which we can call \code{eBayes()} and \code{topTable()} to test for differentially expressed genes.
}
\references{
Smyth, G. K. Linear Models and empirical Bayes methods for assesing differential expression in microarray experiments. Stat Appl Genet Mol Biol. \bold{3}, Article 3 (2004).
}
\author{
Jonas Mueller}
\seealso{
\code{\link{fitGAPLM}}, \code{\link{plmDE}}, \code{\link{limma}}
}
\examples{
## create an object of type \code{plmDE} containing disease
## with "control" and "disease" and measurements of weight and severity:
ExpressionData = as.data.frame(matrix(abs(rnorm(10000, 1, 1.5)), ncol = 100))
names(ExpressionData) = sapply(1:100, function(x) paste("Sample", x))
Genes = sapply(1:100, function(x) paste("Gene", x))
DataInfo = data.frame(sample = names(ExpressionData), group = c(rep("Control", 50),
rep("Diseased", 50)), weight = abs(rnorm(100, 50, 20)), severity = c(rep(0, 50),
abs(rnorm(50, 100, 20))))
plmDEobject = plmDEmodel(Genes, ExpressionData, DataInfo)
## create a linear model from which various hypotheses can be tested:
toTest = limmaPLM(plmDEobject, continuousCovariates = c("weight", "severity"),
fitSplineFromData = TRUE, splineDegrees = rep(3, length(groups)),
splineKnots = rep(0, length(groups)), splineKnotSpread = "quantile")
## view the coefficients/variables in the model:
toTest$coefficients[1, ]
weightCoefficients = c("DiseasedBasisFunction.weight.1",
"DiseasedBasisFunction.weight.2", "DiseasedBasisFunction.weight.3",
"DiseasedBasisFunction.weight.4", "DiseasedBasisFunction.weight.5",
"DiseasedBasisFunction.weight.6", "DiseasedBasisFunction.weight.7",
"DiseasedBasisFunction.weight.8", "DiseasedBasisFunction.weight.9")
## test the significance of weight in variation of the expression levels:
toTestCoefficients = contrasts.fit(toTest, coefficients = weightCoefficients)
moderatedTest = eBayes(toTestCoefficients)
topTableF(moderatedTest)
}
| /man/limmaPLM.Rd | no_license | cran/plmDE | R | false | false | 3,898 | rd | \name{limmaPLM}
\alias{limmaPLM}
\title{
Adapt Additive Partially Linear Models for Testing via \code{\link{limma}}
}
\description{
Uses the methods of \code{\link{fitGAPLM}} to generate linear models of the class
\code{MArrayLM} so that the moderated t and F methods of \code{\link{limma}} may be used to test for differential gene expression. See \code{\link{fitGAPLM}} for more a more in-depth description of the inputs.
}
\usage{
limmaPLM(dataObject, intercept = TRUE,
indicators = as.character(unique(dataObject$sampleInfo[,2])[-1]),
continuousCovariates = NULL,
groups = as.character(unique(dataObject$sampleInfo[,2])[-1]),
groupFunctions = rep("AdditiveSpline", length(groups)),
fitSplineFromData = TRUE, splineDegrees = rep(3, length(groups)),
splineKnots = rep(0, length(groups)), splineKnotSpread = "quantile", ...)
}
\arguments{
\item{dataObject}{
An object of type \code{plmDE} which we wish to test for differential gene expression.
}
\item{intercept}{
Should an intercept term be included in the model?
}
\item{indicators}{
Same as \code{indicators.fullModel} in \code{\link{fitGAPLM}}. Note that choice of \code{intercept} should affect choice of \code{indicators}.
}
\item{continuousCovariates}{
Same as \code{continuousCovariates.fullModel} in \code{\link{fitGAPLM}}.
}
\item{groups}{
Same as \code{groups.fullModel} in \code{\link{fitGAPLM}}.
}
\item{groupFunctions}{
Same as \code{groupFunctions.fullModel} in \code{\link{fitGAPLM}}.
}
\item{fitSplineFromData}{
Same as \code{fitSplineFromData} in \code{\link{fitGAPLM}}.
}
\item{splineDegrees}{
Same as \code{splineDegrees.fullModel} in \code{\link{fitGAPLM}}.
}
\item{splineKnots}{
Same as \code{splineKnots.fullModel} in \code{\link{fitGAPLM}}.
}
\item{splineKnotSpread}{
Same as \code{splineKnotSpread} in \code{\link{fitGAPLM}}.
}
\item{\dots}{
parameters to be passed to \code{lmFit} in \code{\link{limma}}.
}
}
\value{
This method returns an \code{MarrayLM} object on which we can call \code{eBayes()} and \code{topTable()} to test for differentially expressed genes.
}
\references{
Smyth, G. K. Linear Models and empirical Bayes methods for assesing differential expression in microarray experiments. Stat Appl Genet Mol Biol. \bold{3}, Article 3 (2004).
}
\author{
Jonas Mueller}
\seealso{
\code{\link{fitGAPLM}}, \code{\link{plmDE}}, \code{\link{limma}}
}
\examples{
## create an object of type \code{plmDE} containing disease
## with "control" and "disease" and measurements of weight and severity:
ExpressionData = as.data.frame(matrix(abs(rnorm(10000, 1, 1.5)), ncol = 100))
names(ExpressionData) = sapply(1:100, function(x) paste("Sample", x))
Genes = sapply(1:100, function(x) paste("Gene", x))
DataInfo = data.frame(sample = names(ExpressionData), group = c(rep("Control", 50),
rep("Diseased", 50)), weight = abs(rnorm(100, 50, 20)), severity = c(rep(0, 50),
abs(rnorm(50, 100, 20))))
plmDEobject = plmDEmodel(Genes, ExpressionData, DataInfo)
## create a linear model from which various hypotheses can be tested:
toTest = limmaPLM(plmDEobject, continuousCovariates = c("weight", "severity"),
fitSplineFromData = TRUE, splineDegrees = rep(3, length(groups)),
splineKnots = rep(0, length(groups)), splineKnotSpread = "quantile")
## view the coefficients/variables in the model:
toTest$coefficients[1, ]
weightCoefficients = c("DiseasedBasisFunction.weight.1",
"DiseasedBasisFunction.weight.2", "DiseasedBasisFunction.weight.3",
"DiseasedBasisFunction.weight.4", "DiseasedBasisFunction.weight.5",
"DiseasedBasisFunction.weight.6", "DiseasedBasisFunction.weight.7",
"DiseasedBasisFunction.weight.8", "DiseasedBasisFunction.weight.9")
## test the significance of weight in variation of the expression levels:
toTestCoefficients = contrasts.fit(toTest, coefficients = weightCoefficients)
moderatedTest = eBayes(toTestCoefficients)
topTableF(moderatedTest)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/summary.bcmmrm.R
\name{summary.bcmmrm}
\alias{summary.bcmmrm}
\title{Summarize a bcmmrm Object.}
\usage{
\method{summary}{bcmmrm}(object, robust = TRUE, ssadjust = TRUE, ...)
}
\arguments{
\item{object}{an object inheriting from class "\code{bcmmrm}", representing
the Box-Cox transformed MMRM analysis.}
\item{robust}{an optional logical value used to specify whether to apply
the robust inference. The default is \code{TRUE}.}
\item{ssadjust}{an optional logical value used to specify whether to apply
the empirical small sample adjustment. The default is \code{TRUE}.}
\item{...}{some methods for this generic require additional arguments.
None are used in this method.}
}
\value{
an object inheriting from class \code{summary.bcmmrm} with all
components included in \code{object} (see \code{\link{glsObject}} for
a full description of the components) plus the following components:
\describe{
\item{\code{median}}{a list including inference results of the model median
for specified values of \code{robust} and \code{ssadjust}.}
\item{\code{meddif}}{a list including inference results of the model median
difference for specified values of \code{robust} and
\code{ssadjust}.}
\item{\code{robust}}{a specified value of \code{robust}.}
\item{\code{ssadjust}}{a specified value of \code{ssadjust}.}
}
}
\description{
Additional information about the Box-Cox transformed MMRM analysis
represented by \code{object} is extracted and included as components
of \code{object}.
}
\examples{
data(aidscd4)
resar <- bcmarg(cd4 ~ as.factor(treatment), aidscd4, weekc, id, "AR(1)")
summary(resar)
}
\seealso{
\code{\link{bcmmrm}}, \code{\link{bcmmrmObject}},
\code{\link{summary}}
}
| /man/summary.bcmmrm.Rd | no_license | cran/bcmixed | R | false | true | 1,799 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/summary.bcmmrm.R
\name{summary.bcmmrm}
\alias{summary.bcmmrm}
\title{Summarize a bcmmrm Object.}
\usage{
\method{summary}{bcmmrm}(object, robust = TRUE, ssadjust = TRUE, ...)
}
\arguments{
\item{object}{an object inheriting from class "\code{bcmmrm}", representing
the Box-Cox transformed MMRM analysis.}
\item{robust}{an optional logical value used to specify whether to apply
the robust inference. The default is \code{TRUE}.}
\item{ssadjust}{an optional logical value used to specify whether to apply
the empirical small sample adjustment. The default is \code{TRUE}.}
\item{...}{some methods for this generic require additional arguments.
None are used in this method.}
}
\value{
an object inheriting from class \code{summary.bcmmrm} with all
components included in \code{object} (see \code{\link{glsObject}} for
a full description of the components) plus the following components:
\describe{
\item{\code{median}}{a list including inference results of the model median
for specified values of \code{robust} and \code{ssadjust}.}
\item{\code{meddif}}{a list including inference results of the model median
difference for specified values of \code{robust} and
\code{ssadjust}.}
\item{\code{robust}}{a specified value of \code{robust}.}
\item{\code{ssadjust}}{a specified value of \code{ssadjust}.}
}
}
\description{
Additional information about the Box-Cox transformed MMRM analysis
represented by \code{object} is extracted and included as components
of \code{object}.
}
\examples{
data(aidscd4)
resar <- bcmarg(cd4 ~ as.factor(treatment), aidscd4, weekc, id, "AR(1)")
summary(resar)
}
\seealso{
\code{\link{bcmmrm}}, \code{\link{bcmmrmObject}},
\code{\link{summary}}
}
|
\name{BSGS.PE}
\alias{BSGS.PE}
%\keyword{arith}
\title{Posterior estimates of parameters.}
\description{Provide the posterior estimates of parameters.}
\usage{BSGS.PE(BSGS.Output)}
\arguments{
\item{BSGS.Output}{A list of random samples generated from the posterior distribution by MCMC procedures.}
}
\value{A list is returned with estimates of regression coefficients, \eqn{\beta}, the posterior probability of binary variable \eqn{\eta} for group selection equal to 1, binary variable \eqn{\gamma} for variable selection equal to 1,
and variance, \eqn{\sigma^2}.}
\examples{
\dontrun{
output = BSGS.Simple(Y, X, Group.Index, r.value, eta.value, beta.value, tau2.value,
rho.value, theta.value, sigma2.value, nu, lambda,
Num.of.Iter.Inside.CompWise, Num.Of.Iteration, MCSE.Sigma2.Given)
BSGS.PE(output)
}
}
| /man/BSGS.PE.Rd | no_license | cran/BSGS | R | false | false | 815 | rd | \name{BSGS.PE}
\alias{BSGS.PE}
%\keyword{arith}
\title{Posterior estimates of parameters.}
\description{Provide the posterior estimates of parameters.}
\usage{BSGS.PE(BSGS.Output)}
\arguments{
\item{BSGS.Output}{A list of random samples generated from the posterior distribution by MCMC procedures.}
}
\value{A list is returned with estimates of regression coefficients, \eqn{\beta}, the posterior probability of binary variable \eqn{\eta} for group selection equal to 1, binary variable \eqn{\gamma} for variable selection equal to 1,
and variance, \eqn{\sigma^2}.}
\examples{
\dontrun{
output = BSGS.Simple(Y, X, Group.Index, r.value, eta.value, beta.value, tau2.value,
rho.value, theta.value, sigma2.value, nu, lambda,
Num.of.Iter.Inside.CompWise, Num.Of.Iteration, MCSE.Sigma2.Given)
BSGS.PE(output)
}
}
|
# plot1
# checking if achieve already exist
courseFile <- "Electric Power Consumption.zip"
if(!file.exists(courseFile)){
fileUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(fileUrl, courseFile)
}
# checking if folder exists
if (!file.exists("EPC")) { #EPC stands for Electric Power Consumption
unzip(courseFile)
}
# reading the data
library(readr)
df_raw <- read_delim("household_power_consumption.txt", delim = ";")
# substting the data
library(dplyr)
library(lubridate)
df <- df_raw %>% mutate(Date = dmy(Date)) %>%
mutate(Time = hms(Time)) %>%
filter(Date == "2007-02-01" | Date == "2007-02-02")
# plot
hist(df$Global_active_power,
main = "Global Active Power",
xlab = "Global Active Power (kilowatts)",
ylab = "Frequency",
col = "red")
# to png
png("plot1.png", width=480, height=480)
dev.off() | /plot1.R | no_license | asadalishah/ExData_Plotting1 | R | false | false | 899 | r | # plot1
# checking if achieve already exist
courseFile <- "Electric Power Consumption.zip"
if(!file.exists(courseFile)){
fileUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(fileUrl, courseFile)
}
# checking if folder exists
if (!file.exists("EPC")) { #EPC stands for Electric Power Consumption
unzip(courseFile)
}
# reading the data
library(readr)
df_raw <- read_delim("household_power_consumption.txt", delim = ";")
# substting the data
library(dplyr)
library(lubridate)
df <- df_raw %>% mutate(Date = dmy(Date)) %>%
mutate(Time = hms(Time)) %>%
filter(Date == "2007-02-01" | Date == "2007-02-02")
# plot
hist(df$Global_active_power,
main = "Global Active Power",
xlab = "Global Active Power (kilowatts)",
ylab = "Frequency",
col = "red")
# to png
png("plot1.png", width=480, height=480)
dev.off() |
#Total number of cells
TotalCells <- nrow(Design)
for (i in 1:TotalCells){
Row <- i
print(i / TotalCells)
MyResult <- MySimulationCell(Design = Design, RowOfDesign = Row, K = 100000)
# Write output of one cell of the design
save(MyResult, file =file.path("results",paste0("MyResult", "Row", Row,".Rdata" , sep ="")))
}
| /SimulationAllCells.R | no_license | BasvanDalsum/Bachelors-Thesis | R | false | false | 338 | r | #Total number of cells
TotalCells <- nrow(Design)
for (i in 1:TotalCells){
Row <- i
print(i / TotalCells)
MyResult <- MySimulationCell(Design = Design, RowOfDesign = Row, K = 100000)
# Write output of one cell of the design
save(MyResult, file =file.path("results",paste0("MyResult", "Row", Row,".Rdata" , sep ="")))
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/funs_GUI.R
\name{create_net2plot}
\alias{create_net2plot}
\title{Create an igraph object of the chromatin interaction network (CIN) for visualization purposes}
\usage{
create_net2plot(
g_net,
input_m,
gf_prop,
ann_net_b,
frag_pattern = "F",
ff_net = NULL,
ff_prop = NULL
)
}
\arguments{
\item{g_net}{Edge list of the chromatin interaction network such that first column are genes and second column are "FragX" fragments}
\item{input_m}{numeric matrix of a cell expression profile before the propagation}
\item{gf_prop}{numeric matrix of a cell profile after the first step of the propagation applied with only the gene-genic fragment component of the CIN}
\item{ann_net_b}{data.frame, for each row presents the gene identifier, the chromosome in which the gene is, the starting and ending position in the sequence.}
\item{frag_pattern}{string, initial character of the fragments name (e.g. "F" or "Frag")}
\item{ff_net}{Edge list of the chromatin interaction network such that first and second column are "FragX" fragments}
\item{ff_prop}{numeric matrix of a cell profile after the second step of the propagation applied with the fragment-fragment component of the CIN}
}
\value{
igraph object
}
\description{
Given the input and output of the two step network based propagation, it assembles an igraph object of the CIN with all
the information included in order to be visualized or analysed
}
| /man/create_net2plot.Rd | permissive | InfOmics/Esearch3D | R | false | true | 1,493 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/funs_GUI.R
\name{create_net2plot}
\alias{create_net2plot}
\title{Create an igraph object of the chromatin interaction network (CIN) for visualization purposes}
\usage{
create_net2plot(
g_net,
input_m,
gf_prop,
ann_net_b,
frag_pattern = "F",
ff_net = NULL,
ff_prop = NULL
)
}
\arguments{
\item{g_net}{Edge list of the chromatin interaction network such that first column are genes and second column are "FragX" fragments}
\item{input_m}{numeric matrix of a cell expression profile before the propagation}
\item{gf_prop}{numeric matrix of a cell profile after the first step of the propagation applied with only the gene-genic fragment component of the CIN}
\item{ann_net_b}{data.frame, for each row presents the gene identifier, the chromosome in which the gene is, the starting and ending position in the sequence.}
\item{frag_pattern}{string, initial character of the fragments name (e.g. "F" or "Frag")}
\item{ff_net}{Edge list of the chromatin interaction network such that first and second column are "FragX" fragments}
\item{ff_prop}{numeric matrix of a cell profile after the second step of the propagation applied with the fragment-fragment component of the CIN}
}
\value{
igraph object
}
\description{
Given the input and output of the two step network based propagation, it assembles an igraph object of the CIN with all
the information included in order to be visualized or analysed
}
|
\name{strCompare}
\alias{strCompare}
\title{strCompare}
\usage{
strCompare(ctFile1,ctFile2,randomTime = 1000)
}
\arguments{
\item{ctFile1}{A RNA secondary structure file containing structure information}
\item{ctFile2}{A RNA secondary structure file containing structure information}
\item{randomTime}{random times of permutation test to get P value}
}
\description{
return similarity score of two RNA secondary structures
}
\value{
Returns a numerical value which represent the similarity of the two RNA secondary structures.The larger the value, the more similar the two RNA structures are.The maximum value is 10, representing the two RNA secondary structures exactly the same,and 0 is the minmum value.
}
\examples{
###
data(DataCluster1)
data(DataCluster2)
#####RNAstrPlot(DataCluster1)
#####RNAstrPlot(DataCluster2)
strCompare(DataCluster1,DataCluster2,randomTime = 10)
}
| /man/strCompare.rd | no_license | ZhengHeWei/RNAsmc | R | false | false | 903 | rd | \name{strCompare}
\alias{strCompare}
\title{strCompare}
\usage{
strCompare(ctFile1,ctFile2,randomTime = 1000)
}
\arguments{
\item{ctFile1}{A RNA secondary structure file containing structure information}
\item{ctFile2}{A RNA secondary structure file containing structure information}
\item{randomTime}{random times of permutation test to get P value}
}
\description{
return similarity score of two RNA secondary structures
}
\value{
Returns a numerical value which represent the similarity of the two RNA secondary structures.The larger the value, the more similar the two RNA structures are.The maximum value is 10, representing the two RNA secondary structures exactly the same,and 0 is the minmum value.
}
\examples{
###
data(DataCluster1)
data(DataCluster2)
#####RNAstrPlot(DataCluster1)
#####RNAstrPlot(DataCluster2)
strCompare(DataCluster1,DataCluster2,randomTime = 10)
}
|
### For testing, I need to clean the CVTS test locations for compatibility
library(dplyr)
test_data <- readRDS('../test/cvts_test.rds')
test_data$config_code <- test_data %>%
transmute(config_code = plyr::mapvalues(REGION, c("Eastern Oregon",
"California Mixed Conifer Group",
"Western Oregon",
"Western Washington",
"Idaho and western Montana",
"Southeast Alaska",
"Eastern Washington",
"Northern and Eastern Utah",
"Plains States",
"Southern and western Utah",
"Western Wyoming and Western Colorado",
"Northern New Mexico and Arizona",
"Southern New Mexico and Arizona"),
c("OR_E",
"CA_MC",
"OR_W",
"WA_W",
"ID_MTW",
"AK_SECN",
"WA_E",
"UT_NE",
"NCCS",
"UT_SW",
"CO_W_WY_W",
"AZ_N_NM_N",
"AZ_S_NM_S")))
## Save and check
head(test_data)
names(test_data)
test_data$config_code
test_data$cyl <- NULL
saveRDS(test_data, '../test/csvts_test.rds')
test_2 <- readRDS('../test/csvts_test.rds')
head(test_2)
| /bin/clean_cvts_test.R | no_license | parvezrana/forvol | R | false | false | 1,904 | r | ### For testing, I need to clean the CVTS test locations for compatibility
library(dplyr)
test_data <- readRDS('../test/cvts_test.rds')
test_data$config_code <- test_data %>%
transmute(config_code = plyr::mapvalues(REGION, c("Eastern Oregon",
"California Mixed Conifer Group",
"Western Oregon",
"Western Washington",
"Idaho and western Montana",
"Southeast Alaska",
"Eastern Washington",
"Northern and Eastern Utah",
"Plains States",
"Southern and western Utah",
"Western Wyoming and Western Colorado",
"Northern New Mexico and Arizona",
"Southern New Mexico and Arizona"),
c("OR_E",
"CA_MC",
"OR_W",
"WA_W",
"ID_MTW",
"AK_SECN",
"WA_E",
"UT_NE",
"NCCS",
"UT_SW",
"CO_W_WY_W",
"AZ_N_NM_N",
"AZ_S_NM_S")))
## Save and check
head(test_data)
names(test_data)
test_data$config_code
test_data$cyl <- NULL
saveRDS(test_data, '../test/csvts_test.rds')
test_2 <- readRDS('../test/csvts_test.rds')
head(test_2)
|
library(shiny)
#library(plotly)
# Define UI for for soccer winning percentage simulate app
ui <- fluidPage(
# App title ----
titlePanel("soccer simulateR"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: A team's score ----
numericInput(inputId = "score_A",
label = "A team's score:",
value = 0),
# Input: B team's score ----
numericInput(inputId = "score_B",
label = "B team's score:",
value = 0),
# br() element to introduce extra vertical spacing ----
#br(),
# Input: Slider for the number of remaining time ----
sliderInput("time",
"remaining time:",
value = 90,
min = 1,
max = 90),
# Input: Slider for the number of simulation----
numericInput(inputId = "n",
label = "Number of simulation:",
value = 100),
# Input: A team's expected score per 1 game ----
numericInput(inputId = "expected_score_A",
label = "A team's expected score per 1 game:",
value = 1),
# Input: B team's expected score per 1 game ----
numericInput(inputId = "expected_score_B",
label = "B team's expected score per 1 game:",
value = 1)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Tabset----
tabsetPanel(type = "tabs",
tabPanel("winning percentage", plotOutput("winning_percentage")),
tabPanel("distribution of score", plotOutput("distribution_score")),
tabPanel("percentage transition", plotOutput("percentage_transition"))
)
)
)
) | /Simulation/soccersimulateR/ui.R | no_license | flaty4218/sport_analysis | R | false | false | 1,940 | r | library(shiny)
#library(plotly)
# Define UI for for soccer winning percentage simulate app
ui <- fluidPage(
# App title ----
titlePanel("soccer simulateR"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: A team's score ----
numericInput(inputId = "score_A",
label = "A team's score:",
value = 0),
# Input: B team's score ----
numericInput(inputId = "score_B",
label = "B team's score:",
value = 0),
# br() element to introduce extra vertical spacing ----
#br(),
# Input: Slider for the number of remaining time ----
sliderInput("time",
"remaining time:",
value = 90,
min = 1,
max = 90),
# Input: Slider for the number of simulation----
numericInput(inputId = "n",
label = "Number of simulation:",
value = 100),
# Input: A team's expected score per 1 game ----
numericInput(inputId = "expected_score_A",
label = "A team's expected score per 1 game:",
value = 1),
# Input: B team's expected score per 1 game ----
numericInput(inputId = "expected_score_B",
label = "B team's expected score per 1 game:",
value = 1)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Tabset----
tabsetPanel(type = "tabs",
tabPanel("winning percentage", plotOutput("winning_percentage")),
tabPanel("distribution of score", plotOutput("distribution_score")),
tabPanel("percentage transition", plotOutput("percentage_transition"))
)
)
)
) |
publicArea <- read.csv("광주광역시_공공시설개방정보_20150918.csv")
install.packages("ggmap")
library(ggmap)
imap <- get_map("kwangju", zoom = 12, maptype = "roadmap")#maptype : roadmap, hybrid, satellite, terrain
ggmap(imap)
ggmap(imap) +
geom_point(data = publicArea, aes(x=경도, y=위도), size = 2, color = "red", alpha = 0.3) +
geom_text(data = publicArea, aes(x=경도, y=위도+0.005), label = publicArea$개방시설명, size = 2)
| /20171101_ggplot/ggmap_publicData.R | no_license | coldMater/smhrd_R_Basic_Tutorials | R | false | false | 461 | r | publicArea <- read.csv("광주광역시_공공시설개방정보_20150918.csv")
install.packages("ggmap")
library(ggmap)
imap <- get_map("kwangju", zoom = 12, maptype = "roadmap")#maptype : roadmap, hybrid, satellite, terrain
ggmap(imap)
ggmap(imap) +
geom_point(data = publicArea, aes(x=경도, y=위도), size = 2, color = "red", alpha = 0.3) +
geom_text(data = publicArea, aes(x=경도, y=위도+0.005), label = publicArea$개방시설명, size = 2)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/coxrt_functions.R
\name{coxph.RT}
\alias{coxph.RT}
\title{Fits Cox Regression Model Using Right Truncated Data}
\usage{
coxph.RT(formula, right, data, bs = FALSE, nbs.rep = 500,
conf.int = 0.95)
}
\arguments{
\item{formula}{a formula object, with the response on the left of a ~ operator, and covariates on the right.
The response is a target lifetime variable.}
\item{right}{a right truncation variable.}
\item{data}{a data frame that includes the variables used in both sides of \code{formula}
and in \code{right}.
The observations with missing values in one of the variables are dropped.}
\item{bs}{logical value: if \code{TRUE}, the bootstrap esimator of standard error,
confidence interval,
and confidence upper and lower limits for one-sided confidence intervals
based on the bootstrap distribution are calculated. The default value is \code{FALSE}.}
\item{nbs.rep}{number of bootstrap replications. The default number is 200.}
\item{conf.int}{The confidence level for confidence intervals and hypotheses tests.
The default level is 0.95.}
}
\value{
A list with components:
\tabular{llr}{
\code{coef} \tab an estimate of regression coefficients \tab \cr
\code{var} \tab covariance matrix of estimates of regression coefficients based on the analytic formula\tab \cr
\code{n} \tab the number of observations used to fit the model \tab \cr
\code{summary} \tab a data frame with a summary of fit: \tab \cr}
\itemize{
\item{\code{coef}} a vector of coefficients
\item{\code{exp.coef}} exponent of regression coefficients (=hazard ratio)
\item{\code{SE}} asymptotic standard error estimate based on the analytic formula derived in Vakulenko-Lagun et al. (2018)
\item{\code{CI.L}} lower confidence limit for two-sided hypothesis \ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>} = 0}{\eqn{\beta_i=0}}
\item{\code{CI.U}} upper confidence limit for two-sided hypothesis \ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>} = 0}{\eqn{\beta_i=0}}
\item{\code{pvalue}} p-value from a Wald test for a two-sided hypothesis
\ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>} = 0}{\eqn{\beta_i=0}}
\item{\code{pvalue.H1.b.gr0}} p-value from the Wald test for a one-sided
partial hypothesis \ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>}\eqn{\le 0}}{\eqn{\beta_i\le 0}}
based on the analytical asymptotic standard error estimate
\item{\code{pvalue.H1.b.le0}} p-value from the Wald test a for one-sided
partial hypothesis \ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>}\eqn{\ge 0}}{\eqn{\beta_i\ge 0}}
based on the analytical asymptotic standard error estimate }
\tabular{ll}{
\code{bs } \tab if the input argument \code{bs} was TRUE, then an output list also includes an element \code{bs} with\cr
\tab statistics from the bootstrap distribution of estimated
coefficients:\cr}
\itemize{
\item{\code{num.bs.rep}}
{number of bootsrap replications used to obtain the sample distribution}
\item{\code{var}} {estimated variance}
\item{\code{summary}} {a data frame with a summary
of bootstrap distribution that includes:
\code{SE}, a bootstrap estimated standard error;
\code{CI.L}, a quantile estimated lower confidence limit
for two-sided hypothesis \ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>} = 0}{\eqn{\beta_i=0}};
\code{CI.U}, a quantile estimated upper confidence limit for two-sided hypothesis
\ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>} = 0}{\eqn{\beta_i=0}};
\code{CI.L.H1.b.gr0},
a quantile estimated the limit for one-sided hypothesis
\ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>}\eqn{\le 0}}{\eqn{\beta_i\le 0}};
\code{CI.U.H1.b.le0}, a
quantile estimated the limit for one-sided hypothesis
\ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>}\eqn{\ge 0}}{\eqn{\beta_i\ge 0}}.}
}
}
\description{
Estimates covariate effects in a Cox proportional hazard regression
from right-truncated survival data assuming positivity, that is
\code{P(lifetime>max(right) | Z=0)=0}.
}
\details{
When positivity does not hold, the estimator of regression coefficients
will be biased.
But if all the covariates are independent in the population,
the Wald test performed by this function is still valid and can be used
for testing partial hypotheses about regression coefficients
even in the absence of positivity. If the covariates are not independent and
positivity does not hold, the partial tests cannot guarantee the correct
level of type I error.
}
\examples{
# loading AIDS data set
library(gss)
data(aids)
all <- data.frame(age=aids$age, ageg=as.numeric(aids$age<=59), T=aids$incu, R=aids$infe, hiv.mon =102-aids$infe)
all$T[all$T==0] <- 0.5 # as in Kalbfeisch and Lawless (1989)
s <- all[all$hiv.mon>60,] # select those who were infected in 1983 or later
# analysis assuming positivity
# we request bootstrap SE estimate as well:
sol <- coxph.RT(T~ageg, right=R, data=s, bs=FALSE)
sol
sol$summary # print the summary of fit based on the analytic Asymptotic Standard Error estimate
}
\seealso{
\code{\link{coxph.RT.a0}}, \code{\link{coxrt}}, \code{\link[survival]{coxph}}
}
| /man/coxph.RT.Rd | no_license | Bella2001/coxrt | R | false | true | 5,455 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/coxrt_functions.R
\name{coxph.RT}
\alias{coxph.RT}
\title{Fits Cox Regression Model Using Right Truncated Data}
\usage{
coxph.RT(formula, right, data, bs = FALSE, nbs.rep = 500,
conf.int = 0.95)
}
\arguments{
\item{formula}{a formula object, with the response on the left of a ~ operator, and covariates on the right.
The response is a target lifetime variable.}
\item{right}{a right truncation variable.}
\item{data}{a data frame that includes the variables used in both sides of \code{formula}
and in \code{right}.
The observations with missing values in one of the variables are dropped.}
\item{bs}{logical value: if \code{TRUE}, the bootstrap esimator of standard error,
confidence interval,
and confidence upper and lower limits for one-sided confidence intervals
based on the bootstrap distribution are calculated. The default value is \code{FALSE}.}
\item{nbs.rep}{number of bootstrap replications. The default number is 200.}
\item{conf.int}{The confidence level for confidence intervals and hypotheses tests.
The default level is 0.95.}
}
\value{
A list with components:
\tabular{llr}{
\code{coef} \tab an estimate of regression coefficients \tab \cr
\code{var} \tab covariance matrix of estimates of regression coefficients based on the analytic formula\tab \cr
\code{n} \tab the number of observations used to fit the model \tab \cr
\code{summary} \tab a data frame with a summary of fit: \tab \cr}
\itemize{
\item{\code{coef}} a vector of coefficients
\item{\code{exp.coef}} exponent of regression coefficients (=hazard ratio)
\item{\code{SE}} asymptotic standard error estimate based on the analytic formula derived in Vakulenko-Lagun et al. (2018)
\item{\code{CI.L}} lower confidence limit for two-sided hypothesis \ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>} = 0}{\eqn{\beta_i=0}}
\item{\code{CI.U}} upper confidence limit for two-sided hypothesis \ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>} = 0}{\eqn{\beta_i=0}}
\item{\code{pvalue}} p-value from a Wald test for a two-sided hypothesis
\ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>} = 0}{\eqn{\beta_i=0}}
\item{\code{pvalue.H1.b.gr0}} p-value from the Wald test for a one-sided
partial hypothesis \ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>}\eqn{\le 0}}{\eqn{\beta_i\le 0}}
based on the analytical asymptotic standard error estimate
\item{\code{pvalue.H1.b.le0}} p-value from the Wald test a for one-sided
partial hypothesis \ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>}\eqn{\ge 0}}{\eqn{\beta_i\ge 0}}
based on the analytical asymptotic standard error estimate }
\tabular{ll}{
\code{bs } \tab if the input argument \code{bs} was TRUE, then an output list also includes an element \code{bs} with\cr
\tab statistics from the bootstrap distribution of estimated
coefficients:\cr}
\itemize{
\item{\code{num.bs.rep}}
{number of bootsrap replications used to obtain the sample distribution}
\item{\code{var}} {estimated variance}
\item{\code{summary}} {a data frame with a summary
of bootstrap distribution that includes:
\code{SE}, a bootstrap estimated standard error;
\code{CI.L}, a quantile estimated lower confidence limit
for two-sided hypothesis \ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>} = 0}{\eqn{\beta_i=0}};
\code{CI.U}, a quantile estimated upper confidence limit for two-sided hypothesis
\ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>} = 0}{\eqn{\beta_i=0}};
\code{CI.L.H1.b.gr0},
a quantile estimated the limit for one-sided hypothesis
\ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>}\eqn{\le 0}}{\eqn{\beta_i\le 0}};
\code{CI.U.H1.b.le0}, a
quantile estimated the limit for one-sided hypothesis
\ifelse{html}{\out{H<sub>0</sub>:}}{\eqn{H_0}:} \ifelse{html}{\eqn{\beta}\out{<sub>i</sub>}\eqn{\ge 0}}{\eqn{\beta_i\ge 0}}.}
}
}
\description{
Estimates covariate effects in a Cox proportional hazard regression
from right-truncated survival data assuming positivity, that is
\code{P(lifetime>max(right) | Z=0)=0}.
}
\details{
When positivity does not hold, the estimator of regression coefficients
will be biased.
But if all the covariates are independent in the population,
the Wald test performed by this function is still valid and can be used
for testing partial hypotheses about regression coefficients
even in the absence of positivity. If the covariates are not independent and
positivity does not hold, the partial tests cannot guarantee the correct
level of type I error.
}
\examples{
# loading AIDS data set
library(gss)
data(aids)
all <- data.frame(age=aids$age, ageg=as.numeric(aids$age<=59), T=aids$incu, R=aids$infe, hiv.mon =102-aids$infe)
all$T[all$T==0] <- 0.5 # as in Kalbfeisch and Lawless (1989)
s <- all[all$hiv.mon>60,] # select those who were infected in 1983 or later
# analysis assuming positivity
# we request bootstrap SE estimate as well:
sol <- coxph.RT(T~ageg, right=R, data=s, bs=FALSE)
sol
sol$summary # print the summary of fit based on the analytic Asymptotic Standard Error estimate
}
\seealso{
\code{\link{coxph.RT.a0}}, \code{\link{coxrt}}, \code{\link[survival]{coxph}}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/unpublish.R
\name{remove_publish_target}
\alias{remove_publish_target}
\title{Helper to unpublish. similar to remake:::remake_remove_target, but without file deletion}
\usage{
remove_publish_target(obj, target_name)
}
\arguments{
\item{obj}{argument as in remake:::remake_remove_target}
\item{target_name}{argument as in remake:::remake_remove_target}
}
\description{
Helper to unpublish. similar to remake:::remake_remove_target, but without file deletion
}
\keyword{internal}
| /man/remove_publish_target.Rd | permissive | USGS-VIZLAB/vizlab | R | false | true | 557 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/unpublish.R
\name{remove_publish_target}
\alias{remove_publish_target}
\title{Helper to unpublish. similar to remake:::remake_remove_target, but without file deletion}
\usage{
remove_publish_target(obj, target_name)
}
\arguments{
\item{obj}{argument as in remake:::remake_remove_target}
\item{target_name}{argument as in remake:::remake_remove_target}
}
\description{
Helper to unpublish. similar to remake:::remake_remove_target, but without file deletion
}
\keyword{internal}
|
rm(list = ls())
#setwd("~/Classes/Fall/DataAnalytics/FinalProject/")
library(dplyr)
#Load data set
words <- read.csv("./data/words.csv")
#Remove uncommon words
words.cleaned <- words %>% select(Artist, User, HEARD_OF, Aggressive, Edgy, Current, Stylish,
Cheap, Calm, Outgoing, Inspiring, Beautiful, Fun,
Authentic, Credible, Cool, Catchy, Sensitive,
Superficial, Passionate, Timeless, Original,
Talented, Distinctive, Approachable, Trendsetter,
Noisy, Upbeat, Depressing, Energetic, Sexy,
Fake, Cheesy, Unoriginal, Dated, Unapproachable,
Classic, Playful, Arrogant, Warm, Serious,
Good.lyrics, Unattractive, Confident, Youthful,
Thoughtful)
#Removing blank HEARD_OF
words.cleaned <- filter(words.cleaned, HEARD_OF != "")
#Converting HEARD_OF to two factors
heardof <- words.cleaned$HEARD_OF
heardof <- as.character(heardof)
heardof[heardof != "Never heard of"] <- "Heard of"
words.cleaned$HEARD_OF <- heardof
words.cleaned$HEARD_OF <- as.factor(words.cleaned$HEARD_OF)
#Load train set
train <- read.csv("./data/train.csv")
#Create mean rating for artists
train.group <- group_by(train, Artist, User)
trainSumm <- summarise(train.group, meanRating = mean(Rating))
#merge with word set
master <- inner_join(trainSumm, words.cleaned)
#Check for NAs
apply(master, 2, function(x) table(is.na(x)))
#Clean master data
master.cleaned <- select(master, -Aggressive, -Cheap, -Calm, -Outgoing, -Inspiring,
-Catchy, -Sensitive, -Superficial, -Upbeat, -Depressing,
-Fake, -Cheesy, -Unoriginal, -Dated, -Unapproachable,
-Classic, -Playful, -Arrogant, -Serious, -Good.lyrics,
-Unattractive, -Confident, -Youthful, -Noisy)
#write.csv(master.cleaned, "master.csv")
#Create some summaries and initial models
master.cleaned2 <- select(master.cleaned, -User, -HEARD_OF)
master.group <- group_by(master.cleaned2, Artist)
master.Summ <- summarise_each(master.group, funs(mean))
master.Summ <- master.Summ %>% arrange(desc(meanRating))
fit <- lm(meanRating ~ . - Artist, data = master.Summ)
x <- cor(master.Summ[,3:21])
| /datacleaning.R | no_license | chloelemon/dataAnalyticsFinal | R | false | false | 2,427 | r | rm(list = ls())
#setwd("~/Classes/Fall/DataAnalytics/FinalProject/")
library(dplyr)
#Load data set
words <- read.csv("./data/words.csv")
#Remove uncommon words
words.cleaned <- words %>% select(Artist, User, HEARD_OF, Aggressive, Edgy, Current, Stylish,
Cheap, Calm, Outgoing, Inspiring, Beautiful, Fun,
Authentic, Credible, Cool, Catchy, Sensitive,
Superficial, Passionate, Timeless, Original,
Talented, Distinctive, Approachable, Trendsetter,
Noisy, Upbeat, Depressing, Energetic, Sexy,
Fake, Cheesy, Unoriginal, Dated, Unapproachable,
Classic, Playful, Arrogant, Warm, Serious,
Good.lyrics, Unattractive, Confident, Youthful,
Thoughtful)
#Removing blank HEARD_OF
words.cleaned <- filter(words.cleaned, HEARD_OF != "")
#Converting HEARD_OF to two factors
heardof <- words.cleaned$HEARD_OF
heardof <- as.character(heardof)
heardof[heardof != "Never heard of"] <- "Heard of"
words.cleaned$HEARD_OF <- heardof
words.cleaned$HEARD_OF <- as.factor(words.cleaned$HEARD_OF)
#Load train set
train <- read.csv("./data/train.csv")
#Create mean rating for artists
train.group <- group_by(train, Artist, User)
trainSumm <- summarise(train.group, meanRating = mean(Rating))
#merge with word set
master <- inner_join(trainSumm, words.cleaned)
#Check for NAs
apply(master, 2, function(x) table(is.na(x)))
#Clean master data
master.cleaned <- select(master, -Aggressive, -Cheap, -Calm, -Outgoing, -Inspiring,
-Catchy, -Sensitive, -Superficial, -Upbeat, -Depressing,
-Fake, -Cheesy, -Unoriginal, -Dated, -Unapproachable,
-Classic, -Playful, -Arrogant, -Serious, -Good.lyrics,
-Unattractive, -Confident, -Youthful, -Noisy)
#write.csv(master.cleaned, "master.csv")
#Create some summaries and initial models
master.cleaned2 <- select(master.cleaned, -User, -HEARD_OF)
master.group <- group_by(master.cleaned2, Artist)
master.Summ <- summarise_each(master.group, funs(mean))
master.Summ <- master.Summ %>% arrange(desc(meanRating))
fit <- lm(meanRating ~ . - Artist, data = master.Summ)
x <- cor(master.Summ[,3:21])
|
dataFile <- "~/Ed/R directory/data/household_power_consumption.txt"
data <- read.table(dataFile, header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".")
subSetData <- data[data$Date %in% c("1/2/2007","2/2/2007") ,]
#str(subSetData)
globalActivePower <- as.numeric(subSetData$Global_active_power)
png("plot1.png", width=480, height=480)
hist(globalActivePower, col="red", main="Global Active Power", xlab="Global Active Power (kilowatts)")
dev.off()
| /plot1.R | no_license | adlihs/ExData_Plotting1 | R | false | false | 458 | r | dataFile <- "~/Ed/R directory/data/household_power_consumption.txt"
data <- read.table(dataFile, header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".")
subSetData <- data[data$Date %in% c("1/2/2007","2/2/2007") ,]
#str(subSetData)
globalActivePower <- as.numeric(subSetData$Global_active_power)
png("plot1.png", width=480, height=480)
hist(globalActivePower, col="red", main="Global Active Power", xlab="Global Active Power (kilowatts)")
dev.off()
|
#********************************************************************************
#
# Univariate Graphics
#
#********************************************************************************
#************************************
# Reading in data
#************************************
# Set working directory
# For example, an iOS user
#setwd("/Users/me/data/TrainAccidents")
# or a windows user
setwd("D:\\R")
mydatapath14 <- "R_data\\RailAccidents14.txt"
mysourcepathAI <- "R_Code\\AccidentInput.R"
mylistpath <- "D:\\R\\R_data"
#***********************************************
# Read in the accident files one at at time
acts14 <- read.table(mydatapath14,sep = ",",header = TRUE)
# Since the files are really csv you can use
acts14 <- read.csv(mydatapath14)
#**************************************************
# To get a summary of all of the variables use
summary(acts14)
# To get a summary of a subset of the variables (e.g., "ACCDMG", "TOTKLD", "CARS" )
# you can use
summary(acts14$ACCDMG,acts14$TOTKLD,acts14$CARS)
# To get individual statistics (e.g. mean, var) you can use
mean(acts14$ACCDMG)
var(acts14$ACCDMG, na.rm = FALSE, use = "complete")
mean(acts14$TOTKLD)
var(acts14$TOTKLD, na.rm = FALSE, use = "complete")
mean(acts14$CARS)
var(acts14$CARS)
# You can round your answer using the round() function
#**************************************************
# You will need to read in all 14 years of the data
# You will put the data into a data structure called a list
# To do this you will use code I have written, AccidentInput.R
# Put that file in your working directory and then source it:
source(mysourcepathAI)
# Now use it to read in all the data. You must have ALL and ONLY the rail accident data
# files in one directory. Call that directory and its path, path.
# You can give your data a name
# In my examples below I use acts as the name for data sets
# Then use the command
acts <- file.inputl(mylistpath)
# E.G.
#acts <- file.inputl("C:\\Users\\james Bennett\\Desktop\\R_Code\\AccidentInput.R")
# path is the specification of the path to your file.
# Now acts[[1]] is the data set from year 2001,
# acts[[2]] is the data set from year 2002, etc.
# Before we put all the data into one data frame
# we must clean the data
##################################################
#
# Data Cleaning
#
##################################################
#************************************************
# Variable names
matrix(names(acts[[1]]))
matrix(names(acts[[8]]))
# Notice that the number of columns changes from year to year - 146 vs 140
ncol(acts[[1]])
ncol(acts[[8]])
# Get a common set the variables
comvar <- intersect(colnames(acts[[1]]), colnames(acts[[8]]))
# Now combine the data frames for all 12 years
# Use combine.data()
totacts <- combine.data(acts, comvar)
# How many accidents? 46883
dim(totacts)
# View of accident damage - Most of them are minor accideint
par(mfcol=c(1,1), oma=c(1,0,0,0), mar=c(1,1,1,0), tcl=-0.1, mgp=c(2,0,0))
boxplot(totacts$ACCDMG,range = 1.5, main = "Boxplot of accident damage")
hist(totacts$ACCDMG)
#*************************************************
# Accident Reports
# Look at the most costly accident in the data set
which(totacts$ACCDMG == max(totacts$ACCDMG))
# Check out the narratives for this extreme accident
totacts[42881,]
# How do we find duplicates?
# Are there other duplicates?
duplicated(totacts[1:100, c("YEAR", "MONTH", "DAY", "TIMEHR", "TIMEMIN")])
# why not use latitude and longitude? - Because date and time does the trick - what are the chances we had had accidents at the same time?!
# why not use INCDTNO? - it is not unique to an incident - We need a primary key - Think DB
totacts[totacts$INCDTNO == "1", 1:10]
# Remove duplicates
totacts <- totacts[!duplicated(totacts[, c("YEAR", "MONTH", "DAY", "TIMEHR", "TIMEMIN")]),]
#*******************************************
# What is the second most extreme accident?
which(totacts$ACCDMG > 1.5e7)
# what should we do? - We remove it - This was a result of a terrorist attack - cannot be expected to controll this
totacts <- totacts[-1223,]
#********************************************
# Missing data
# Do a summary of totacts
names(summary(totacts$Latitude))
# Are we missing values for any variables?
# How many?
nafind <- function(x){sum(is.na(x))}
apply(totacts,2, "nafind")
# Do we need all the variables?
matrix(names(totacts))
# Remove unnecessary variables, then get a summary
nacount <- apply(totacts,2, "nafind")
varWna <- which(nacount > 0)
# Keep TYPEQ, we'll use it. The others we don't need.
which(colnames(totacts)[varWna] == "TYPEQ")
varWna <- varWna[-which(colnames(totacts)[varWna]== "TYPEQ")]
totacts <- totacts[, -varWna]
# Save your data frame
# check you working directory and change it if necessary
getwd()
write.csv(totacts, file ="D:\\R\\R_Output\\totactsClean.csv", row.names = F)
#***********************************
#
# Summary of accidents
#
#***********************************
# Get a summary of the cleaned data set
# It does not seem to address the expense associated with Bodily Injuries or Deaths or litigation from deaths or injuries
summary(totacts)
# How many accidents?
dim(totacts)
# Total cost of all accidents
sum(totacts$ACCDMG)
#summary(totacts$CAUSE)
# Average annual cost of accidents
sum(totacts$ACCDMG)/14
# first yearly costs (sums)
dmgyrsum <- tapply(totacts$ACCDMG, totacts$YEAR, sum)
##what about the cost for injuries and deaths
## for instance
which(totacts$TOTKLD == max(totacts$TOTKLD))
pd_dmg <- sum(totacts$EQPDMG[15012],totacts$TRKDMG[15012])
discrepancy <- totacts$ACCDMG[15012] - pd_dmg
discrepancy
## of 592800 - but there were 9 deaths and 292 injuries ??
#then average
mean(dmgyrsum)
# Total number killed
sum(totacts$TOTKLD)
# Largest number killed in an accident - But the data shows that
max(totacts$TOTKLD)
# Total number injured
sum(totacts$TOTINJ)
# Largest number injured in an accident
max(totacts$TOTINJ)
# What is the average number of injuries per year?
round(sum(totacts$TOTINJ)/14)
# types of variables
str(totacts)
#**************************************************
#
# Time series of Accidents
#
#**************************************************
# Yearly no. of accidents
plot(1:max(totacts$YEAR), tapply(totacts$ACCDMG, totacts$YEAR, length), type = "l", col = "black", xlab = "Year", ylab = "Frequency", main = "Number of Accidents per Year", lwd =2)
# Yearly total cost of accidents
plot(1:max(totacts$YEAR), tapply(totacts$ACCDMG, totacts$YEAR, sum), type = "l", col = "black", xlab = "Year", ylab = "Cost ($)", main = "Total Damage per Year", lwd =2)
# Yearly maximum cost of accidents
plot(1:max(totacts$YEAR), tapply(totacts$ACCDMG, totacts$YEAR, max), type = "l", col = "black", xlab = "Year", ylab = "Cost ($)", main = "Total Damage per Year", lwd =2)
# Putting total and maximum together using symbols
symbols(2001:2014, tapply(totacts$ACCDMG, totacts$YEAR, sum), circles=tapply(totacts$ACCDMG, totacts$YEAR, max),inches=0.35, fg="white", bg="red", xlab="Year", ylab="Cost ($)", main = "Total Accident Damage")
lines(2001:2014, tapply(totacts$ACCDMG, totacts$YEAR, sum))
# Repeat this for total killed and total injured and the sum of them.
symbols(2001:2014, tapply(totacts$TOTKLD, totacts$YEAR, sum), circles = tapply(totacts$TOTKLD, totacts$YEAR, max), inches = 0.35, fg ="yellow", bg ="red", xlab = "Year", ylab = "People Killed", main = "Total Killed")
lines(2001:2014, tapply(totacts$TOTKLD, totacts$YEAR, sum))
symbols(2001:2014, tapply(totacts$TOTINJ, totacts$YEAR, sum), circles = tapply(totacts$TOTINJ, totacts$YEAR, max), inches = 0.35, fg ="black", bg ="red", xlab = "Year", ylab = "People Injured", main = "Total Injured")
lines(2001:2014, tapply(totacts$TOTINJ, totacts$YEAR, sum))
#***********************************
#
# histograms of ACCDMG and TEMP
#
#***********************************
# These examples are for 2011
hist(acts[[11]]$ACCDMG) # for 2011
hist(acts[[11]]$ACCDMG, main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
# Different bin widths
par(mfrow = c(2,2))
hist(totacts$TEMP, breaks = "scott", main = "Accident Temperatures (Scott)", xlab = "Temp (F)", col = "steelblue")
hist(totacts$TEMP, breaks = "fd", main = "Accident Temperatures (FD)", xlab = "Temp (F)", col = "steelblue")
hist(totacts$TEMP, main = "Accident Temperatures (Sturges)", xlab = "Temp (F)", col = "steelblue")
hist(totacts$TEMP, breaks = 100, main = "Accident Temperatures (100)", xlab = "Temp (F)", col = "steelblue")
par(mfrow = c(1,1))
# Different bin widths
hist(acts[[11]]$ACCDMG, breaks = "scott", main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[11]]$ACCDMG, breaks = "fd", main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[11]]$ACCDMG, breaks = 20, main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[11]]$ACCDMG, breaks = 100, main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
# other years
par(mfrow = c(2,2))
hist(acts[[1]]$ACCDMG, main = "Total Accident Damage in 2001", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[4]]$ACCDMG, main = "Total Accident Damage in 2004", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[8]]$ACCDMG, main = "Total Accident Damage in 2008", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[11]]$ACCDMG, main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
par(mfrow = c(1,1))
#*********************************************************************
#
# Box Plots of Metrics
# and Extreme Accidents
#
#*********************************************************************
#*****************************
# ACCDMG
boxplot(totacts$ACCDMG, main = "Xtreme Accident damage")
boxplot(totacts$TOTKLD, main = "Deaths in Extreme incident")
# Plot only the extreme points
# (extreme defined by the box plot rule)
# Get the values in the box plot
dmgbox <- boxplot(totacts$ACCDMG)
dmgbox2 <- boxplot(totacts$TOTKLD)
# How many extreme damage accidents?
length(dmgbox$out)
##extreme accident dmg 4862
length(dmgbox2$out)
dmgbox$stats
##extreme accident relative to deaths 479 (this is not commom)
# What proportion of accidents are extreme? (round to 2 digits) - 13%
round(length(dmgbox$out)/length(totacts$ACCDMG),2)
# What is the proportion of costs for extreme damage accidents? (round to 2 digits)
round(sum(dmgbox$out)/sum(totacts$ACCDMG),2) ##13% causes 74% of the damages - Insanity!!
# Create a data frame with just the extreme ACCDMG accidents
round(length(dmgbox2$out)/length(totacts$TOTKLD),2)
##.01 are extreme - deaths are an wear event
round(sum(dmgbox2$out)/sum(totacts$TOTKLD),2)
##all deaths are were events
xdmg <- totacts[totacts$ACCDMG > dmgbox$stats[5],]
dim(xdmg)
###4862 are were
# Look at the boxplots and histograms of these extreme accidents
boxplot(xdmg$ACCDMG, col = "steelblue", main = "Accidents with Extreme Damage", ylab = "Cost ($)")
plot(1:14, tapply(xdmg$ACCDMG, xdmg$YEAR, sum), type = "l", xlab = "Year", ylab = "Total Damage ($)", main = "Total Extreme Accident Damage per Year")
# also plot number of accidents per year.
plot(1:14, tapply(xdmg$ACCDMG, xdmg$YEAR, length), type = "l", xlab = "Year", ylab = "No. of Accidents", main = "Number of Extreme Accidents per Year")
# Frequency of accident types
barplot(table(xdmg$TYPE)) #compare with the totacts plot
##Lots of Derailments - wonder is speeding has to do with this - Type = 1
# Repeat for TOTKLD and TOTINJ
# Create a variable called Casualty = TOTKLD + TOTINJ
max(totacts$TOTINJ) ##1000 in a single accident
max(totacts$TOTKLD) ##9 in a single maccident
Casualidad = totacts$TOTKLD + totacts$TOTINJ
max(Casualidad) ###1001
plot(1:max(totacts$YEAR), tapply(totacts$TOTKLD, totacts$YEAR, max), type = "l", col = "black", xlab = "Year", ylab = "Frequency", main = "Number of KILLED", lwd =2)
plot(1:max(totacts$YEAR), tapply(totacts$TOTINJ, totacts$YEAR, max), type = "l", col = "black", xlab = "Year", ylab = "Frequency", main = "Number of Injured", lwd =2)
plot(1:max(totacts$YEAR), tapply(Casualidad, totacts$YEAR, max), type = "l", col = "blue", xlab = "Year", ylab = "Frequency", main = "Combined Casualties", lwd =2)
| /S1.1Graphics (1).R | no_license | James3B/Stats-for-Engineers | R | false | false | 12,848 | r |
#********************************************************************************
#
# Univariate Graphics
#
#********************************************************************************
#************************************
# Reading in data
#************************************
# Set working directory
# For example, an iOS user
#setwd("/Users/me/data/TrainAccidents")
# or a windows user
setwd("D:\\R")
mydatapath14 <- "R_data\\RailAccidents14.txt"
mysourcepathAI <- "R_Code\\AccidentInput.R"
mylistpath <- "D:\\R\\R_data"
#***********************************************
# Read in the accident files one at at time
acts14 <- read.table(mydatapath14,sep = ",",header = TRUE)
# Since the files are really csv you can use
acts14 <- read.csv(mydatapath14)
#**************************************************
# To get a summary of all of the variables use
summary(acts14)
# To get a summary of a subset of the variables (e.g., "ACCDMG", "TOTKLD", "CARS" )
# you can use
summary(acts14$ACCDMG,acts14$TOTKLD,acts14$CARS)
# To get individual statistics (e.g. mean, var) you can use
mean(acts14$ACCDMG)
var(acts14$ACCDMG, na.rm = FALSE, use = "complete")
mean(acts14$TOTKLD)
var(acts14$TOTKLD, na.rm = FALSE, use = "complete")
mean(acts14$CARS)
var(acts14$CARS)
# You can round your answer using the round() function
#**************************************************
# You will need to read in all 14 years of the data
# You will put the data into a data structure called a list
# To do this you will use code I have written, AccidentInput.R
# Put that file in your working directory and then source it:
source(mysourcepathAI)
# Now use it to read in all the data. You must have ALL and ONLY the rail accident data
# files in one directory. Call that directory and its path, path.
# You can give your data a name
# In my examples below I use acts as the name for data sets
# Then use the command
acts <- file.inputl(mylistpath)
# E.G.
#acts <- file.inputl("C:\\Users\\james Bennett\\Desktop\\R_Code\\AccidentInput.R")
# path is the specification of the path to your file.
# Now acts[[1]] is the data set from year 2001,
# acts[[2]] is the data set from year 2002, etc.
# Before we put all the data into one data frame
# we must clean the data
##################################################
#
# Data Cleaning
#
##################################################
#************************************************
# Variable names
matrix(names(acts[[1]]))
matrix(names(acts[[8]]))
# Notice that the number of columns changes from year to year - 146 vs 140
ncol(acts[[1]])
ncol(acts[[8]])
# Get a common set the variables
comvar <- intersect(colnames(acts[[1]]), colnames(acts[[8]]))
# Now combine the data frames for all 12 years
# Use combine.data()
totacts <- combine.data(acts, comvar)
# How many accidents? 46883
dim(totacts)
# View of accident damage - Most of them are minor accideint
par(mfcol=c(1,1), oma=c(1,0,0,0), mar=c(1,1,1,0), tcl=-0.1, mgp=c(2,0,0))
boxplot(totacts$ACCDMG,range = 1.5, main = "Boxplot of accident damage")
hist(totacts$ACCDMG)
#*************************************************
# Accident Reports
# Look at the most costly accident in the data set
which(totacts$ACCDMG == max(totacts$ACCDMG))
# Check out the narratives for this extreme accident
totacts[42881,]
# How do we find duplicates?
# Are there other duplicates?
duplicated(totacts[1:100, c("YEAR", "MONTH", "DAY", "TIMEHR", "TIMEMIN")])
# why not use latitude and longitude? - Because date and time does the trick - what are the chances we had had accidents at the same time?!
# why not use INCDTNO? - it is not unique to an incident - We need a primary key - Think DB
totacts[totacts$INCDTNO == "1", 1:10]
# Remove duplicates
totacts <- totacts[!duplicated(totacts[, c("YEAR", "MONTH", "DAY", "TIMEHR", "TIMEMIN")]),]
#*******************************************
# What is the second most extreme accident?
which(totacts$ACCDMG > 1.5e7)
# what should we do? - We remove it - This was a result of a terrorist attack - cannot be expected to controll this
totacts <- totacts[-1223,]
#********************************************
# Missing data
# Do a summary of totacts
names(summary(totacts$Latitude))
# Are we missing values for any variables?
# How many?
nafind <- function(x){sum(is.na(x))}
apply(totacts,2, "nafind")
# Do we need all the variables?
matrix(names(totacts))
# Remove unnecessary variables, then get a summary
nacount <- apply(totacts,2, "nafind")
varWna <- which(nacount > 0)
# Keep TYPEQ, we'll use it. The others we don't need.
which(colnames(totacts)[varWna] == "TYPEQ")
varWna <- varWna[-which(colnames(totacts)[varWna]== "TYPEQ")]
totacts <- totacts[, -varWna]
# Save your data frame
# check you working directory and change it if necessary
getwd()
write.csv(totacts, file ="D:\\R\\R_Output\\totactsClean.csv", row.names = F)
#***********************************
#
# Summary of accidents
#
#***********************************
# Get a summary of the cleaned data set
# It does not seem to address the expense associated with Bodily Injuries or Deaths or litigation from deaths or injuries
summary(totacts)
# How many accidents?
dim(totacts)
# Total cost of all accidents
sum(totacts$ACCDMG)
#summary(totacts$CAUSE)
# Average annual cost of accidents
sum(totacts$ACCDMG)/14
# first yearly costs (sums)
dmgyrsum <- tapply(totacts$ACCDMG, totacts$YEAR, sum)
##what about the cost for injuries and deaths
## for instance
which(totacts$TOTKLD == max(totacts$TOTKLD))
pd_dmg <- sum(totacts$EQPDMG[15012],totacts$TRKDMG[15012])
discrepancy <- totacts$ACCDMG[15012] - pd_dmg
discrepancy
## of 592800 - but there were 9 deaths and 292 injuries ??
#then average
mean(dmgyrsum)
# Total number killed
sum(totacts$TOTKLD)
# Largest number killed in an accident - But the data shows that
max(totacts$TOTKLD)
# Total number injured
sum(totacts$TOTINJ)
# Largest number injured in an accident
max(totacts$TOTINJ)
# What is the average number of injuries per year?
round(sum(totacts$TOTINJ)/14)
# types of variables
str(totacts)
#**************************************************
#
# Time series of Accidents
#
#**************************************************
# Yearly no. of accidents
plot(1:max(totacts$YEAR), tapply(totacts$ACCDMG, totacts$YEAR, length), type = "l", col = "black", xlab = "Year", ylab = "Frequency", main = "Number of Accidents per Year", lwd =2)
# Yearly total cost of accidents
plot(1:max(totacts$YEAR), tapply(totacts$ACCDMG, totacts$YEAR, sum), type = "l", col = "black", xlab = "Year", ylab = "Cost ($)", main = "Total Damage per Year", lwd =2)
# Yearly maximum cost of accidents
plot(1:max(totacts$YEAR), tapply(totacts$ACCDMG, totacts$YEAR, max), type = "l", col = "black", xlab = "Year", ylab = "Cost ($)", main = "Total Damage per Year", lwd =2)
# Putting total and maximum together using symbols
symbols(2001:2014, tapply(totacts$ACCDMG, totacts$YEAR, sum), circles=tapply(totacts$ACCDMG, totacts$YEAR, max),inches=0.35, fg="white", bg="red", xlab="Year", ylab="Cost ($)", main = "Total Accident Damage")
lines(2001:2014, tapply(totacts$ACCDMG, totacts$YEAR, sum))
# Repeat this for total killed and total injured and the sum of them.
symbols(2001:2014, tapply(totacts$TOTKLD, totacts$YEAR, sum), circles = tapply(totacts$TOTKLD, totacts$YEAR, max), inches = 0.35, fg ="yellow", bg ="red", xlab = "Year", ylab = "People Killed", main = "Total Killed")
lines(2001:2014, tapply(totacts$TOTKLD, totacts$YEAR, sum))
symbols(2001:2014, tapply(totacts$TOTINJ, totacts$YEAR, sum), circles = tapply(totacts$TOTINJ, totacts$YEAR, max), inches = 0.35, fg ="black", bg ="red", xlab = "Year", ylab = "People Injured", main = "Total Injured")
lines(2001:2014, tapply(totacts$TOTINJ, totacts$YEAR, sum))
#***********************************
#
# histograms of ACCDMG and TEMP
#
#***********************************
# These examples are for 2011
hist(acts[[11]]$ACCDMG) # for 2011
hist(acts[[11]]$ACCDMG, main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
# Different bin widths
par(mfrow = c(2,2))
hist(totacts$TEMP, breaks = "scott", main = "Accident Temperatures (Scott)", xlab = "Temp (F)", col = "steelblue")
hist(totacts$TEMP, breaks = "fd", main = "Accident Temperatures (FD)", xlab = "Temp (F)", col = "steelblue")
hist(totacts$TEMP, main = "Accident Temperatures (Sturges)", xlab = "Temp (F)", col = "steelblue")
hist(totacts$TEMP, breaks = 100, main = "Accident Temperatures (100)", xlab = "Temp (F)", col = "steelblue")
par(mfrow = c(1,1))
# Different bin widths
hist(acts[[11]]$ACCDMG, breaks = "scott", main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[11]]$ACCDMG, breaks = "fd", main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[11]]$ACCDMG, breaks = 20, main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[11]]$ACCDMG, breaks = 100, main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
# other years
par(mfrow = c(2,2))
hist(acts[[1]]$ACCDMG, main = "Total Accident Damage in 2001", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[4]]$ACCDMG, main = "Total Accident Damage in 2004", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[8]]$ACCDMG, main = "Total Accident Damage in 2008", xlab = "Dollars ($)", col = "steelblue")
hist(acts[[11]]$ACCDMG, main = "Total Accident Damage in 2011", xlab = "Dollars ($)", col = "steelblue")
par(mfrow = c(1,1))
#*********************************************************************
#
# Box Plots of Metrics
# and Extreme Accidents
#
#*********************************************************************
#*****************************
# ACCDMG
boxplot(totacts$ACCDMG, main = "Xtreme Accident damage")
boxplot(totacts$TOTKLD, main = "Deaths in Extreme incident")
# Plot only the extreme points
# (extreme defined by the box plot rule)
# Get the values in the box plot
dmgbox <- boxplot(totacts$ACCDMG)
dmgbox2 <- boxplot(totacts$TOTKLD)
# How many extreme damage accidents?
length(dmgbox$out)
##extreme accident dmg 4862
length(dmgbox2$out)
dmgbox$stats
##extreme accident relative to deaths 479 (this is not commom)
# What proportion of accidents are extreme? (round to 2 digits) - 13%
round(length(dmgbox$out)/length(totacts$ACCDMG),2)
# What is the proportion of costs for extreme damage accidents? (round to 2 digits)
round(sum(dmgbox$out)/sum(totacts$ACCDMG),2) ##13% causes 74% of the damages - Insanity!!
# Create a data frame with just the extreme ACCDMG accidents
round(length(dmgbox2$out)/length(totacts$TOTKLD),2)
##.01 are extreme - deaths are an wear event
round(sum(dmgbox2$out)/sum(totacts$TOTKLD),2)
##all deaths are were events
xdmg <- totacts[totacts$ACCDMG > dmgbox$stats[5],]
dim(xdmg)
###4862 are were
# Look at the boxplots and histograms of these extreme accidents
boxplot(xdmg$ACCDMG, col = "steelblue", main = "Accidents with Extreme Damage", ylab = "Cost ($)")
plot(1:14, tapply(xdmg$ACCDMG, xdmg$YEAR, sum), type = "l", xlab = "Year", ylab = "Total Damage ($)", main = "Total Extreme Accident Damage per Year")
# also plot number of accidents per year.
plot(1:14, tapply(xdmg$ACCDMG, xdmg$YEAR, length), type = "l", xlab = "Year", ylab = "No. of Accidents", main = "Number of Extreme Accidents per Year")
# Frequency of accident types
barplot(table(xdmg$TYPE)) #compare with the totacts plot
##Lots of Derailments - wonder is speeding has to do with this - Type = 1
# Repeat for TOTKLD and TOTINJ
# Create a variable called Casualty = TOTKLD + TOTINJ
max(totacts$TOTINJ) ##1000 in a single accident
max(totacts$TOTKLD) ##9 in a single maccident
Casualidad = totacts$TOTKLD + totacts$TOTINJ
max(Casualidad) ###1001
plot(1:max(totacts$YEAR), tapply(totacts$TOTKLD, totacts$YEAR, max), type = "l", col = "black", xlab = "Year", ylab = "Frequency", main = "Number of KILLED", lwd =2)
plot(1:max(totacts$YEAR), tapply(totacts$TOTINJ, totacts$YEAR, max), type = "l", col = "black", xlab = "Year", ylab = "Frequency", main = "Number of Injured", lwd =2)
plot(1:max(totacts$YEAR), tapply(Casualidad, totacts$YEAR, max), type = "l", col = "blue", xlab = "Year", ylab = "Frequency", main = "Combined Casualties", lwd =2)
|
library(knitr)
library(rvest)
library(gsubfn)
library(reshape2)
library(shiny)
library(readr)
library(dplyr)
library(ggplot2)
library(corrplot)
library(tidyr)
library(data.table)
# Uvozimo funkcije za pobiranje in uvoz zemljevida.
source("lib/uvozi.zemljevid.r", encoding="UTF-8") | /lib/libraries.r | permissive | nejclu/APPR-2018-19 | R | false | false | 281 | r | library(knitr)
library(rvest)
library(gsubfn)
library(reshape2)
library(shiny)
library(readr)
library(dplyr)
library(ggplot2)
library(corrplot)
library(tidyr)
library(data.table)
# Uvozimo funkcije za pobiranje in uvoz zemljevida.
source("lib/uvozi.zemljevid.r", encoding="UTF-8") |
# Reading large csv tables as dataframes and Split into Multiple CSV files in R Language
# require(data.table)
# install.packages("data.table")
library(data.table)
# Depend on your system it may be use long time
# use system.time(X) to get reading time
DT <- fread("/Users/yadi/RProjects/data-2015_hse.csv")
# n = number of records to split.
n <- 977000
# Assuming that 'DT' is the data.frame which we need to segment every 977000 rows and save it in a new file,
# we split the dataset by creating a grouping index based on the sequence of rows to a list (lst).
# We loop through the sequence of list elements (lapply(...), and write new file with write.csv.
lst <- split(DT, ((seq_len(nrow(DT)))-1)%/%n+1L)
invisible(lapply(seq_along(lst), function(i)
write.csv(lst[[i]], file=paste0('project', i, '.csv'), row.names=FALSE)))
# Optianl - Importing multi csv files into R ( Reading csv directory
# and import all of them as a data frame )
temp = list.files(pattern="*.csv")
system.time(for (i in 1:length(temp)) assign(temp[i], fread(temp[i])))
| /SplitFile.R | permissive | shahryary/SplitCSVFile | R | false | false | 1,141 | r | # Reading large csv tables as dataframes and Split into Multiple CSV files in R Language
# require(data.table)
# install.packages("data.table")
library(data.table)
# Depend on your system it may be use long time
# use system.time(X) to get reading time
DT <- fread("/Users/yadi/RProjects/data-2015_hse.csv")
# n = number of records to split.
n <- 977000
# Assuming that 'DT' is the data.frame which we need to segment every 977000 rows and save it in a new file,
# we split the dataset by creating a grouping index based on the sequence of rows to a list (lst).
# We loop through the sequence of list elements (lapply(...), and write new file with write.csv.
lst <- split(DT, ((seq_len(nrow(DT)))-1)%/%n+1L)
invisible(lapply(seq_along(lst), function(i)
write.csv(lst[[i]], file=paste0('project', i, '.csv'), row.names=FALSE)))
# Optianl - Importing multi csv files into R ( Reading csv directory
# and import all of them as a data frame )
temp = list.files(pattern="*.csv")
system.time(for (i in 1:length(temp)) assign(temp[i], fread(temp[i])))
|
context("invoke")
sc <- testthat_spark_connection()
test_that("we can invoke_static with 0 arguments", {
expect_equal(invoke_static(sc, "sparklyr.Test", "nullary"), 0)
})
test_that("we can invoke_static with 1 scalar argument", {
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryPrimitiveInt",
ensure_scalar_integer(5)), 25)
expect_error(invoke_static(sc, "sparklyr.Test", "unaryPrimitiveInt", NULL))
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryInteger",
ensure_scalar_integer(5)), 25)
expect_error(invoke_static(sc, "sparklyr.Test", "unaryInteger", NULL))
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryNullableInteger",
ensure_scalar_integer(5)), 25)
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryNullableInteger", NULL), -1)
})
test_that("we can invoke_static with 1 Seq argument", {
expect_equal(invoke_static(sc, "sparklyr.Test", "unarySeq", list(3, 4)), 25)
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryNullableSeq", list(3, 4)), 25)
})
test_that("we can invoke_static with null Seq argument", {
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryNullableSeq", NULL), -1)
})
test_that("infer correct overloaded method", {
expect_equal(invoke_static(sc, "sparklyr.Test", "infer", 0), "Double")
expect_equal(invoke_static(sc, "sparklyr.Test", "infer", "a"), "String")
expect_equal(invoke_static(sc, "sparklyr.Test", "infer", list()), "Seq")
})
test_that("roundtrip date array", {
dates <- list(as.Date("2016/1/1"), as.Date("2016/1/1"))
expect_equal(
invoke_static(sc, "sparklyr.Test", "roundtrip", dates),
do.call("c", dates)
)
})
test_that("we can invoke_static using make_ensure_scalar_impl", {
test_ensure_scalar_integer <- make_ensure_scalar_impl(
is.numeric,
"a length-one integer vector",
as.integer
)
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryPrimitiveInt",
test_ensure_scalar_integer(5)), 25)
})
test_that("we can invoke_static 'package object' types", {
expect_equal(
invoke_static(sc, "sparklyr.test", "testPackageObject", "x"),
"x"
)
})
| /tests/testthat/test-invoke.R | permissive | Ineedi2/sparklyr | R | false | false | 2,238 | r | context("invoke")
sc <- testthat_spark_connection()
test_that("we can invoke_static with 0 arguments", {
expect_equal(invoke_static(sc, "sparklyr.Test", "nullary"), 0)
})
test_that("we can invoke_static with 1 scalar argument", {
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryPrimitiveInt",
ensure_scalar_integer(5)), 25)
expect_error(invoke_static(sc, "sparklyr.Test", "unaryPrimitiveInt", NULL))
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryInteger",
ensure_scalar_integer(5)), 25)
expect_error(invoke_static(sc, "sparklyr.Test", "unaryInteger", NULL))
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryNullableInteger",
ensure_scalar_integer(5)), 25)
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryNullableInteger", NULL), -1)
})
test_that("we can invoke_static with 1 Seq argument", {
expect_equal(invoke_static(sc, "sparklyr.Test", "unarySeq", list(3, 4)), 25)
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryNullableSeq", list(3, 4)), 25)
})
test_that("we can invoke_static with null Seq argument", {
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryNullableSeq", NULL), -1)
})
test_that("infer correct overloaded method", {
expect_equal(invoke_static(sc, "sparklyr.Test", "infer", 0), "Double")
expect_equal(invoke_static(sc, "sparklyr.Test", "infer", "a"), "String")
expect_equal(invoke_static(sc, "sparklyr.Test", "infer", list()), "Seq")
})
test_that("roundtrip date array", {
dates <- list(as.Date("2016/1/1"), as.Date("2016/1/1"))
expect_equal(
invoke_static(sc, "sparklyr.Test", "roundtrip", dates),
do.call("c", dates)
)
})
test_that("we can invoke_static using make_ensure_scalar_impl", {
test_ensure_scalar_integer <- make_ensure_scalar_impl(
is.numeric,
"a length-one integer vector",
as.integer
)
expect_equal(invoke_static(sc, "sparklyr.Test", "unaryPrimitiveInt",
test_ensure_scalar_integer(5)), 25)
})
test_that("we can invoke_static 'package object' types", {
expect_equal(
invoke_static(sc, "sparklyr.test", "testPackageObject", "x"),
"x"
)
})
|
####################################################
##### Filtering of new BRASS vcf's ##############
##### Hinxton, EMBL-EBI, Sept 2017 ##############
##### N. Volkova, nvolkova@ebi.ac.uk ##############
####################################################
library(tidyr)
library(rtracklayer)
library(VariantAnnotation)
source('../../useful_functions.R')
# 1. Upload the variants and perform QC
data <- openxlsx::read.xlsx(xlsxFile = "Supplementary Table 1. Sample description for C.elegans experiments.xlsx", sheet = 2, cols = 1:8)
data$Sample <- as.character(data$Sample)
data$Genotype <- as.character(data$Genotype)
CD2Mutant <- sapply(1:nrow(data), function(i) {
if (data$Type[i] == 'mut.acc.') return(paste0(data$Genotype[i],':',data$Generation[i]))
return(paste0(data$Genotype[i],':',data$Mutagen[i],':',data$Drug.concentration[i]))
})
names(CD2Mutant) <- data$Sample
CD2Mutant <- CD2Mutant[sort(names(CD2Mutant))]
# Upload the VCFs
library(VariantAnnotation)
VCFPATH='/path/to/SV/VCFs'
# # FILTERING
raw.delly.vcf <- sapply(names(CD2Mutant), function(x) read_ce_vcf(paste0(VCFPATH,x,'.vcf')))
raw.delly.vcf <- raw.delly.vcf[!is.na(raw.delly.vcf)]
delly.vcf <- sapply(raw.delly.vcf, function(vcf)
vcf[geno(vcf)[['DV']][,1]>=10 & # variant support in test
geno(vcf)[['DV']][,2]<1 & # variant support in control
geno(vcf)[['DR']][,1]+geno(vcf)[['DV']][,1] < 150 & # coverage
geno(vcf)[['DR']][,2]+geno(vcf)[['DV']][,2] < 150 & # coverage
granges(vcf)$FILTER=='PASS']) # quality filter
barplot(sapply(delly.vcf,length))
# Remove MtDNA variants
delly.vcf <- lapply(delly.vcf, function(vcf) {
if (length(vcf)==0) return(vcf)
return(vcf[seqnames(vcf) %in% c("I","II","III","IV","V","X")])
})
# Make tables
delly.tables <- lapply(delly.vcf, function(vcf) {
tmp <- data.frame(CHR1 = seqnames(granges(vcf)),
POS1 = start(granges(vcf)),
CHR2 = info(vcf)$CHR2,
POS2 = info(vcf)$END,
READS = info(vcf)$PE,
TYPE = info(vcf)$SVTYPE)
rownames(tmp) <- names(vcf)
return(tmp)
})
# 2. Filter out telomeric stuff etc
# Filter out telomeric stuff
# upload genome and get chromosome sizes
url <- 'ftp://ftp.ensembl.org/pub/release-96/fasta/caenorhabditis_elegans/dna/Caenorhabditis_elegans.WBcel235.dna_sm.toplevel.fa.gz'
download.file(url = url, destfile = 'Caenorhabditis_elegans.WBcel235.dna.toplevel.fa.gz', method = "auto", quiet=FALSE)
WBcel235 <- readDNAStringSet("Caenorhabditis_elegans.WBcel235.dna.toplevel.fa.gz") # get worm reference genome
chr_sizes <- width(WBcel235)
names(chr_sizes) <- c("I","II","III","IV","MtDNA","V","X")
genome_size = sum(as.numeric(chr_sizes))
# telomeres
telomere <- matrix(1,nrow=6,ncol=4,dimnames=list(c("I","II","III","IV","V","X"),c("l.start","l.end","r.start","r.end")))
telomere[,2] <- c(436,400,200,47500,700,5000)
telomere[,3] <- c(15060000,15277300,13781900,
17492000,20923800,17718700)
telomere[,4] <- chr_sizes[-5]
telomere.delly <- list()
# get rid of variants intersecting with telomeres
for (x in names(delly.tables)) {
bad <- NULL
if (nrow(delly.tables[[x]])==0 || is.na(delly.tables[[x]])) next
for (j in 1:nrow(delly.tables[[x]])) {
if (delly.tables[[x]][j,2] < telomere[as.character(delly.tables[[x]][j,1]),2] ||
delly.tables[[x]][j,4] > telomere[as.character(delly.tables[[x]][j,3]),3])
bad <- c(bad,j)
}
if (length(bad)>0) {
telomere.delly[[x]] <- delly.tables[[x]][bad,]
delly.tables[[x]] <- delly.tables[[x]][-bad,]
print(c("telomeres",length(bad),x))
}
}
dimensions_filt <- sapply(delly.tables,nrow)
# 3. Deduplicate breakpoints
# Special treatment for MA samples: they may be related across generations so shall not be compared against each other within same genotype
mut.acc <- intersect(names(CD2Mutant)[is.na(data$Mutagen[match(names(CD2Mutant),data$Sample)])],names(delly.tables))
all_genotypes <- data$Genotype.new[match(mut.acc, data$Sample)]
all_generations <- data$Generation[match(mut.acc, data$Sample)]
allSV <- data.frame()
for (x in names(delly.tables)) {
if(nrow(delly.tables[[x]]) == 0) next
allSV <- rbind(allSV,
data.frame(delly.tables[[x]],
name = x,
stringsAsFactors = F))
}
allSV[,1] <- as.character(allSV[,1])
allSV[,3] <- as.character(allSV[,3])
allSV[,2] <- as.numeric(allSV[,2])
allSV[,4] <- as.numeric(allSV[,4]) # 41643
allSV.mut <- allSV[!(allSV$name %in% mut.acc),] # 34039
delly.tables.dedup <- list()
for (worm in names(delly.tables)) {
if (worm %in% mut.acc) {
worm_genotype <- data$Genotype.new[match(worm, data$Sample)]
if (all_generations[match(worm,mut.acc)] > 1)
worms_to_compare <- setdiff(mut.acc[all_genotypes != worm_genotype | all_generations < 2],worm)
else worms_to_compare <- setdiff(mut.acc,worm)
allSV.compare <- allSV[allSV$name %in% worms_to_compare,]
reference <- rbind(allSV.mut, allSV.compare)
delly.tables.dedup[[worm]] <- filter.breakpoints(SV = delly.tables[[worm]], reference = reference)
} else {
delly.tables.dedup[[worm]] <- filter.breakpoints(SV = delly.tables[[worm]], reference = allSV[allSV$name != worm,])
}
print(worm)
}
dimensions_dedup <- sapply(delly.tables.dedup,nrow)
plot(dimensions_dedup,cex=0.2,main="numbers of SVs after deduplication of breakpoints")
# count 'em all
delly.filtered.bp.counts <- list()
for (i in seq_along(delly.tables.dedup)) {
rearr.counts <- vector("numeric",5)
names(rearr.counts) <- c("BND","DEL","INV","DUP","ALL")
if (nrow(delly.tables.dedup[[i]]) < 1) {
delly.filtered.bp.counts[[i]] <- rearr.counts
next
}
if (is.na(delly.tables.dedup[[i]])) {
delly.filtered.bp.counts[[i]] <- NA
next
}
rearr.counts[1] <- sum(delly.tables.dedup[[i]]$TYPE == 'BND')
rearr.counts[2] <- sum(delly.tables.dedup[[i]]$TYPE == 'DEL')
rearr.counts[3] <- sum(delly.tables.dedup[[i]]$TYPE == 'INV')
rearr.counts[4] <- sum(delly.tables.dedup[[i]]$TYPE == 'DUP')
rearr.counts[5] <- sum(rearr.counts[1:4])
delly.filtered.bp.counts[[i]] <- rearr.counts
}
names(delly.filtered.bp.counts) <- names(delly.tables.dedup)
# visualize class sizes
barplot(colSums(do.call("rbind",delly.filtered.bp.counts)))
# compare to non-bp deduplication
barplot(colSums(do.call("rbind",delly.filtcounts)))
# size filter
barplot(sapply(delly.tables.dedup, nrow))
for (i in 1:length(delly.tables.dedup)) {
ind <- which(as.character(delly.tables.dedup[[i]][,1])==as.character(delly.tables.dedup[[i]][,3]) &
(as.numeric(delly.tables.dedup[[i]][,4])-as.numeric(delly.tables.dedup[[i]][,2])<400))
if (length(ind)>0)
delly.tables.dedup[[i]] <- delly.tables.dedup[[i]][-ind,,drop=F]
}
barplot(sapply(delly.tables.dedup, nrow))
# 4. Now make sure that DELs and TDs are actually DELs and TDs (get them a p-value)
# Will need the paths to BigWig and bamstats files for each of the samples which have any deletions or tandem duplications.
# bamstats files were acuired as
# samtools idxstats sample.bam > sample.stat.dat
PATHTOBW <- 'path/to/bw/files'
PATHTOBAMSTATS <- 'path/to/bam/stats/files'
ref.reads1 <- 44773320 # overall number of mapped reads in reference genome (CD0001b)
ref.reads2 <- 31427593 # overall number of mapped reads in reference genome (CD0850b)
# Check TD and DEL, deduplicate
set1 <- names(CD2Mutant)[1:(match('CD0683b',names(CD2Mutant))-1)]
for (worm in names(delly.tables.dedup)[794:length(delly.tables.dedup)]) {
if (worm %in% set1) {
ref.reads <- ref.reads1
ref.worm <- 'CD0001b'
}
else {
ref.reads <- ref.reads2
ref.worm <- 'CD0850b'
}
# upload stats files to get the number of mapped reads in the sample of interest
if (nrow(delly.tables.dedup[[worm]]) == 0) next
file <- paste(PATHTOBAMSTATS,worm,".stat.dat",sep="")
alt.reads <- sum(read.table(file)$V3[1:6])
r.ratio <- ref.reads / alt.reads
# get the deletions
dels <- delly.tables.dedup[[worm]][delly.tables.dedup[[worm]]$TYPE=="DEL",]
if (nrow(dels)!=0) {
goodness <- sapply(1:nrow(dels),function(j) {
big.ranges <- c(as.numeric(as.character(dels[j,2])),as.numeric(as.character(dels[j,4])))
chr <- as.character(dels[j,1])
if (big.ranges[2]-big.ranges[1]<100000) {
unit <- 10**round(log10(big.ranges[2]-big.ranges[1])-1)
if (big.ranges[2]+unit > telomere[chr,'r.start']) big.ranges[2] <- telomere[chr,'r.start'] - unit
if (big.ranges[1]-unit < telomere[chr,'l.end']) big.ranges[1] <- telomere[chr,'l.end'] + unit
big.ranges <- GRanges(seqnames = chr, ranges = IRanges(start=big.ranges[1]-unit, end=big.ranges[2]+unit))
x <- seq(from=start(big.ranges), to=end(big.ranges), by = unit/10)
region <- rtracklayer::import(paste0(PATHTOBW,'/',worm,'.merged.bw'),which=big.ranges)
region.ref <- rtracklayer::import(paste0(PATHTOBW,'/',ref.worm,".merged.bw"),which=big.ranges)
bins <- GRanges(seqnames=dels[j,1],
ranges=IRanges(start=x[-length(x)]+1,end=x[-1]),
seqinfo=seqinfo(region))
numvar <- mcolAsRleList(x=region,varname="score")
numvar.ref <- mcolAsRleList(x=region.ref,varname="score")
numvar.ref <- numvar.ref[names(numvar)]
points <- as.numeric(binnedAverage(bins,numvar,varname="score",na.rm=T)$score) + 0.1
points[is.na(points)] <- 1
points.ref <- as.numeric(binnedAverage(bins,numvar.ref,varname="score")$score) + 0.1
points.ref[is.na(points.ref)] <- 1
x <- x[-length(x)]
logfold <- log(points / points.ref * r.ratio)
normal = c(1:10,(length(logfold)-9):length(logfold))
odd = c(10:(length(logfold)-10))
if (length(which(is.nan(points)))>0) {
print(c("NaN points!!!",file))
points.ref <- points.ref[-which(points=="NaN")]
normal <- setdiff(normal,which(points=="NaN"))
odd <- setdiff(odd,which(points=="NaN"))
x <- x[-which(points=="NaN")]
points <- points[-which(points=="NaN")]
}
if (length(which(is.na(points.ref)))>0) {
print(c("NA points in ref!!!",file))
normal <- setdiff(normal,which(is.na(points.ref)))
odd <- setdiff(odd,which(is.na(points.ref)))
x <- x[-which(is.na(points.ref))]
points <- points[-which(is.na(points.ref))]
points.ref <- points.ref[-which(is.na(points.ref))]
}
logfold <- log(points / points.ref * r.ratio)
if (length(logfold)==0) return(NA)
return(wilcox.test(logfold[normal], logfold[odd], alternative="greater")$p.value)
}
else {
unit <- 10**round(log10(big.ranges[2]-big.ranges[1]) - 1)
if (big.ranges[2]+unit > telomere[chr,'r.start']) big.ranges[2] <- telomere[chr,'r.start'] - unit
if (big.ranges[1]-unit < telomere[chr,'l.end']) big.ranges[1] <- telomere[chr,'l.end'] + unit
big.ranges <- GRanges(seqnames = chr, ranges = IRanges(start=big.ranges[1]-unit, end=big.ranges[2]+unit))
x <- seq(from=start(big.ranges), to=end(big.ranges), by = unit/10)
region <- rtracklayer::import(paste0(PATHTOBW,'/',worm,'.merged.bw'),which=big.ranges)
region.ref <- rtracklayer::import(paste0(PATHTOBW,'/',ref.worm,".merged.bw"),which=big.ranges)
bins <- GRanges(seqnames=dels[j,1],
ranges=IRanges(start=x[-length(x)]+1,end=x[-1]),
seqinfo=seqinfo(region))
numvar <- mcolAsRleList(x=region,varname="score")
numvar.ref <- mcolAsRleList(x=region.ref,varname="score")
numvar.ref <- numvar.ref[names(numvar)]
points <- as.numeric(binnedAverage(bins,numvar,varname="score",na.rm=T)$score) + 0.1
points[is.na(points)] <- 1
points.ref <- as.numeric(binnedAverage(bins,numvar.ref,varname="score")$score) + 0.1
points.ref[is.na(points.ref)] <- 1
if (length(which(is.nan(points)))>0) {
print(c("NaN points!!!",file))
points.ref <- points.ref[-which(points=="NaN")]
points <- points[-which(points=="NaN")]
}
if (length(which(is.nan(points.ref)))>0) {
print(c("NaN points in ref!!!",file))
points <- points[-which(points.ref=="NaN")]
points.ref <- points.ref[-which(points.ref=="NaN")]
}
logfold <- log(points / points.ref * r.ratio)
return(wilcox.test(logfold,mu=0,alternative = 'less')$p.value)
}
})
}
else goodness <- NULL
del.td.pvalue <- rep(NA,nrow(delly.tables.dedup[[worm]]))
del.td.pvalue[delly.tables.dedup[[worm]][,'TYPE']=="DEL"] <- as.numeric(goodness)
delly.tables.dedup[[worm]]$del.td.pvalue <- del.td.pvalue
# get the deletions
tds <- delly.tables.dedup[[worm]][delly.tables.dedup[[worm]]$TYPE=="DUP",]
if (nrow(tds)!=0) {
goodness <- sapply(1:nrow(tds),function(j) {
big.ranges <- c(as.numeric(as.character(tds[j,2])),as.numeric(as.character(tds[j,4])))
chr <- as.character(tds[j,1])
if (big.ranges[2]-big.ranges[1]<100000) {
unit <- 10**round(log10(big.ranges[2]-big.ranges[1])-1)
if (big.ranges[2]+unit > telomere[chr,'r.start']) big.ranges[2] <- telomere[chr,'r.start'] - unit
if (big.ranges[1]-unit < telomere[chr,'l.end']) big.ranges[1] <- telomere[chr,'l.end'] + unit
big.ranges <- GRanges(seqnames = chr, ranges = IRanges(start=big.ranges[1]-unit, end=big.ranges[2]+unit))
x <- seq(from=start(big.ranges), to=end(big.ranges), by = unit/10)
region <- rtracklayer::import(paste0(PATHTOBW,'/',worm,'.merged.bw'),which=big.ranges)
region.ref <- rtracklayer::import(paste0(PATHTOBW,'/',ref.worm,".merged.bw"),which=big.ranges)
bins <- GRanges(seqnames=tds[j,1],
ranges=IRanges(start=x[-length(x)]+1,end=x[-1]),
seqinfo=seqinfo(region))
numvar <- mcolAsRleList(x=region,varname="score")
numvar.ref <- mcolAsRleList(x=region.ref,varname="score")
numvar.ref <- numvar.ref[names(numvar)]
points <- as.numeric(binnedAverage(bins,numvar,varname="score",na.rm=T)$score) + 0.1
points[is.na(points)] <- 1
points.ref <- as.numeric(binnedAverage(bins,numvar.ref,varname="score")$score) + 0.1
points.ref[is.na(points.ref)] <- 1
x <- x[-length(x)]
logfold <- log(points / points.ref * r.ratio)
normal = c(1:10,(length(logfold)-9):length(logfold))
odd = c(10:(length(logfold)-10))
if (length(which(is.nan(points)))>0) {
print(c("NaN points!!!",file))
points.ref <- points.ref[-which(points=="NaN")]
normal <- setdiff(normal,which(points=="NaN"))
odd <- setdiff(odd,which(points=="NaN"))
x <- x[-which(points=="NaN")]
points <- points[-which(points=="NaN")]
}
if (length(which(is.na(points.ref)))>0) {
print(c("NA points in ref!!!",file))
normal <- setdiff(normal,which(is.na(points.ref)))
odd <- setdiff(odd,which(is.na(points.ref)))
x <- x[-which(is.na(points.ref))]
points <- points[-which(is.na(points.ref))]
points.ref <- points.ref[-which(is.na(points.ref))]
}
logfold <- log(points / points.ref * r.ratio)
if (length(logfold)==0) return(NA)
return(wilcox.test(logfold[normal], logfold[odd], alternative="less")$p.value)
}
else {
unit <- 10**round(log10(big.ranges[2]-big.ranges[1]) - 1)
if (big.ranges[2]+unit > telomere[chr,'r.start']) big.ranges[2] <- telomere[chr,'r.start'] - unit
if (big.ranges[1]-unit < telomere[chr,'l.end']) big.ranges[1] <- telomere[chr,'l.end'] + unit
big.ranges <- GRanges(seqnames = chr, ranges = IRanges(start=big.ranges[1]-unit, end=big.ranges[2]+unit))
x <- seq(from=start(big.ranges), to=end(big.ranges), by = unit/10)
region <- rtracklayer::import(paste0(PATHTOBW,'/',worm,'.merged.bw'),which=big.ranges)
region.ref <- rtracklayer::import(paste0(PATHTOBW,'/',ref.worm,".merged.bw"),which=big.ranges)
bins <- GRanges(seqnames=tds[j,1],
ranges=IRanges(start=x[-length(x)]+1,end=x[-1]),
seqinfo=seqinfo(region))
numvar <- mcolAsRleList(x=region,varname="score")
numvar.ref <- mcolAsRleList(x=region.ref,varname="score")
numvar.ref <- numvar.ref[names(numvar)]
points <- as.numeric(binnedAverage(bins,numvar,varname="score",na.rm=T)$score)+0.1
points[is.na(points)] <- 1
points.ref <- as.numeric(binnedAverage(bins,numvar.ref,varname="score")$score)+0.1
points.ref[is.na(points.ref)] <- 1
if (length(which(is.nan(points)))>0) {
print(c("NaN points!!!",file))
points.ref <- points.ref[-which(points=="NaN")]
points <- points[-which(points=="NaN")]
}
if (length(which(is.nan(points.ref)))>0) {
print(c("NaN points in ref!!!",file))
points <- points[-which(points.ref=="NaN")]
points.ref <- points.ref[-which(points.ref=="NaN")]
}
logfold <- log(points / points.ref * r.ratio)
return(wilcox.test(logfold,mu=0,alternative='greater')$p.value)
}
})
}
else goodness <- NULL
if (!('del.td.pvalue' %in% colnames(delly.tables.dedup[[worm]]))) {
del.td.pvalue <- rep(NA,nrow(delly.tables.dedup[[worm]]))
del.td.pvalue[delly.tables.dedup[[worm]][,'TYPE']=="DUP"] <- as.numeric(goodness)
delly.tables.dedup[[worm]]$del.td.pvalue <- del.td.pvalue
}
else {
delly.tables.dedup[[worm]]$del.td.pvalue[delly.tables.dedup[[worm]][,'TYPE']=="DUP"] <- as.numeric(goodness)
}
print(worm)
}
# p-values - check NAs
for (worm in names(delly.tables.dedup)) {
dels <- which(delly.tables.dedup[[worm]]$TYPE=="DUP")
tds <- which(delly.tables.dedup[[worm]]$TYPE=="DEL")
if (length(dels)>0) {
bad.del <- which(is.na(delly.tables.dedup[[worm]][dels,7]))
if (length(bad.del)>0) delly.tables.dedup[[worm]] <- delly.tables.dedup[[worm]][-dels[bad.del],]
}
if (length(tds)>0) {
bad.td <- which(is.na(delly.tables.dedup[[worm]][tds,7]))
if (length(bad.td)>0) delly.tables.dedup[[worm]] <- delly.tables.dedup[[worm]][-tds[bad.td],]
}
}
delly.tables <- delly.tables.dedup[sapply(delly.tables.dedup,nrow)>0]
barplot(sapply(delly.tables.dedup,nrow)) # no difference
# do multiple testing correction - Benjamini-Hochberg
pval.del <- NULL
pval.td <- NULL
for (x in names(delly.tables.dedup)) {
pval.del <- c(pval.del,delly.tables.dedup[[x]][delly.tables.dedup[[x]]$TYPE=="DEL",7])
pval.td <- c(pval.td,delly.tables.dedup[[x]][delly.tables.dedup[[x]]$TYPE=="DUP",7])
}
pval.del.adj <- p.adjust(pval.del,method="BH")
pval.td.adj <- p.adjust(pval.td,method="BH")
for (x in names(delly.tables.dedup)) {
td.length <- length(which(delly.tables.dedup[[x]]$TYPE=="DUP"))
del.length <- length(which(delly.tables.dedup[[x]]$TYPE=="DEL"))
if (del.length>0) {
delly.tables.dedup[[x]]$del.td.pvalue[delly.tables.dedup[[x]]$TYPE=="DEL"] <- pval.del.adj[1:del.length]
pval.del.adj <- pval.del.adj[-c(1:del.length)]
}
if (td.length>0) {
delly.tables.dedup[[x]]$del.td.pvalue[delly.tables.dedup[[x]]$TYPE=="DUP"] <- pval.td.adj[1:td.length]
pval.td.adj <- pval.td.adj[-c(1:td.length)]
}
}
PATHTOCLUST='/path/where/to/write/clustered/tables'
# CLUSTER
source("classification_script.R")
for (worm in names(delly.tables.dedup)) {
d <- delly.tables.dedup[[worm]]
if (nrow(d) == 0) next
output_file = paste(PATHTOCLUST,'/',worm,".clust_mat",sep="")
d[,1] = as.character(d[,1]) # chomosomes
d[,3] = as.character(d[,3]) # chomosomes
d[,2] = as.numeric(as.character(d[,2]))
d[,4] = as.numeric(as.character(d[,4]))
d[,6] = as.character(d[,6])
if (nrow(d) == 1) {
ct = 1
# Get the footprint info
pos = c(d[,2], d[,4])
chrs = c(d[,1], d[,3])
res = get_footprints(pos, chrs)
footprint_idx = sprintf("%s.chr%s.%s", c(ct, ct), chrs, res$footprint_idx)
footprint_bounds = res$footprint_bounds
write.table(
data.frame(
d,
clust = ct,
clust_size = sapply(ct, function(x) sum(x == ct)),
fp_l = footprint_idx[1:nrow(d)],
fp_h = footprint_idx[-(1:nrow(d))]
),
output_file,
quote = F,
sep = "\t"
)
} else {
ct = clust_rgs_new(d)$cutree
# Get the footprint info
pos = c(d[,2], d[,4])
chrs = c(d[,1], d[,3])
res = get_footprints(pos, chrs)
footprint_idx = sprintf("%s.chr%s.%s", c(ct, ct), chrs, res$footprint_idx)
footprint_bounds = res$footprint_bounds
write.table(
data.frame(
d,
clust = ct,
clust_size = sapply(ct, function(x) sum(x == ct)),
fp_l = footprint_idx[1:nrow(d)],
fp_h = footprint_idx[-(1:nrow(d))]
),
output_file,
quote = F,
sep = "\t"
)
}
}
delly.tables.dedup <- delly.tables.dedup[sapply(delly.tables.dedup,nrow)>0]
# reading reclustered SVs
SVclust <- list()
for (worm in names(delly.tables.dedup))
{
if(nrow(delly.tables.dedup[[worm]]) > 0) {
file = paste(PATHTOCLUST,'/',worm,".clust_mat",sep="")
SVclust[[worm]] <- read.table(file=file, header=T, sep = "\t")
}
}
# add sample name to all SV tables
for (worm in names(SVclust)){
SVclust[[worm]] <- cbind(SVclust[[worm]][,1:10],Sample=as.character(rep(worm,nrow(SVclust[[worm]]))),
del.td.pvalue = delly.tables.dedup[[worm]]$del.td.pvalue)
}
# Assessing types of clusters
rearr.count.final.dedup <- list()
for (i in seq_along(SVclust)) {
SVclust[[i]] <- cbind(SVclust[[i]],clust.type=as.character(rep("some",nrow(SVclust[[i]]))))
SVclust[[i]]$clust.type <- as.character(SVclust[[i]]$clust.type)
rearr.counts <- vector("numeric",8)
names(rearr.counts) <- c("TD","DEL","INV","COMPLEX","TRSL","INTCHR","FOLDBACK","MOVE") # TRSL = copypaste, MOVE = TRSL with deletion
for (j in unique(SVclust[[i]]$clust)) {
which(SVclust[[i]]$clust==j) -> clust_ind
bp.types <- as.character(SVclust[[i]]$TYPE[clust_ind])
# 2 INTERSECTING pairs of breakpoints DEL, DEL, TD - translocation
# any >2 pairs - complex
if (length(clust_ind)>2) {
if (length(clust_ind)==3 &
(length(which(bp.types=="DEL"))==2) &
("DUP" %in% bp.types)) {
rearr.counts["MOVE"] = rearr.counts["MOVE"] + 1
SVclust[[i]]$clust.type[clust_ind] <- rep("MOVE",length(clust_ind))
} else {
rearr.counts["COMPLEX"] = rearr.counts["COMPLEX"] + 1
SVclust[[i]]$clust.type[clust_ind] <- rep("COMPLEX",length(clust_ind))
}
}
# 2 pairs of breakpoints: inversions, interchromosomal
if (length(clust_ind)==2) {
if (length(setdiff(c("INV","INV"),bp.types))==0) {
rearr.counts["INV"] = rearr.counts["INV"] + 1
SVclust[[i]]$clust.type[clust_ind] <- c("INV","INV")
}
else if (length(setdiff(bp.types, c("BND","BND")))==0) {
SVclust[[i]]$clust.type[clust_ind] <- c("INTCHR","INTCHR")
rearr.counts["INTCHR"] = rearr.counts["INTCHR"] + 1
}
else if (length(setdiff(bp.types,c("DUP","DEL")))==0) {
dist1 <- SVclust[[i]]$POS1[clust_ind][2]-SVclust[[i]]$POS1[clust_ind][1]
dist2 <- SVclust[[i]]$POS2[clust_ind][2]-SVclust[[i]]$POS2[clust_ind][1]
dist <- SVclust[[i]]$POS2[clust_ind][2]-SVclust[[i]]$POS1[clust_ind][1]
if ((abs(dist1)<(0.1*dist) & bp.types[which.max(SVclust[[i]]$POS2[clust_ind])]=="DUP") ||
(abs(dist2)<(0.2*dist) & bp.types[1]=="DUP") ||
(abs(dist1)<(0.1*dist) & abs(dist2)<(0.1*dist))) {
SVclust[[i]]$clust.type[clust_ind] <- rep("TRSL",2)
rearr.counts["TRSL"] = rearr.counts["TRSL"] + 1
} else {
SVclust[[i]]$clust.type[clust_ind] <- c("COMPLEX","COMPLEX")
rearr.counts["COMPLEX"] = rearr.counts["COMPLEX"] + 1
}
}
else if (length(which(bp.types=="DEL"))==2) {
if (length(which(SVclust[[i]][clust_ind,12]>0.05))==0) {
SVclust[[i]]$clust.type[clust_ind] <- c("COMPLEX","COMPLEX")
rearr.counts["COMPLEX"] = rearr.counts["COMPLEX"] + 1
}
else if (length(which(SVclust[[i]][clust_ind,12]>0.05))==1) {
SVclust[[i]]$clust.type[clust_ind] <- c("DEL","DEL")
rearr.counts["DEL"] = rearr.counts["DEL"] + 1
}
}
else if (length(which(bp.types=="DUP"))==2) {
if (length(which(SVclust[[i]][clust_ind,12]>0.05))==0) {
SVclust[[i]]$clust.type[clust_ind] <- c("COMPLEX","COMPLEX")
rearr.counts["COMPLEX"] = rearr.counts["COMPLEX"] + 1
}
else if (length(which(SVclust[[i]][clust_ind,12]>0.05))==1) {
SVclust[[i]]$clust.type[clust_ind] <- c("TD","TD")
rearr.counts["TD"] = rearr.counts["TD"] + 1
}
}
else {
rearr.counts["COMPLEX"] = rearr.counts["COMPLEX"] + 1
SVclust[[i]]$clust.type[clust_ind] <- c("COMPLEX","COMPLEX")
}
}
if (length(clust_ind)==1) {
if (bp.types=="DUP" && length(which(SVclust[[i]]$del.td.pvalue[clust_ind]>0.05))==0) {
SVclust[[i]]$clust.type[clust_ind] <- "TD"
rearr.counts["TD"] = rearr.counts["TD"] + 1
}
if (bp.types=="DEL" && length(which(SVclust[[i]]$del.td.pvalue[clust_ind]>0.05))==0)
{
rearr.counts["DEL"] = rearr.counts["DEL"] + 1
SVclust[[i]]$clust.type[clust_ind] <- "DEL"
}
if (bp.types=="INV")
{
rearr.counts["FOLDBACK"] = rearr.counts["FOLDBACK"] + 1
SVclust[[i]]$clust.type[clust_ind] <- "FOLDBACK"
}
if (bp.types=="BND") {
rearr.counts["INTCHR"] = rearr.counts["INTCHR"] + 1
SVclust[[i]]$clust.type[clust_ind] <- "INTCHR"
}
}
}
print(i)
rearr.count.final.dedup[[i]] <- rearr.counts
}
names(rearr.count.final.dedup) <- names(SVclust)
# visualize class sizes
colSums(do.call("rbind",delly.filtcounts))
# TD DEL INV COMPLEX TRSL INTCHR FOLDBACK MOVE ALL
# 150 167 99 128 32 125 90 1 792
colSums(do.call("rbind",rearr.count.final.dedup))
# TD DEL INV COMPLEX TRSL INTCHR FOLDBACK MOVE ALL
# 767 604 257 320 100 337 265 32 2682
delly.filtcounts <- rearr.count.final.dedup
SVclust -> delly.SVclust
delly.tables.dedup <- delly.tables.dedup[sapply(delly.tables.dedup,nrow)>0]
for (worm in names(delly.tables.dedup)) {
if ('del.td.pvalue' %in% colnames(delly.tables.dedup[[worm]])) next
delly.tables.dedup[[worm]]$del.td.pvalue <- NA
}
SVclust <- SVclust[sapply(SVclust,nrow)>0]
for (worm in names(SVclust)) {
if ('del.td.pvalue' %in% colnames(SVclust[[worm]])) next
SVclust[[worm]]$del.td.pvalue <- NA
}
save(delly.SVclust, delly.tables.dedup, delly.filtcounts, file='filtered_SV.RData')
filt.delly.vcf <- lapply(names(delly.vcf), function(z) delly.vcf[[z]][rownames(delly.tables.dedup[[z]])])
names(filt.delly.vcf) <- names(delly.vcf)
save(delly.vcf, file = 'Deduplicated_and_filtered_DELLY_vcfs.Rds')
| /worms/filtering/SV_filtering.R | no_license | nvolkova/signature-interactions | R | false | false | 27,451 | r | ####################################################
##### Filtering of new BRASS vcf's ##############
##### Hinxton, EMBL-EBI, Sept 2017 ##############
##### N. Volkova, nvolkova@ebi.ac.uk ##############
####################################################
library(tidyr)
library(rtracklayer)
library(VariantAnnotation)
source('../../useful_functions.R')
# 1. Upload the variants and perform QC
data <- openxlsx::read.xlsx(xlsxFile = "Supplementary Table 1. Sample description for C.elegans experiments.xlsx", sheet = 2, cols = 1:8)
data$Sample <- as.character(data$Sample)
data$Genotype <- as.character(data$Genotype)
CD2Mutant <- sapply(1:nrow(data), function(i) {
if (data$Type[i] == 'mut.acc.') return(paste0(data$Genotype[i],':',data$Generation[i]))
return(paste0(data$Genotype[i],':',data$Mutagen[i],':',data$Drug.concentration[i]))
})
names(CD2Mutant) <- data$Sample
CD2Mutant <- CD2Mutant[sort(names(CD2Mutant))]
# Upload the VCFs
library(VariantAnnotation)
VCFPATH='/path/to/SV/VCFs'
# # FILTERING
raw.delly.vcf <- sapply(names(CD2Mutant), function(x) read_ce_vcf(paste0(VCFPATH,x,'.vcf')))
raw.delly.vcf <- raw.delly.vcf[!is.na(raw.delly.vcf)]
delly.vcf <- sapply(raw.delly.vcf, function(vcf)
vcf[geno(vcf)[['DV']][,1]>=10 & # variant support in test
geno(vcf)[['DV']][,2]<1 & # variant support in control
geno(vcf)[['DR']][,1]+geno(vcf)[['DV']][,1] < 150 & # coverage
geno(vcf)[['DR']][,2]+geno(vcf)[['DV']][,2] < 150 & # coverage
granges(vcf)$FILTER=='PASS']) # quality filter
barplot(sapply(delly.vcf,length))
# Remove MtDNA variants
delly.vcf <- lapply(delly.vcf, function(vcf) {
if (length(vcf)==0) return(vcf)
return(vcf[seqnames(vcf) %in% c("I","II","III","IV","V","X")])
})
# Make tables
delly.tables <- lapply(delly.vcf, function(vcf) {
tmp <- data.frame(CHR1 = seqnames(granges(vcf)),
POS1 = start(granges(vcf)),
CHR2 = info(vcf)$CHR2,
POS2 = info(vcf)$END,
READS = info(vcf)$PE,
TYPE = info(vcf)$SVTYPE)
rownames(tmp) <- names(vcf)
return(tmp)
})
# 2. Filter out telomeric stuff etc
# Filter out telomeric stuff
# upload genome and get chromosome sizes
url <- 'ftp://ftp.ensembl.org/pub/release-96/fasta/caenorhabditis_elegans/dna/Caenorhabditis_elegans.WBcel235.dna_sm.toplevel.fa.gz'
download.file(url = url, destfile = 'Caenorhabditis_elegans.WBcel235.dna.toplevel.fa.gz', method = "auto", quiet=FALSE)
WBcel235 <- readDNAStringSet("Caenorhabditis_elegans.WBcel235.dna.toplevel.fa.gz") # get worm reference genome
chr_sizes <- width(WBcel235)
names(chr_sizes) <- c("I","II","III","IV","MtDNA","V","X")
genome_size = sum(as.numeric(chr_sizes))
# telomeres
telomere <- matrix(1,nrow=6,ncol=4,dimnames=list(c("I","II","III","IV","V","X"),c("l.start","l.end","r.start","r.end")))
telomere[,2] <- c(436,400,200,47500,700,5000)
telomere[,3] <- c(15060000,15277300,13781900,
17492000,20923800,17718700)
telomere[,4] <- chr_sizes[-5]
telomere.delly <- list()
# get rid of variants intersecting with telomeres
for (x in names(delly.tables)) {
bad <- NULL
if (nrow(delly.tables[[x]])==0 || is.na(delly.tables[[x]])) next
for (j in 1:nrow(delly.tables[[x]])) {
if (delly.tables[[x]][j,2] < telomere[as.character(delly.tables[[x]][j,1]),2] ||
delly.tables[[x]][j,4] > telomere[as.character(delly.tables[[x]][j,3]),3])
bad <- c(bad,j)
}
if (length(bad)>0) {
telomere.delly[[x]] <- delly.tables[[x]][bad,]
delly.tables[[x]] <- delly.tables[[x]][-bad,]
print(c("telomeres",length(bad),x))
}
}
dimensions_filt <- sapply(delly.tables,nrow)
# 3. Deduplicate breakpoints
# Special treatment for MA samples: they may be related across generations so shall not be compared against each other within same genotype
mut.acc <- intersect(names(CD2Mutant)[is.na(data$Mutagen[match(names(CD2Mutant),data$Sample)])],names(delly.tables))
all_genotypes <- data$Genotype.new[match(mut.acc, data$Sample)]
all_generations <- data$Generation[match(mut.acc, data$Sample)]
allSV <- data.frame()
for (x in names(delly.tables)) {
if(nrow(delly.tables[[x]]) == 0) next
allSV <- rbind(allSV,
data.frame(delly.tables[[x]],
name = x,
stringsAsFactors = F))
}
allSV[,1] <- as.character(allSV[,1])
allSV[,3] <- as.character(allSV[,3])
allSV[,2] <- as.numeric(allSV[,2])
allSV[,4] <- as.numeric(allSV[,4]) # 41643
allSV.mut <- allSV[!(allSV$name %in% mut.acc),] # 34039
delly.tables.dedup <- list()
for (worm in names(delly.tables)) {
if (worm %in% mut.acc) {
worm_genotype <- data$Genotype.new[match(worm, data$Sample)]
if (all_generations[match(worm,mut.acc)] > 1)
worms_to_compare <- setdiff(mut.acc[all_genotypes != worm_genotype | all_generations < 2],worm)
else worms_to_compare <- setdiff(mut.acc,worm)
allSV.compare <- allSV[allSV$name %in% worms_to_compare,]
reference <- rbind(allSV.mut, allSV.compare)
delly.tables.dedup[[worm]] <- filter.breakpoints(SV = delly.tables[[worm]], reference = reference)
} else {
delly.tables.dedup[[worm]] <- filter.breakpoints(SV = delly.tables[[worm]], reference = allSV[allSV$name != worm,])
}
print(worm)
}
dimensions_dedup <- sapply(delly.tables.dedup,nrow)
plot(dimensions_dedup,cex=0.2,main="numbers of SVs after deduplication of breakpoints")
# count 'em all
delly.filtered.bp.counts <- list()
for (i in seq_along(delly.tables.dedup)) {
rearr.counts <- vector("numeric",5)
names(rearr.counts) <- c("BND","DEL","INV","DUP","ALL")
if (nrow(delly.tables.dedup[[i]]) < 1) {
delly.filtered.bp.counts[[i]] <- rearr.counts
next
}
if (is.na(delly.tables.dedup[[i]])) {
delly.filtered.bp.counts[[i]] <- NA
next
}
rearr.counts[1] <- sum(delly.tables.dedup[[i]]$TYPE == 'BND')
rearr.counts[2] <- sum(delly.tables.dedup[[i]]$TYPE == 'DEL')
rearr.counts[3] <- sum(delly.tables.dedup[[i]]$TYPE == 'INV')
rearr.counts[4] <- sum(delly.tables.dedup[[i]]$TYPE == 'DUP')
rearr.counts[5] <- sum(rearr.counts[1:4])
delly.filtered.bp.counts[[i]] <- rearr.counts
}
names(delly.filtered.bp.counts) <- names(delly.tables.dedup)
# visualize class sizes
barplot(colSums(do.call("rbind",delly.filtered.bp.counts)))
# compare to non-bp deduplication
barplot(colSums(do.call("rbind",delly.filtcounts)))
# size filter
barplot(sapply(delly.tables.dedup, nrow))
for (i in 1:length(delly.tables.dedup)) {
ind <- which(as.character(delly.tables.dedup[[i]][,1])==as.character(delly.tables.dedup[[i]][,3]) &
(as.numeric(delly.tables.dedup[[i]][,4])-as.numeric(delly.tables.dedup[[i]][,2])<400))
if (length(ind)>0)
delly.tables.dedup[[i]] <- delly.tables.dedup[[i]][-ind,,drop=F]
}
barplot(sapply(delly.tables.dedup, nrow))
# 4. Now make sure that DELs and TDs are actually DELs and TDs (get them a p-value)
# Will need the paths to BigWig and bamstats files for each of the samples which have any deletions or tandem duplications.
# bamstats files were acuired as
# samtools idxstats sample.bam > sample.stat.dat
PATHTOBW <- 'path/to/bw/files'
PATHTOBAMSTATS <- 'path/to/bam/stats/files'
ref.reads1 <- 44773320 # overall number of mapped reads in reference genome (CD0001b)
ref.reads2 <- 31427593 # overall number of mapped reads in reference genome (CD0850b)
# Check TD and DEL, deduplicate
set1 <- names(CD2Mutant)[1:(match('CD0683b',names(CD2Mutant))-1)]
for (worm in names(delly.tables.dedup)[794:length(delly.tables.dedup)]) {
if (worm %in% set1) {
ref.reads <- ref.reads1
ref.worm <- 'CD0001b'
}
else {
ref.reads <- ref.reads2
ref.worm <- 'CD0850b'
}
# upload stats files to get the number of mapped reads in the sample of interest
if (nrow(delly.tables.dedup[[worm]]) == 0) next
file <- paste(PATHTOBAMSTATS,worm,".stat.dat",sep="")
alt.reads <- sum(read.table(file)$V3[1:6])
r.ratio <- ref.reads / alt.reads
# get the deletions
dels <- delly.tables.dedup[[worm]][delly.tables.dedup[[worm]]$TYPE=="DEL",]
if (nrow(dels)!=0) {
goodness <- sapply(1:nrow(dels),function(j) {
big.ranges <- c(as.numeric(as.character(dels[j,2])),as.numeric(as.character(dels[j,4])))
chr <- as.character(dels[j,1])
if (big.ranges[2]-big.ranges[1]<100000) {
unit <- 10**round(log10(big.ranges[2]-big.ranges[1])-1)
if (big.ranges[2]+unit > telomere[chr,'r.start']) big.ranges[2] <- telomere[chr,'r.start'] - unit
if (big.ranges[1]-unit < telomere[chr,'l.end']) big.ranges[1] <- telomere[chr,'l.end'] + unit
big.ranges <- GRanges(seqnames = chr, ranges = IRanges(start=big.ranges[1]-unit, end=big.ranges[2]+unit))
x <- seq(from=start(big.ranges), to=end(big.ranges), by = unit/10)
region <- rtracklayer::import(paste0(PATHTOBW,'/',worm,'.merged.bw'),which=big.ranges)
region.ref <- rtracklayer::import(paste0(PATHTOBW,'/',ref.worm,".merged.bw"),which=big.ranges)
bins <- GRanges(seqnames=dels[j,1],
ranges=IRanges(start=x[-length(x)]+1,end=x[-1]),
seqinfo=seqinfo(region))
numvar <- mcolAsRleList(x=region,varname="score")
numvar.ref <- mcolAsRleList(x=region.ref,varname="score")
numvar.ref <- numvar.ref[names(numvar)]
points <- as.numeric(binnedAverage(bins,numvar,varname="score",na.rm=T)$score) + 0.1
points[is.na(points)] <- 1
points.ref <- as.numeric(binnedAverage(bins,numvar.ref,varname="score")$score) + 0.1
points.ref[is.na(points.ref)] <- 1
x <- x[-length(x)]
logfold <- log(points / points.ref * r.ratio)
normal = c(1:10,(length(logfold)-9):length(logfold))
odd = c(10:(length(logfold)-10))
if (length(which(is.nan(points)))>0) {
print(c("NaN points!!!",file))
points.ref <- points.ref[-which(points=="NaN")]
normal <- setdiff(normal,which(points=="NaN"))
odd <- setdiff(odd,which(points=="NaN"))
x <- x[-which(points=="NaN")]
points <- points[-which(points=="NaN")]
}
if (length(which(is.na(points.ref)))>0) {
print(c("NA points in ref!!!",file))
normal <- setdiff(normal,which(is.na(points.ref)))
odd <- setdiff(odd,which(is.na(points.ref)))
x <- x[-which(is.na(points.ref))]
points <- points[-which(is.na(points.ref))]
points.ref <- points.ref[-which(is.na(points.ref))]
}
logfold <- log(points / points.ref * r.ratio)
if (length(logfold)==0) return(NA)
return(wilcox.test(logfold[normal], logfold[odd], alternative="greater")$p.value)
}
else {
unit <- 10**round(log10(big.ranges[2]-big.ranges[1]) - 1)
if (big.ranges[2]+unit > telomere[chr,'r.start']) big.ranges[2] <- telomere[chr,'r.start'] - unit
if (big.ranges[1]-unit < telomere[chr,'l.end']) big.ranges[1] <- telomere[chr,'l.end'] + unit
big.ranges <- GRanges(seqnames = chr, ranges = IRanges(start=big.ranges[1]-unit, end=big.ranges[2]+unit))
x <- seq(from=start(big.ranges), to=end(big.ranges), by = unit/10)
region <- rtracklayer::import(paste0(PATHTOBW,'/',worm,'.merged.bw'),which=big.ranges)
region.ref <- rtracklayer::import(paste0(PATHTOBW,'/',ref.worm,".merged.bw"),which=big.ranges)
bins <- GRanges(seqnames=dels[j,1],
ranges=IRanges(start=x[-length(x)]+1,end=x[-1]),
seqinfo=seqinfo(region))
numvar <- mcolAsRleList(x=region,varname="score")
numvar.ref <- mcolAsRleList(x=region.ref,varname="score")
numvar.ref <- numvar.ref[names(numvar)]
points <- as.numeric(binnedAverage(bins,numvar,varname="score",na.rm=T)$score) + 0.1
points[is.na(points)] <- 1
points.ref <- as.numeric(binnedAverage(bins,numvar.ref,varname="score")$score) + 0.1
points.ref[is.na(points.ref)] <- 1
if (length(which(is.nan(points)))>0) {
print(c("NaN points!!!",file))
points.ref <- points.ref[-which(points=="NaN")]
points <- points[-which(points=="NaN")]
}
if (length(which(is.nan(points.ref)))>0) {
print(c("NaN points in ref!!!",file))
points <- points[-which(points.ref=="NaN")]
points.ref <- points.ref[-which(points.ref=="NaN")]
}
logfold <- log(points / points.ref * r.ratio)
return(wilcox.test(logfold,mu=0,alternative = 'less')$p.value)
}
})
}
else goodness <- NULL
del.td.pvalue <- rep(NA,nrow(delly.tables.dedup[[worm]]))
del.td.pvalue[delly.tables.dedup[[worm]][,'TYPE']=="DEL"] <- as.numeric(goodness)
delly.tables.dedup[[worm]]$del.td.pvalue <- del.td.pvalue
# get the deletions
tds <- delly.tables.dedup[[worm]][delly.tables.dedup[[worm]]$TYPE=="DUP",]
if (nrow(tds)!=0) {
goodness <- sapply(1:nrow(tds),function(j) {
big.ranges <- c(as.numeric(as.character(tds[j,2])),as.numeric(as.character(tds[j,4])))
chr <- as.character(tds[j,1])
if (big.ranges[2]-big.ranges[1]<100000) {
unit <- 10**round(log10(big.ranges[2]-big.ranges[1])-1)
if (big.ranges[2]+unit > telomere[chr,'r.start']) big.ranges[2] <- telomere[chr,'r.start'] - unit
if (big.ranges[1]-unit < telomere[chr,'l.end']) big.ranges[1] <- telomere[chr,'l.end'] + unit
big.ranges <- GRanges(seqnames = chr, ranges = IRanges(start=big.ranges[1]-unit, end=big.ranges[2]+unit))
x <- seq(from=start(big.ranges), to=end(big.ranges), by = unit/10)
region <- rtracklayer::import(paste0(PATHTOBW,'/',worm,'.merged.bw'),which=big.ranges)
region.ref <- rtracklayer::import(paste0(PATHTOBW,'/',ref.worm,".merged.bw"),which=big.ranges)
bins <- GRanges(seqnames=tds[j,1],
ranges=IRanges(start=x[-length(x)]+1,end=x[-1]),
seqinfo=seqinfo(region))
numvar <- mcolAsRleList(x=region,varname="score")
numvar.ref <- mcolAsRleList(x=region.ref,varname="score")
numvar.ref <- numvar.ref[names(numvar)]
points <- as.numeric(binnedAverage(bins,numvar,varname="score",na.rm=T)$score) + 0.1
points[is.na(points)] <- 1
points.ref <- as.numeric(binnedAverage(bins,numvar.ref,varname="score")$score) + 0.1
points.ref[is.na(points.ref)] <- 1
x <- x[-length(x)]
logfold <- log(points / points.ref * r.ratio)
normal = c(1:10,(length(logfold)-9):length(logfold))
odd = c(10:(length(logfold)-10))
if (length(which(is.nan(points)))>0) {
print(c("NaN points!!!",file))
points.ref <- points.ref[-which(points=="NaN")]
normal <- setdiff(normal,which(points=="NaN"))
odd <- setdiff(odd,which(points=="NaN"))
x <- x[-which(points=="NaN")]
points <- points[-which(points=="NaN")]
}
if (length(which(is.na(points.ref)))>0) {
print(c("NA points in ref!!!",file))
normal <- setdiff(normal,which(is.na(points.ref)))
odd <- setdiff(odd,which(is.na(points.ref)))
x <- x[-which(is.na(points.ref))]
points <- points[-which(is.na(points.ref))]
points.ref <- points.ref[-which(is.na(points.ref))]
}
logfold <- log(points / points.ref * r.ratio)
if (length(logfold)==0) return(NA)
return(wilcox.test(logfold[normal], logfold[odd], alternative="less")$p.value)
}
else {
unit <- 10**round(log10(big.ranges[2]-big.ranges[1]) - 1)
if (big.ranges[2]+unit > telomere[chr,'r.start']) big.ranges[2] <- telomere[chr,'r.start'] - unit
if (big.ranges[1]-unit < telomere[chr,'l.end']) big.ranges[1] <- telomere[chr,'l.end'] + unit
big.ranges <- GRanges(seqnames = chr, ranges = IRanges(start=big.ranges[1]-unit, end=big.ranges[2]+unit))
x <- seq(from=start(big.ranges), to=end(big.ranges), by = unit/10)
region <- rtracklayer::import(paste0(PATHTOBW,'/',worm,'.merged.bw'),which=big.ranges)
region.ref <- rtracklayer::import(paste0(PATHTOBW,'/',ref.worm,".merged.bw"),which=big.ranges)
bins <- GRanges(seqnames=tds[j,1],
ranges=IRanges(start=x[-length(x)]+1,end=x[-1]),
seqinfo=seqinfo(region))
numvar <- mcolAsRleList(x=region,varname="score")
numvar.ref <- mcolAsRleList(x=region.ref,varname="score")
numvar.ref <- numvar.ref[names(numvar)]
points <- as.numeric(binnedAverage(bins,numvar,varname="score",na.rm=T)$score)+0.1
points[is.na(points)] <- 1
points.ref <- as.numeric(binnedAverage(bins,numvar.ref,varname="score")$score)+0.1
points.ref[is.na(points.ref)] <- 1
if (length(which(is.nan(points)))>0) {
print(c("NaN points!!!",file))
points.ref <- points.ref[-which(points=="NaN")]
points <- points[-which(points=="NaN")]
}
if (length(which(is.nan(points.ref)))>0) {
print(c("NaN points in ref!!!",file))
points <- points[-which(points.ref=="NaN")]
points.ref <- points.ref[-which(points.ref=="NaN")]
}
logfold <- log(points / points.ref * r.ratio)
return(wilcox.test(logfold,mu=0,alternative='greater')$p.value)
}
})
}
else goodness <- NULL
if (!('del.td.pvalue' %in% colnames(delly.tables.dedup[[worm]]))) {
del.td.pvalue <- rep(NA,nrow(delly.tables.dedup[[worm]]))
del.td.pvalue[delly.tables.dedup[[worm]][,'TYPE']=="DUP"] <- as.numeric(goodness)
delly.tables.dedup[[worm]]$del.td.pvalue <- del.td.pvalue
}
else {
delly.tables.dedup[[worm]]$del.td.pvalue[delly.tables.dedup[[worm]][,'TYPE']=="DUP"] <- as.numeric(goodness)
}
print(worm)
}
# p-values - check NAs
for (worm in names(delly.tables.dedup)) {
dels <- which(delly.tables.dedup[[worm]]$TYPE=="DUP")
tds <- which(delly.tables.dedup[[worm]]$TYPE=="DEL")
if (length(dels)>0) {
bad.del <- which(is.na(delly.tables.dedup[[worm]][dels,7]))
if (length(bad.del)>0) delly.tables.dedup[[worm]] <- delly.tables.dedup[[worm]][-dels[bad.del],]
}
if (length(tds)>0) {
bad.td <- which(is.na(delly.tables.dedup[[worm]][tds,7]))
if (length(bad.td)>0) delly.tables.dedup[[worm]] <- delly.tables.dedup[[worm]][-tds[bad.td],]
}
}
delly.tables <- delly.tables.dedup[sapply(delly.tables.dedup,nrow)>0]
barplot(sapply(delly.tables.dedup,nrow)) # no difference
# do multiple testing correction - Benjamini-Hochberg
pval.del <- NULL
pval.td <- NULL
for (x in names(delly.tables.dedup)) {
pval.del <- c(pval.del,delly.tables.dedup[[x]][delly.tables.dedup[[x]]$TYPE=="DEL",7])
pval.td <- c(pval.td,delly.tables.dedup[[x]][delly.tables.dedup[[x]]$TYPE=="DUP",7])
}
pval.del.adj <- p.adjust(pval.del,method="BH")
pval.td.adj <- p.adjust(pval.td,method="BH")
for (x in names(delly.tables.dedup)) {
td.length <- length(which(delly.tables.dedup[[x]]$TYPE=="DUP"))
del.length <- length(which(delly.tables.dedup[[x]]$TYPE=="DEL"))
if (del.length>0) {
delly.tables.dedup[[x]]$del.td.pvalue[delly.tables.dedup[[x]]$TYPE=="DEL"] <- pval.del.adj[1:del.length]
pval.del.adj <- pval.del.adj[-c(1:del.length)]
}
if (td.length>0) {
delly.tables.dedup[[x]]$del.td.pvalue[delly.tables.dedup[[x]]$TYPE=="DUP"] <- pval.td.adj[1:td.length]
pval.td.adj <- pval.td.adj[-c(1:td.length)]
}
}
PATHTOCLUST='/path/where/to/write/clustered/tables'
# CLUSTER
source("classification_script.R")
for (worm in names(delly.tables.dedup)) {
d <- delly.tables.dedup[[worm]]
if (nrow(d) == 0) next
output_file = paste(PATHTOCLUST,'/',worm,".clust_mat",sep="")
d[,1] = as.character(d[,1]) # chomosomes
d[,3] = as.character(d[,3]) # chomosomes
d[,2] = as.numeric(as.character(d[,2]))
d[,4] = as.numeric(as.character(d[,4]))
d[,6] = as.character(d[,6])
if (nrow(d) == 1) {
ct = 1
# Get the footprint info
pos = c(d[,2], d[,4])
chrs = c(d[,1], d[,3])
res = get_footprints(pos, chrs)
footprint_idx = sprintf("%s.chr%s.%s", c(ct, ct), chrs, res$footprint_idx)
footprint_bounds = res$footprint_bounds
write.table(
data.frame(
d,
clust = ct,
clust_size = sapply(ct, function(x) sum(x == ct)),
fp_l = footprint_idx[1:nrow(d)],
fp_h = footprint_idx[-(1:nrow(d))]
),
output_file,
quote = F,
sep = "\t"
)
} else {
ct = clust_rgs_new(d)$cutree
# Get the footprint info
pos = c(d[,2], d[,4])
chrs = c(d[,1], d[,3])
res = get_footprints(pos, chrs)
footprint_idx = sprintf("%s.chr%s.%s", c(ct, ct), chrs, res$footprint_idx)
footprint_bounds = res$footprint_bounds
write.table(
data.frame(
d,
clust = ct,
clust_size = sapply(ct, function(x) sum(x == ct)),
fp_l = footprint_idx[1:nrow(d)],
fp_h = footprint_idx[-(1:nrow(d))]
),
output_file,
quote = F,
sep = "\t"
)
}
}
delly.tables.dedup <- delly.tables.dedup[sapply(delly.tables.dedup,nrow)>0]
# reading reclustered SVs
SVclust <- list()
for (worm in names(delly.tables.dedup))
{
if(nrow(delly.tables.dedup[[worm]]) > 0) {
file = paste(PATHTOCLUST,'/',worm,".clust_mat",sep="")
SVclust[[worm]] <- read.table(file=file, header=T, sep = "\t")
}
}
# add sample name to all SV tables
for (worm in names(SVclust)){
SVclust[[worm]] <- cbind(SVclust[[worm]][,1:10],Sample=as.character(rep(worm,nrow(SVclust[[worm]]))),
del.td.pvalue = delly.tables.dedup[[worm]]$del.td.pvalue)
}
# Assessing types of clusters
rearr.count.final.dedup <- list()
for (i in seq_along(SVclust)) {
SVclust[[i]] <- cbind(SVclust[[i]],clust.type=as.character(rep("some",nrow(SVclust[[i]]))))
SVclust[[i]]$clust.type <- as.character(SVclust[[i]]$clust.type)
rearr.counts <- vector("numeric",8)
names(rearr.counts) <- c("TD","DEL","INV","COMPLEX","TRSL","INTCHR","FOLDBACK","MOVE") # TRSL = copypaste, MOVE = TRSL with deletion
for (j in unique(SVclust[[i]]$clust)) {
which(SVclust[[i]]$clust==j) -> clust_ind
bp.types <- as.character(SVclust[[i]]$TYPE[clust_ind])
# 2 INTERSECTING pairs of breakpoints DEL, DEL, TD - translocation
# any >2 pairs - complex
if (length(clust_ind)>2) {
if (length(clust_ind)==3 &
(length(which(bp.types=="DEL"))==2) &
("DUP" %in% bp.types)) {
rearr.counts["MOVE"] = rearr.counts["MOVE"] + 1
SVclust[[i]]$clust.type[clust_ind] <- rep("MOVE",length(clust_ind))
} else {
rearr.counts["COMPLEX"] = rearr.counts["COMPLEX"] + 1
SVclust[[i]]$clust.type[clust_ind] <- rep("COMPLEX",length(clust_ind))
}
}
# 2 pairs of breakpoints: inversions, interchromosomal
if (length(clust_ind)==2) {
if (length(setdiff(c("INV","INV"),bp.types))==0) {
rearr.counts["INV"] = rearr.counts["INV"] + 1
SVclust[[i]]$clust.type[clust_ind] <- c("INV","INV")
}
else if (length(setdiff(bp.types, c("BND","BND")))==0) {
SVclust[[i]]$clust.type[clust_ind] <- c("INTCHR","INTCHR")
rearr.counts["INTCHR"] = rearr.counts["INTCHR"] + 1
}
else if (length(setdiff(bp.types,c("DUP","DEL")))==0) {
dist1 <- SVclust[[i]]$POS1[clust_ind][2]-SVclust[[i]]$POS1[clust_ind][1]
dist2 <- SVclust[[i]]$POS2[clust_ind][2]-SVclust[[i]]$POS2[clust_ind][1]
dist <- SVclust[[i]]$POS2[clust_ind][2]-SVclust[[i]]$POS1[clust_ind][1]
if ((abs(dist1)<(0.1*dist) & bp.types[which.max(SVclust[[i]]$POS2[clust_ind])]=="DUP") ||
(abs(dist2)<(0.2*dist) & bp.types[1]=="DUP") ||
(abs(dist1)<(0.1*dist) & abs(dist2)<(0.1*dist))) {
SVclust[[i]]$clust.type[clust_ind] <- rep("TRSL",2)
rearr.counts["TRSL"] = rearr.counts["TRSL"] + 1
} else {
SVclust[[i]]$clust.type[clust_ind] <- c("COMPLEX","COMPLEX")
rearr.counts["COMPLEX"] = rearr.counts["COMPLEX"] + 1
}
}
else if (length(which(bp.types=="DEL"))==2) {
if (length(which(SVclust[[i]][clust_ind,12]>0.05))==0) {
SVclust[[i]]$clust.type[clust_ind] <- c("COMPLEX","COMPLEX")
rearr.counts["COMPLEX"] = rearr.counts["COMPLEX"] + 1
}
else if (length(which(SVclust[[i]][clust_ind,12]>0.05))==1) {
SVclust[[i]]$clust.type[clust_ind] <- c("DEL","DEL")
rearr.counts["DEL"] = rearr.counts["DEL"] + 1
}
}
else if (length(which(bp.types=="DUP"))==2) {
if (length(which(SVclust[[i]][clust_ind,12]>0.05))==0) {
SVclust[[i]]$clust.type[clust_ind] <- c("COMPLEX","COMPLEX")
rearr.counts["COMPLEX"] = rearr.counts["COMPLEX"] + 1
}
else if (length(which(SVclust[[i]][clust_ind,12]>0.05))==1) {
SVclust[[i]]$clust.type[clust_ind] <- c("TD","TD")
rearr.counts["TD"] = rearr.counts["TD"] + 1
}
}
else {
rearr.counts["COMPLEX"] = rearr.counts["COMPLEX"] + 1
SVclust[[i]]$clust.type[clust_ind] <- c("COMPLEX","COMPLEX")
}
}
if (length(clust_ind)==1) {
if (bp.types=="DUP" && length(which(SVclust[[i]]$del.td.pvalue[clust_ind]>0.05))==0) {
SVclust[[i]]$clust.type[clust_ind] <- "TD"
rearr.counts["TD"] = rearr.counts["TD"] + 1
}
if (bp.types=="DEL" && length(which(SVclust[[i]]$del.td.pvalue[clust_ind]>0.05))==0)
{
rearr.counts["DEL"] = rearr.counts["DEL"] + 1
SVclust[[i]]$clust.type[clust_ind] <- "DEL"
}
if (bp.types=="INV")
{
rearr.counts["FOLDBACK"] = rearr.counts["FOLDBACK"] + 1
SVclust[[i]]$clust.type[clust_ind] <- "FOLDBACK"
}
if (bp.types=="BND") {
rearr.counts["INTCHR"] = rearr.counts["INTCHR"] + 1
SVclust[[i]]$clust.type[clust_ind] <- "INTCHR"
}
}
}
print(i)
rearr.count.final.dedup[[i]] <- rearr.counts
}
names(rearr.count.final.dedup) <- names(SVclust)
# visualize class sizes
colSums(do.call("rbind",delly.filtcounts))
# TD DEL INV COMPLEX TRSL INTCHR FOLDBACK MOVE ALL
# 150 167 99 128 32 125 90 1 792
colSums(do.call("rbind",rearr.count.final.dedup))
# TD DEL INV COMPLEX TRSL INTCHR FOLDBACK MOVE ALL
# 767 604 257 320 100 337 265 32 2682
delly.filtcounts <- rearr.count.final.dedup
SVclust -> delly.SVclust
delly.tables.dedup <- delly.tables.dedup[sapply(delly.tables.dedup,nrow)>0]
for (worm in names(delly.tables.dedup)) {
if ('del.td.pvalue' %in% colnames(delly.tables.dedup[[worm]])) next
delly.tables.dedup[[worm]]$del.td.pvalue <- NA
}
SVclust <- SVclust[sapply(SVclust,nrow)>0]
for (worm in names(SVclust)) {
if ('del.td.pvalue' %in% colnames(SVclust[[worm]])) next
SVclust[[worm]]$del.td.pvalue <- NA
}
save(delly.SVclust, delly.tables.dedup, delly.filtcounts, file='filtered_SV.RData')
filt.delly.vcf <- lapply(names(delly.vcf), function(z) delly.vcf[[z]][rownames(delly.tables.dedup[[z]])])
names(filt.delly.vcf) <- names(delly.vcf)
save(delly.vcf, file = 'Deduplicated_and_filtered_DELLY_vcfs.Rds')
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/qrFitted.R
\name{predict.cdfqr}
\alias{predict.cdfqr}
\alias{fitted.cdfqr}
\title{Methods for Cdfqr Objects}
\usage{
\method{predict}{cdfqr}(
object,
newdata = NULL,
type = c("full", "mu", "sigma", "theta", "one", "zero"),
quant = 0.5,
...
)
\method{fitted}{cdfqr}(
object,
type = c("full", "mu", "sigma", "theta", "one", "zero"),
plot = FALSE,
...
)
}
\arguments{
\item{object}{A cdfqr model fit object}
\item{newdata}{Optional. A data frame in which to look for variables with which to predict. If not provided, the fitted values are returned}
\item{type}{A character that indicates whether the full model prediction/fitted values are needed, or values for the `mu` and `sigma` submodel only.}
\item{quant}{A number or a numeric vector (must be in (0, 1)) to specify the quantile(s) of the predicted value (when `newdata` is provided, and predicted values for responses are required). The default is to use median to predict response values.}
\item{...}{currently ignored}
\item{plot}{if a plot is needed.}
}
\description{
Methods for obtaining the fitted/predicted values for a fitted cdfqr object.
}
\examples{
data(cdfqrExampleData)
fit <- cdfquantreg(crc99 ~ vert | confl, 't2','t2', data = JurorData)
plot(predict(fit))
plot(predict(fit))
}
| /man/predict.cdfqr.Rd | no_license | cran/cdfquantreg | R | false | true | 1,351 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/qrFitted.R
\name{predict.cdfqr}
\alias{predict.cdfqr}
\alias{fitted.cdfqr}
\title{Methods for Cdfqr Objects}
\usage{
\method{predict}{cdfqr}(
object,
newdata = NULL,
type = c("full", "mu", "sigma", "theta", "one", "zero"),
quant = 0.5,
...
)
\method{fitted}{cdfqr}(
object,
type = c("full", "mu", "sigma", "theta", "one", "zero"),
plot = FALSE,
...
)
}
\arguments{
\item{object}{A cdfqr model fit object}
\item{newdata}{Optional. A data frame in which to look for variables with which to predict. If not provided, the fitted values are returned}
\item{type}{A character that indicates whether the full model prediction/fitted values are needed, or values for the `mu` and `sigma` submodel only.}
\item{quant}{A number or a numeric vector (must be in (0, 1)) to specify the quantile(s) of the predicted value (when `newdata` is provided, and predicted values for responses are required). The default is to use median to predict response values.}
\item{...}{currently ignored}
\item{plot}{if a plot is needed.}
}
\description{
Methods for obtaining the fitted/predicted values for a fitted cdfqr object.
}
\examples{
data(cdfqrExampleData)
fit <- cdfquantreg(crc99 ~ vert | confl, 't2','t2', data = JurorData)
plot(predict(fit))
plot(predict(fit))
}
|
### Reduce Data
latlon <- read.csv("gridlocs.dat")
files <- list.files("temps")
filenum <- as.numeric( sub(".dat",files,repl="") )
L <- length(files)
ord <- order(filenum)
i <- 0
test <- read.table('temps/0.dat',skip=8,header=T)
n <- nrow(test)
# Assuming Years are
uyears <- unique( test$YEAR )
nyears <- length(uyears)
umonths <- 1:12
nmonths <- 12
TT <- nyears * nmonths
Y <- as.list(n)
for (f in files[ord]) {
i <- i + 1
dat <- read.table(paste0('temps/',f),skip=8,header=T)
lon <- latlon[i,1]
lat <- latlon[i,2]
fbig <- matrix(0, TT, 5)
colnames(fbig) <- c("year","mo","lat","lon","C")
j <- 0
for (yr in uyears) {
for (mo in umonths) {
j <- j + 1
fbig[j,1] <- yr
fbig[j,2] <- mo
fbig[j,3] <- lat
fbig[j,4] <- lon
ind <- as.logical( (dat$YEAR == yr) * (dat$MO == mo) )
fbig[j,5] <- mean(dat$T10M[which(ind)])
}
}
Y[[i]] <- fbig
cat("\rProgress: ", i, "/",L)
}
### Visualize
library(LatticeKrig) # quilt.plot
library(maps) # map()
view <- function(y,mo,yr) {
M <- matrix(0,L,ncol(y[[1]]))
colnames(M) <- colnames(y[[1]])
i <- 0
for (yy in y) {
i <- i + 1
ind <- as.logical((yy[,"year"]==yr) * (yy[,"mo"]==mo))
M[i,] <- yy[ind,]
}
lon.up <- -114#-120
lon.lo <- -124.5#-122
lat.up <- 42#37
lat.lo <- 32.5#35
quilt.plot(M[,"lon"],M[,"lat"],M[,"C"], #lon,lat,val
xlim=c(lon.lo-1,lon.up+1), ylim=c(lat.lo-1,lat.up+1),
bty="n",fg="grey",breaks=seq(0,32,len=101),main=paste0(mo,"/",yr),
col= colorRampPalette(c('dark blue','grey90','dark red'))(100))
map('county',add=T,lwd=2,col='pink')
map('state',add=T,lwd=2,col='grey40')
M
}
#par(mfrow=c(5,4),mar=c(4,4,1,1))
par.opts <- par()
par(mfrow=c(2,3),mar=c(4,4,1,1))
for (yr in c(1985,1989,1994,1999,2001,2004)) view(Y,6,yr)
par(mfrow=c(1,1))
Yout <- array(0,c(L,TT,5))
for (i in 1:L) {
Yout[i,,] <- Y[[i]]
}
save(Yout,file="Y.RData")
system("cp Y.RData ../")
ind <- 1:TT%%12%%7==0 & 1:TT%%12!=0
loc <- 13
plot(Yout[loc,,5],type='o',pch=20,ylim=c(0,35),
cex=ifelse(ind,2,1),ylab=bquote({ }^o~"C"),
col=ifelse(ind,'red','grey'),
fg='grey',bty='l',main="Temperature over Years",xaxt='n')
axis(1,labels=1985:2004,at=which(ind),fg='grey')
lines((1:TT)[which(ind)],Yout[loc,ind,5],col='red',type='o',pch=20)
| /project/bnp_spatialDP/data/retrieve/reduce.R | no_license | stjordanis/bnp_hw | R | false | false | 2,328 | r | ### Reduce Data
latlon <- read.csv("gridlocs.dat")
files <- list.files("temps")
filenum <- as.numeric( sub(".dat",files,repl="") )
L <- length(files)
ord <- order(filenum)
i <- 0
test <- read.table('temps/0.dat',skip=8,header=T)
n <- nrow(test)
# Assuming Years are
uyears <- unique( test$YEAR )
nyears <- length(uyears)
umonths <- 1:12
nmonths <- 12
TT <- nyears * nmonths
Y <- as.list(n)
for (f in files[ord]) {
i <- i + 1
dat <- read.table(paste0('temps/',f),skip=8,header=T)
lon <- latlon[i,1]
lat <- latlon[i,2]
fbig <- matrix(0, TT, 5)
colnames(fbig) <- c("year","mo","lat","lon","C")
j <- 0
for (yr in uyears) {
for (mo in umonths) {
j <- j + 1
fbig[j,1] <- yr
fbig[j,2] <- mo
fbig[j,3] <- lat
fbig[j,4] <- lon
ind <- as.logical( (dat$YEAR == yr) * (dat$MO == mo) )
fbig[j,5] <- mean(dat$T10M[which(ind)])
}
}
Y[[i]] <- fbig
cat("\rProgress: ", i, "/",L)
}
### Visualize
library(LatticeKrig) # quilt.plot
library(maps) # map()
view <- function(y,mo,yr) {
M <- matrix(0,L,ncol(y[[1]]))
colnames(M) <- colnames(y[[1]])
i <- 0
for (yy in y) {
i <- i + 1
ind <- as.logical((yy[,"year"]==yr) * (yy[,"mo"]==mo))
M[i,] <- yy[ind,]
}
lon.up <- -114#-120
lon.lo <- -124.5#-122
lat.up <- 42#37
lat.lo <- 32.5#35
quilt.plot(M[,"lon"],M[,"lat"],M[,"C"], #lon,lat,val
xlim=c(lon.lo-1,lon.up+1), ylim=c(lat.lo-1,lat.up+1),
bty="n",fg="grey",breaks=seq(0,32,len=101),main=paste0(mo,"/",yr),
col= colorRampPalette(c('dark blue','grey90','dark red'))(100))
map('county',add=T,lwd=2,col='pink')
map('state',add=T,lwd=2,col='grey40')
M
}
#par(mfrow=c(5,4),mar=c(4,4,1,1))
par.opts <- par()
par(mfrow=c(2,3),mar=c(4,4,1,1))
for (yr in c(1985,1989,1994,1999,2001,2004)) view(Y,6,yr)
par(mfrow=c(1,1))
Yout <- array(0,c(L,TT,5))
for (i in 1:L) {
Yout[i,,] <- Y[[i]]
}
save(Yout,file="Y.RData")
system("cp Y.RData ../")
ind <- 1:TT%%12%%7==0 & 1:TT%%12!=0
loc <- 13
plot(Yout[loc,,5],type='o',pch=20,ylim=c(0,35),
cex=ifelse(ind,2,1),ylab=bquote({ }^o~"C"),
col=ifelse(ind,'red','grey'),
fg='grey',bty='l',main="Temperature over Years",xaxt='n')
axis(1,labels=1985:2004,at=which(ind),fg='grey')
lines((1:TT)[which(ind)],Yout[loc,ind,5],col='red',type='o',pch=20)
|
## The function reads the outcome-of-care-measures.csv file and returns a character
## vector (the name of the hospital) that has the ranking specified by the num
## argument, based on the mortality value for the specified outcome in that state.
##
## The function takes two arguments:
## - state : the 2-character abbreviated name of a state
## - outcome : outcome name (either "heart attack", "heart failure" or "pneumonia")
## - num : the ranking of a hospital (either "best", "worst", non-zero integer)
##
## Note: The function throws an error if either state or outcome is not valid.
##
## Handling ties: If there is a tie for the best hospital for a given outcome,
## then the hospital names should be sorted in alphabetical order and the first
## hospital in that set should be chosen (i.e. if hospitals “b”, “c”, and “f”
## are tied for best, then hospital “b” should be returned).
##
## Usage examples:
## ==============
## Example with best:
## > rankhospital("TX", "heart failure", "best")
## [1] "FORT DUNCAN MEDICAL CENTER"
##
## Example with 1st index:
## > rankhospital("TX", "heart failure", 1)
## [1] "FORT DUNCAN MEDICAL CENTER"
##
## Example with worst
## > rankhospital("TX", "heart failure", "worst")
## [1] "ETMC CARTHAGE"
##
## Example with negative index
## > rankhospital("TX", "heart failure", -1)
## [1] "ETMC CARTHAGE"
##
## Example with incorrect argument
## > rankhospital("TX", "hart failure", 1)
## Error in rankhospital("TX", "hart failure", 1) : invalid outcome
##
rankhospital <- function(state, outcome, num = "best") {
## Read outcome data
directory <- file.path("data", "rprog_data_ProgAssignment3-data")
input_data <- read.csv(file.path(directory, "outcome-of-care-measures.csv"),
colClasses = "character")
## Check that state and outcome are valid
avail_states <- unique(input_data$State)
if (! state %in% avail_states){
stop("invalid state")
}
if (! outcome %in% c("heart attack", "heart failure", "pneumonia")){
stop("invalid outcome")
}
## Based on the selected outcome find the best hospital
name_col <- 2
state_col <- 7
if (outcome == "heart attack"){
outcome_col <- 11
} else if (outcome == "heart failure"){
outcome_col <- 17
} else if (outcome == "pneumonia"){
outcome_col <- 23
}
# Convert to numeric and suppress warning for NAs
suppressWarnings(input_data[, outcome_col] <- as.numeric(input_data[, outcome_col]))
# Get only relevant columns
target_data <- input_data[, c(name_col, state_col, outcome_col)]
# Exclude rows with NAs
use <- complete.cases(target_data)
# Get columns for specified state
use_state <- target_data[, 2] == state
rel_data <- target_data[use & use_state, ]
# Rename columns for easier handling
names(rel_data) <- c("Hospital", "State", "Mortality")
# Order by ascending mortality and then by ascending hospital names
# For descending order add a '-' in front of the column data
index <- order(rel_data$Mortality, rel_data$Hospital)
sorted_data <- rel_data[index, ]
## Return hospital name in that state with the given rank 30-day death rate
if (num == "best"){
return(sorted_data[1, 1])
}
if (num == "worst"){
return(sorted_data[nrow(sorted_data), 1])
}
## If num is negative start counting from the bottom
if (num < 0){
num <- nrow(sorted_data) + 1 + num
}
## If the number is bigger than the number of rows or is zero return NA
if (abs(num) > nrow(sorted_data) || num == 0){
return(NA)
}
sorted_data[num, 1]
} | /Scripts/rankhospital.R | no_license | Ghost-8D/RStudio_repo | R | false | false | 3,762 | r | ## The function reads the outcome-of-care-measures.csv file and returns a character
## vector (the name of the hospital) that has the ranking specified by the num
## argument, based on the mortality value for the specified outcome in that state.
##
## The function takes two arguments:
## - state : the 2-character abbreviated name of a state
## - outcome : outcome name (either "heart attack", "heart failure" or "pneumonia")
## - num : the ranking of a hospital (either "best", "worst", non-zero integer)
##
## Note: The function throws an error if either state or outcome is not valid.
##
## Handling ties: If there is a tie for the best hospital for a given outcome,
## then the hospital names should be sorted in alphabetical order and the first
## hospital in that set should be chosen (i.e. if hospitals “b”, “c”, and “f”
## are tied for best, then hospital “b” should be returned).
##
## Usage examples:
## ==============
## Example with best:
## > rankhospital("TX", "heart failure", "best")
## [1] "FORT DUNCAN MEDICAL CENTER"
##
## Example with 1st index:
## > rankhospital("TX", "heart failure", 1)
## [1] "FORT DUNCAN MEDICAL CENTER"
##
## Example with worst
## > rankhospital("TX", "heart failure", "worst")
## [1] "ETMC CARTHAGE"
##
## Example with negative index
## > rankhospital("TX", "heart failure", -1)
## [1] "ETMC CARTHAGE"
##
## Example with incorrect argument
## > rankhospital("TX", "hart failure", 1)
## Error in rankhospital("TX", "hart failure", 1) : invalid outcome
##
rankhospital <- function(state, outcome, num = "best") {
## Read outcome data
directory <- file.path("data", "rprog_data_ProgAssignment3-data")
input_data <- read.csv(file.path(directory, "outcome-of-care-measures.csv"),
colClasses = "character")
## Check that state and outcome are valid
avail_states <- unique(input_data$State)
if (! state %in% avail_states){
stop("invalid state")
}
if (! outcome %in% c("heart attack", "heart failure", "pneumonia")){
stop("invalid outcome")
}
## Based on the selected outcome find the best hospital
name_col <- 2
state_col <- 7
if (outcome == "heart attack"){
outcome_col <- 11
} else if (outcome == "heart failure"){
outcome_col <- 17
} else if (outcome == "pneumonia"){
outcome_col <- 23
}
# Convert to numeric and suppress warning for NAs
suppressWarnings(input_data[, outcome_col] <- as.numeric(input_data[, outcome_col]))
# Get only relevant columns
target_data <- input_data[, c(name_col, state_col, outcome_col)]
# Exclude rows with NAs
use <- complete.cases(target_data)
# Get columns for specified state
use_state <- target_data[, 2] == state
rel_data <- target_data[use & use_state, ]
# Rename columns for easier handling
names(rel_data) <- c("Hospital", "State", "Mortality")
# Order by ascending mortality and then by ascending hospital names
# For descending order add a '-' in front of the column data
index <- order(rel_data$Mortality, rel_data$Hospital)
sorted_data <- rel_data[index, ]
## Return hospital name in that state with the given rank 30-day death rate
if (num == "best"){
return(sorted_data[1, 1])
}
if (num == "worst"){
return(sorted_data[nrow(sorted_data), 1])
}
## If num is negative start counting from the bottom
if (num < 0){
num <- nrow(sorted_data) + 1 + num
}
## If the number is bigger than the number of rows or is zero return NA
if (abs(num) > nrow(sorted_data) || num == 0){
return(NA)
}
sorted_data[num, 1]
} |
## Functions to get and set globally accessible variables
#' @include utils.R
NULL
# Global variable with all the data of a session
sharedData <- reactiveValues()
#' Get global data
#' @return Variable containing all data of interest
getData <- reactive(sharedData$data)
#' Get if history browsing is automatic
#' @return Boolean: is navigation of browser history automatic?
getAutoNavigation <- reactive(sharedData$autoNavigation)
#' Get number of cores to use
#' @return Numeric value with the number of cores to use
getCores <- reactive(sharedData$cores)
#' Get number of significant digits
#' @return Numeric value regarding the number of significant digits
getSignificant <- reactive(sharedData$significant)
#' Get number of decimal places
#' @return Numeric value regarding the number of decimal places
getPrecision <- reactive(sharedData$precision)
#' Get selected alternative splicing event's identifer
#' @return Alternative splicing event's identifier as a string
getEvent <- reactive(sharedData$event)
#' Get available data categories
#' @return Name of all data categories
getCategories <- reactive(names(getData()))
#' Get selected data category
#' @return Name of selected data category
getCategory <- reactive(sharedData$category)
#' Get data of selected data category
#' @return If category is selected, returns the respective data as a data frame;
#' otherwise, returns NULL
getCategoryData <- reactive(
if(!is.null(getCategory())) getData()[[getCategory()]])
#' Get selected dataset
#' @return List of data frames
getActiveDataset <- reactive(sharedData$activeDataset)
#' Get clinical data of the data category
#' @return Data frame with clinical data
getClinicalData <- reactive(getCategoryData()[["Clinical data"]])
#' Get junction quantification data
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return List of data frames of junction quantification
getJunctionQuantification <- function(category=getCategory()) {
if (!is.null(category)) {
data <- getData()[[category]]
match <- sapply(data, attr, "dataType") == "Junction quantification"
if (any(match)) return(data[match])
}
}
#' Get alternative splicing quantification of the selected data category
#' @return Data frame with the alternative splicing quantification
getInclusionLevels <- reactive(getCategoryData()[["Inclusion levels"]])
#' Get sample information of the selected data category
#' @return Data frame with sample information
getSampleInfo <- reactive(getCategoryData()[["Sample metadata"]])
#' Get data from global data
#' @param ... Arguments to identify a variable
#' @param sep Character to separate identifiers
#' @return Data from global data
getGlobal <- function(..., sep="_") sharedData[[paste(..., sep=sep)]]
#' Get the identifier of patients for a given category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Character vector with identifier of patients
getPatientId <- function(category = getCategory())
getGlobal(category, "patients")
#' Get the identifier of samples for a given category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Character vector with identifier of samples
getSampleId <- function(category = getCategory())
getGlobal(category, "samples")
#' Get the table of differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Data frame of differential analyses
getDifferentialAnalyses <- function(category = getCategory())
getGlobal(category, "differentialAnalyses")
#' Get the filtered table of differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Filtered data frame of differential analyses
getDifferentialAnalysesFiltered <- function(category = getCategory())
getGlobal(category, "differentialAnalysesFiltered")
#' Get highlighted events from differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Integer of indexes relative to a table of differential analyses
getDifferentialAnalysesHighlightedEvents <- function(category = getCategory())
getGlobal(category, "differentialAnalysesHighlighted")
#' Get plot coordinates for zooming from differential analyses of a data
#' category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Integer of X and Y axes coordinates
getDifferentialAnalysesZoom <- function(category = getCategory())
getGlobal(category, "differentialAnalysesZoom")
#' Get selected points in the differential analysis table of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Integer containing index of selected points
getDifferentialAnalysesSelected <- function(category = getCategory())
getGlobal(category, "differentialAnalysesSelected")
#' Get the table of differential analyses' survival data of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Data frame of differential analyses' survival data
getDifferentialAnalysesSurvival <- function(category = getCategory())
getGlobal(category, "diffAnalysesSurv")
#' Get the species of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Character value with the species
getSpecies <- function(category = getCategory())
getGlobal(category, "species")
#' Get the assembly version of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Character value with the assembly version
getAssemblyVersion <- function(category = getCategory())
getGlobal(category, "assemblyVersion")
#' Get groups from a given data type
#' @note Needs to be called inside a reactive function
#'
#' @param dataset Character: data set (e.g. "Clinical data")
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @param complete Boolean: return all the information on groups (TRUE) or just
#' the group names and respective indexes (FALSE)? FALSE by default
#' @param samples Boolean: show groups by samples (TRUE) or patients (FALSE)?
#' FALSE by default
#'
#' @return Matrix with groups of a given dataset
getGroupsFrom <- function(dataset, category = getCategory(), complete=FALSE,
samples=FALSE) {
groups <- getGlobal(category, dataset, "groups")
# Return all data if requested
if (complete) return(groups)
if (samples)
col <- "Samples"
else
col <- "Patients"
# Check if data of interest is available
if (!col %in% colnames(groups)) return(NULL)
# If available, return data of interest
g <- groups[ , col, drop=TRUE]
if (length(g) == 1) names(g) <- rownames(groups)
return(g)
}
#' Get clinical matches from a given data type
#' @note Needs to be called inside a reactive function
#'
#' @param dataset Character: data set (e.g. "Junction quantification")
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Integer with clinical matches to a given dataset
getClinicalMatchFrom <- function(dataset, category = getCategory())
getGlobal(category, dataset, "clinicalMatch")
#' Get the URL links to download
#' @note Needs to be called inside a reactive function
#'
#' @return Character vector with URLs to download
getURLtoDownload <- function()
getGlobal("URLtoDownload")
#' Get principal component analysis based on inclusion levels
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return \code{prcomp} object (PCA) of inclusion levels
getInclusionLevelsPCA <- function(category = getCategory())
getGlobal(category, "inclusionLevelsPCA")
#' Set element as globally accessible
#' @details Set element inside the global variable
#' @note Needs to be called inside a reactive function
#'
#' @param ... Arguments to identify a variable
#' @param value Any value to attribute to an element
#' @param sep Character to separate identifier
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setGlobal <- function(..., value, sep="_") {
sharedData[[paste(..., sep=sep)]] <- value
}
#' Set data of the global data
#' @note Needs to be called inside a reactive function
#' @param data Data frame or matrix to set as data
#' @return NULL (this function is used to modify the Shiny session's state)
setData <- function(data) setGlobal("data", value=data)
#' Set if history browsing is automatic
#' @note Needs to be called inside a reactive function
#' @param param Boolean: is navigation of browser history automatic?
#' @return NULL (this function is used to modify the Shiny session's state)
setAutoNavigation <- function(param) setGlobal("autoNavigation", value=param)
#' Set number of cores
#' @param cores Character: number of cores
#' @note Needs to be called inside a reactive function
#' @return NULL (this function is used to modify the Shiny session's state)
setCores <- function(cores) setGlobal("cores", value=cores)
#' Set number of significant digits
#' @param significant Character: number of significant digits
#' @note Needs to be called inside a reactive function
#' @return NULL (this function is used to modify the Shiny session's state)
setSignificant <- function(significant) setGlobal("significant", value=significant)
#' Set number of decimal places
#' @param precision Numeric: number of decimal places
#' @return NULL (this function is used to modify the Shiny session's state)
#' @note Needs to be called inside a reactive function
setPrecision <- function(precision) setGlobal("precision", value=precision)
#' Set event
#' @param event Character: event
#' @note Needs to be called inside a reactive function
#' @return NULL (this function is used to modify the Shiny session's state)
setEvent <- function(event) setGlobal("event", value=event)
#' Set data category
#' @param category Character: data category
#' @note Needs to be called inside a reactive function
#' @return NULL (this function is used to modify the Shiny session's state)
setCategory <- function(category) setGlobal("category", value=category)
#' Set active dataset
#' @param dataset Character: dataset
#' @note Needs to be called inside a reactive function
#' @return NULL (this function is used to modify the Shiny session's state)
setActiveDataset <- function(dataset) setGlobal("activeDataset", value=dataset)
#' Set inclusion levels for a given data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Data frame or matrix: inclusion levels
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setInclusionLevels <- function(value, category = getCategory())
sharedData$data[[category]][["Inclusion levels"]] <- value
#' Set sample information for a given data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Data frame or matrix: sample information
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setSampleInfo <- function(value, category = getCategory())
sharedData$data[[category]][["Sample metadata"]] <- value
#' Set groups from a given data type
#' @note Needs to be called inside a reactive function
#'
#' @param dataset Character: data set (e.g. "Clinical data")
#' @param groups Matrix: groups of dataset
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setGroupsFrom <- function(dataset, groups, category = getCategory())
setGlobal(category, dataset, "groups", value=groups)
#' Set the identifier of patients for a data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Character: identifier of patients
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setPatientId <- function(value, category = getCategory())
setGlobal(category, "patients", value=value)
#' Set the identifier of samples for a data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Character: identifier of samples
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setSampleId <- function(value, category = getCategory())
setGlobal(category, "samples", value=value)
#' Set the table of differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param table Character: differential analyses table
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalyses <- function(table, category = getCategory())
setGlobal(category, "differentialAnalyses", value=table)
#' Set the filtered table of differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param table Character: filtered differential analyses table
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalysesFiltered <- function(table, category = getCategory())
setGlobal(category, "differentialAnalysesFiltered", value=table)
#' Set highlighted events from differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param events Integer: indexes relative to a table of differential analyses
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalysesHighlightedEvents <- function(events,
category = getCategory())
setGlobal(category, "differentialAnalysesHighlighted", value=events)
#' Set plot coordinates for zooming from differential analyses of a data
#' category
#' @note Needs to be called inside a reactive function
#'
#' @param zoom Integer: X and Y coordinates
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalysesZoom <- function(zoom, category=getCategory())
setGlobal(category, "differentialAnalysesZoom", value=zoom)
#' Set selected points in the differential analysis table of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param points Integer: index of selected points
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalysesSelected <- function(points, category=getCategory())
setGlobal(category, "differentialAnalysesSelected", value=points)
#' Set the table of differential analyses' survival data of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param table Character: differential analyses' survival data
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalysesSurvival <- function(table, category = getCategory())
setGlobal(category, "diffAnalysesSurv", value=table)
#' Set the species of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Character: species
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setSpecies <- function(value, category = getCategory())
setGlobal(category, "species", value=value)
#' Set the assembly version of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Character: assembly version
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setAssemblyVersion <- function(value, category = getCategory())
setGlobal(category, "assemblyVersion", value=value)
#' Set clinical matches from a given data type
#' @note Needs to be called inside a reactive function
#'
#' @param dataset Character: data set (e.g. "Clinical data")
#' @param matches Vector of integers: clinical matches of dataset
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setClinicalMatchFrom <- function(dataset, matches, category = getCategory())
setGlobal(category, dataset, "clinicalMatch", value=matches)
#' Set URL links to download
#' @note Needs to be called inside a reactive function
#'
#' @param url Character: URL links to download
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setURLtoDownload <- function(url)
setGlobal("URLtoDownload", value=url)
#' Get principal component analysis based on inclusion levels
#' @note Needs to be called inside a reactive function
#'
#' @param pca \code{prcomp} object (PCA) of inclusion levels
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setInclusionLevelsPCA <- function(pca, category=getCategory())
setGlobal(category, "inclusionLevelsPCA", value=pca)
| /R/globalAccess.R | no_license | mgandal/psichomics | R | false | false | 19,883 | r | ## Functions to get and set globally accessible variables
#' @include utils.R
NULL
# Global variable with all the data of a session
sharedData <- reactiveValues()
#' Get global data
#' @return Variable containing all data of interest
getData <- reactive(sharedData$data)
#' Get if history browsing is automatic
#' @return Boolean: is navigation of browser history automatic?
getAutoNavigation <- reactive(sharedData$autoNavigation)
#' Get number of cores to use
#' @return Numeric value with the number of cores to use
getCores <- reactive(sharedData$cores)
#' Get number of significant digits
#' @return Numeric value regarding the number of significant digits
getSignificant <- reactive(sharedData$significant)
#' Get number of decimal places
#' @return Numeric value regarding the number of decimal places
getPrecision <- reactive(sharedData$precision)
#' Get selected alternative splicing event's identifer
#' @return Alternative splicing event's identifier as a string
getEvent <- reactive(sharedData$event)
#' Get available data categories
#' @return Name of all data categories
getCategories <- reactive(names(getData()))
#' Get selected data category
#' @return Name of selected data category
getCategory <- reactive(sharedData$category)
#' Get data of selected data category
#' @return If category is selected, returns the respective data as a data frame;
#' otherwise, returns NULL
getCategoryData <- reactive(
if(!is.null(getCategory())) getData()[[getCategory()]])
#' Get selected dataset
#' @return List of data frames
getActiveDataset <- reactive(sharedData$activeDataset)
#' Get clinical data of the data category
#' @return Data frame with clinical data
getClinicalData <- reactive(getCategoryData()[["Clinical data"]])
#' Get junction quantification data
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return List of data frames of junction quantification
getJunctionQuantification <- function(category=getCategory()) {
if (!is.null(category)) {
data <- getData()[[category]]
match <- sapply(data, attr, "dataType") == "Junction quantification"
if (any(match)) return(data[match])
}
}
#' Get alternative splicing quantification of the selected data category
#' @return Data frame with the alternative splicing quantification
getInclusionLevels <- reactive(getCategoryData()[["Inclusion levels"]])
#' Get sample information of the selected data category
#' @return Data frame with sample information
getSampleInfo <- reactive(getCategoryData()[["Sample metadata"]])
#' Get data from global data
#' @param ... Arguments to identify a variable
#' @param sep Character to separate identifiers
#' @return Data from global data
getGlobal <- function(..., sep="_") sharedData[[paste(..., sep=sep)]]
#' Get the identifier of patients for a given category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Character vector with identifier of patients
getPatientId <- function(category = getCategory())
getGlobal(category, "patients")
#' Get the identifier of samples for a given category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Character vector with identifier of samples
getSampleId <- function(category = getCategory())
getGlobal(category, "samples")
#' Get the table of differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Data frame of differential analyses
getDifferentialAnalyses <- function(category = getCategory())
getGlobal(category, "differentialAnalyses")
#' Get the filtered table of differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Filtered data frame of differential analyses
getDifferentialAnalysesFiltered <- function(category = getCategory())
getGlobal(category, "differentialAnalysesFiltered")
#' Get highlighted events from differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Integer of indexes relative to a table of differential analyses
getDifferentialAnalysesHighlightedEvents <- function(category = getCategory())
getGlobal(category, "differentialAnalysesHighlighted")
#' Get plot coordinates for zooming from differential analyses of a data
#' category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Integer of X and Y axes coordinates
getDifferentialAnalysesZoom <- function(category = getCategory())
getGlobal(category, "differentialAnalysesZoom")
#' Get selected points in the differential analysis table of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Integer containing index of selected points
getDifferentialAnalysesSelected <- function(category = getCategory())
getGlobal(category, "differentialAnalysesSelected")
#' Get the table of differential analyses' survival data of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Data frame of differential analyses' survival data
getDifferentialAnalysesSurvival <- function(category = getCategory())
getGlobal(category, "diffAnalysesSurv")
#' Get the species of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Character value with the species
getSpecies <- function(category = getCategory())
getGlobal(category, "species")
#' Get the assembly version of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Character value with the assembly version
getAssemblyVersion <- function(category = getCategory())
getGlobal(category, "assemblyVersion")
#' Get groups from a given data type
#' @note Needs to be called inside a reactive function
#'
#' @param dataset Character: data set (e.g. "Clinical data")
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @param complete Boolean: return all the information on groups (TRUE) or just
#' the group names and respective indexes (FALSE)? FALSE by default
#' @param samples Boolean: show groups by samples (TRUE) or patients (FALSE)?
#' FALSE by default
#'
#' @return Matrix with groups of a given dataset
getGroupsFrom <- function(dataset, category = getCategory(), complete=FALSE,
samples=FALSE) {
groups <- getGlobal(category, dataset, "groups")
# Return all data if requested
if (complete) return(groups)
if (samples)
col <- "Samples"
else
col <- "Patients"
# Check if data of interest is available
if (!col %in% colnames(groups)) return(NULL)
# If available, return data of interest
g <- groups[ , col, drop=TRUE]
if (length(g) == 1) names(g) <- rownames(groups)
return(g)
}
#' Get clinical matches from a given data type
#' @note Needs to be called inside a reactive function
#'
#' @param dataset Character: data set (e.g. "Junction quantification")
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return Integer with clinical matches to a given dataset
getClinicalMatchFrom <- function(dataset, category = getCategory())
getGlobal(category, dataset, "clinicalMatch")
#' Get the URL links to download
#' @note Needs to be called inside a reactive function
#'
#' @return Character vector with URLs to download
getURLtoDownload <- function()
getGlobal("URLtoDownload")
#' Get principal component analysis based on inclusion levels
#' @note Needs to be called inside a reactive function
#'
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return \code{prcomp} object (PCA) of inclusion levels
getInclusionLevelsPCA <- function(category = getCategory())
getGlobal(category, "inclusionLevelsPCA")
#' Set element as globally accessible
#' @details Set element inside the global variable
#' @note Needs to be called inside a reactive function
#'
#' @param ... Arguments to identify a variable
#' @param value Any value to attribute to an element
#' @param sep Character to separate identifier
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setGlobal <- function(..., value, sep="_") {
sharedData[[paste(..., sep=sep)]] <- value
}
#' Set data of the global data
#' @note Needs to be called inside a reactive function
#' @param data Data frame or matrix to set as data
#' @return NULL (this function is used to modify the Shiny session's state)
setData <- function(data) setGlobal("data", value=data)
#' Set if history browsing is automatic
#' @note Needs to be called inside a reactive function
#' @param param Boolean: is navigation of browser history automatic?
#' @return NULL (this function is used to modify the Shiny session's state)
setAutoNavigation <- function(param) setGlobal("autoNavigation", value=param)
#' Set number of cores
#' @param cores Character: number of cores
#' @note Needs to be called inside a reactive function
#' @return NULL (this function is used to modify the Shiny session's state)
setCores <- function(cores) setGlobal("cores", value=cores)
#' Set number of significant digits
#' @param significant Character: number of significant digits
#' @note Needs to be called inside a reactive function
#' @return NULL (this function is used to modify the Shiny session's state)
setSignificant <- function(significant) setGlobal("significant", value=significant)
#' Set number of decimal places
#' @param precision Numeric: number of decimal places
#' @return NULL (this function is used to modify the Shiny session's state)
#' @note Needs to be called inside a reactive function
setPrecision <- function(precision) setGlobal("precision", value=precision)
#' Set event
#' @param event Character: event
#' @note Needs to be called inside a reactive function
#' @return NULL (this function is used to modify the Shiny session's state)
setEvent <- function(event) setGlobal("event", value=event)
#' Set data category
#' @param category Character: data category
#' @note Needs to be called inside a reactive function
#' @return NULL (this function is used to modify the Shiny session's state)
setCategory <- function(category) setGlobal("category", value=category)
#' Set active dataset
#' @param dataset Character: dataset
#' @note Needs to be called inside a reactive function
#' @return NULL (this function is used to modify the Shiny session's state)
setActiveDataset <- function(dataset) setGlobal("activeDataset", value=dataset)
#' Set inclusion levels for a given data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Data frame or matrix: inclusion levels
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setInclusionLevels <- function(value, category = getCategory())
sharedData$data[[category]][["Inclusion levels"]] <- value
#' Set sample information for a given data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Data frame or matrix: sample information
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setSampleInfo <- function(value, category = getCategory())
sharedData$data[[category]][["Sample metadata"]] <- value
#' Set groups from a given data type
#' @note Needs to be called inside a reactive function
#'
#' @param dataset Character: data set (e.g. "Clinical data")
#' @param groups Matrix: groups of dataset
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setGroupsFrom <- function(dataset, groups, category = getCategory())
setGlobal(category, dataset, "groups", value=groups)
#' Set the identifier of patients for a data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Character: identifier of patients
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setPatientId <- function(value, category = getCategory())
setGlobal(category, "patients", value=value)
#' Set the identifier of samples for a data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Character: identifier of samples
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setSampleId <- function(value, category = getCategory())
setGlobal(category, "samples", value=value)
#' Set the table of differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param table Character: differential analyses table
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalyses <- function(table, category = getCategory())
setGlobal(category, "differentialAnalyses", value=table)
#' Set the filtered table of differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param table Character: filtered differential analyses table
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalysesFiltered <- function(table, category = getCategory())
setGlobal(category, "differentialAnalysesFiltered", value=table)
#' Set highlighted events from differential analyses of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param events Integer: indexes relative to a table of differential analyses
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalysesHighlightedEvents <- function(events,
category = getCategory())
setGlobal(category, "differentialAnalysesHighlighted", value=events)
#' Set plot coordinates for zooming from differential analyses of a data
#' category
#' @note Needs to be called inside a reactive function
#'
#' @param zoom Integer: X and Y coordinates
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalysesZoom <- function(zoom, category=getCategory())
setGlobal(category, "differentialAnalysesZoom", value=zoom)
#' Set selected points in the differential analysis table of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param points Integer: index of selected points
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalysesSelected <- function(points, category=getCategory())
setGlobal(category, "differentialAnalysesSelected", value=points)
#' Set the table of differential analyses' survival data of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param table Character: differential analyses' survival data
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setDifferentialAnalysesSurvival <- function(table, category = getCategory())
setGlobal(category, "diffAnalysesSurv", value=table)
#' Set the species of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Character: species
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setSpecies <- function(value, category = getCategory())
setGlobal(category, "species", value=value)
#' Set the assembly version of a data category
#' @note Needs to be called inside a reactive function
#'
#' @param value Character: assembly version
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setAssemblyVersion <- function(value, category = getCategory())
setGlobal(category, "assemblyVersion", value=value)
#' Set clinical matches from a given data type
#' @note Needs to be called inside a reactive function
#'
#' @param dataset Character: data set (e.g. "Clinical data")
#' @param matches Vector of integers: clinical matches of dataset
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#' @return NULL (this function is used to modify the Shiny session's state)
setClinicalMatchFrom <- function(dataset, matches, category = getCategory())
setGlobal(category, dataset, "clinicalMatch", value=matches)
#' Set URL links to download
#' @note Needs to be called inside a reactive function
#'
#' @param url Character: URL links to download
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setURLtoDownload <- function(url)
setGlobal("URLtoDownload", value=url)
#' Get principal component analysis based on inclusion levels
#' @note Needs to be called inside a reactive function
#'
#' @param pca \code{prcomp} object (PCA) of inclusion levels
#' @param category Character: data category (e.g. "Carcinoma 2016"); by default,
#' it uses the selected data category
#'
#' @return NULL (this function is used to modify the Shiny session's state)
setInclusionLevelsPCA <- function(pca, category=getCategory())
setGlobal(category, "inclusionLevelsPCA", value=pca)
|
##1/13/16
##Update Beta, n, seed, and file name
rm(list=ls())
seed <- 452585513
###################################################################################
##LIBRARIES##
###################################################################################
require(survival)
require(MASS)
require(gaussquad)
require(numDeriv)
currWorkDir <- getwd()
setwd("/users/emhuang/Ravi/paper/genericCode")
source("allCode.R")
setwd(currWorkDir)
############################################################################################################################################
##FUNCTIONS##
############################################################################################################################################
hazard <- function(t, a, b, exb) exb * a * (t/b)^(a-1)
cumhaz <- function(t, a, b, exb) exb * b * (t/b)^a
froot <- function(x, u, ...) sqrt(cumhaz(x, ...)) - sqrt(u)
############################################################################################################################################
##INPUTS##
############################################################################################################################################
K <- 10000 ##number of randomized trials to be simulated
m <- 3 ##number of follow-up visits
pTreatment <- 0.5 ##probability of being assigned to treatment group
trueBeta <- 0.6 ##treatment effect
n <- 500 ##sample size of each simulated randomized trial
set.seed(seed)
simSeeds <- sample(10^9,K)
visit1Time <- 2
visit2Time <- 4
visit3Time <- 6
###################################################################################
##SIMULATIONS##
###################################################################################
nMethods <- 5
result <- matrix(NA, nrow = K, ncol = nMethods * 2)
nties <- matrix(NA, nrow = K, ncol = 3)
for(k in 1:K){
set.seed(simSeeds[k])
###################################################################################
##Generation of Z (random treatment assignment: 1 if control, 0 if treatment)##
###################################################################################
data <- data.frame(Z=rbinom(n,size=1,prob=pTreatment))
###################################################################################
##Generation of C (censoring time, the last visit the subject attends)##
###################################################################################
data$C <- sample(x=0:m,size=n,replace = TRUE, prob = c(.08,.1,.1,.72))
###################################################################################
##Generation of T (frailty time)##
###################################################################################
##Failure time generated from the Weibull hazard
a <- 2
b <- 100
u <- -log(runif(n))
exb <- exp(trueBeta*data$Z)
data$Tcont <- NA
for(i in 1:n){
data$Tcont[i] <- uniroot(froot, interval=c(1.e-14, 1e04), u = u[i], exb = exb[i], a=a, b=b)$root
}
rm(a,b,u,exb)
#hist(data$Tcont)
#summary(data$Tcont)
###################################################################################
##Generation of T' (grouped frailty time)##
###################################################################################
data$Tgrouped <- 10000
for(i in 1:n){
if(data$Tcont[i]==0){
data$Tgrouped[i] <- 0
}else if(0<data$Tcont[i]&data$Tcont[i]<=visit1Time){
data$Tgrouped[i] <- 1
}else if(visit1Time<data$Tcont[i] & data$Tcont[i]<=visit2Time){
data$Tgrouped[i] <- 2
}else if(visit2Time<data$Tcont[i] & data$Tcont[i]<=visit3Time){
data$Tgrouped[i] <- 3
}
}
###################################################################################
##Calculate delta (censoring indicator) and V (visit time depending on delta)##
###################################################################################
data$delta <- 1
data$delta[data$Tgrouped>data$C] <- 0
data$V <- data$delta*data$Tgrouped + (1-data$delta)*data$C
#table(data$C)/n
#table(data$Tgrouped)/n
#table(data$delta,data$V)/n
#temp <- table(data$delta,data$V)/n
#sum(temp[1,1:3]) #proportion of n subjects who dropout early
#temp[1,4] #proportion of n subjects who are adminstratively censored
#sum(temp[2,]) #proportion who are observed to be frail
data <- data.frame(delta = data$delta, V = data$V, Z = data$Z)
data <- subset(data, V!=0)
nties[k,] <- table(data$delta, data$V)[2,]
temp <- table(data$delta,data$V)/n
if (nrow(temp)!=2) {
result[k,] <- rep(NA,times=nMethods * 2)
warning(paste(k, ":Either no censoring or no failure."))
} else {
result[k,] <- applyMethods(data)
}
}
save(nties,result, file="Beta06_n500.Rdata") | /groupedData/Simulations/SingleCovariate/varyBeta/code/Beta06_n500.R | no_license | emhuang1/groupedData | R | false | false | 4,769 | r | ##1/13/16
##Update Beta, n, seed, and file name
rm(list=ls())
seed <- 452585513
###################################################################################
##LIBRARIES##
###################################################################################
require(survival)
require(MASS)
require(gaussquad)
require(numDeriv)
currWorkDir <- getwd()
setwd("/users/emhuang/Ravi/paper/genericCode")
source("allCode.R")
setwd(currWorkDir)
############################################################################################################################################
##FUNCTIONS##
############################################################################################################################################
hazard <- function(t, a, b, exb) exb * a * (t/b)^(a-1)
cumhaz <- function(t, a, b, exb) exb * b * (t/b)^a
froot <- function(x, u, ...) sqrt(cumhaz(x, ...)) - sqrt(u)
############################################################################################################################################
##INPUTS##
############################################################################################################################################
K <- 10000 ##number of randomized trials to be simulated
m <- 3 ##number of follow-up visits
pTreatment <- 0.5 ##probability of being assigned to treatment group
trueBeta <- 0.6 ##treatment effect
n <- 500 ##sample size of each simulated randomized trial
set.seed(seed)
simSeeds <- sample(10^9,K)
visit1Time <- 2
visit2Time <- 4
visit3Time <- 6
###################################################################################
##SIMULATIONS##
###################################################################################
nMethods <- 5
result <- matrix(NA, nrow = K, ncol = nMethods * 2)
nties <- matrix(NA, nrow = K, ncol = 3)
for(k in 1:K){
set.seed(simSeeds[k])
###################################################################################
##Generation of Z (random treatment assignment: 1 if control, 0 if treatment)##
###################################################################################
data <- data.frame(Z=rbinom(n,size=1,prob=pTreatment))
###################################################################################
##Generation of C (censoring time, the last visit the subject attends)##
###################################################################################
data$C <- sample(x=0:m,size=n,replace = TRUE, prob = c(.08,.1,.1,.72))
###################################################################################
##Generation of T (frailty time)##
###################################################################################
##Failure time generated from the Weibull hazard
a <- 2
b <- 100
u <- -log(runif(n))
exb <- exp(trueBeta*data$Z)
data$Tcont <- NA
for(i in 1:n){
data$Tcont[i] <- uniroot(froot, interval=c(1.e-14, 1e04), u = u[i], exb = exb[i], a=a, b=b)$root
}
rm(a,b,u,exb)
#hist(data$Tcont)
#summary(data$Tcont)
###################################################################################
##Generation of T' (grouped frailty time)##
###################################################################################
data$Tgrouped <- 10000
for(i in 1:n){
if(data$Tcont[i]==0){
data$Tgrouped[i] <- 0
}else if(0<data$Tcont[i]&data$Tcont[i]<=visit1Time){
data$Tgrouped[i] <- 1
}else if(visit1Time<data$Tcont[i] & data$Tcont[i]<=visit2Time){
data$Tgrouped[i] <- 2
}else if(visit2Time<data$Tcont[i] & data$Tcont[i]<=visit3Time){
data$Tgrouped[i] <- 3
}
}
###################################################################################
##Calculate delta (censoring indicator) and V (visit time depending on delta)##
###################################################################################
data$delta <- 1
data$delta[data$Tgrouped>data$C] <- 0
data$V <- data$delta*data$Tgrouped + (1-data$delta)*data$C
#table(data$C)/n
#table(data$Tgrouped)/n
#table(data$delta,data$V)/n
#temp <- table(data$delta,data$V)/n
#sum(temp[1,1:3]) #proportion of n subjects who dropout early
#temp[1,4] #proportion of n subjects who are adminstratively censored
#sum(temp[2,]) #proportion who are observed to be frail
data <- data.frame(delta = data$delta, V = data$V, Z = data$Z)
data <- subset(data, V!=0)
nties[k,] <- table(data$delta, data$V)[2,]
temp <- table(data$delta,data$V)/n
if (nrow(temp)!=2) {
result[k,] <- rep(NA,times=nMethods * 2)
warning(paste(k, ":Either no censoring or no failure."))
} else {
result[k,] <- applyMethods(data)
}
}
save(nties,result, file="Beta06_n500.Rdata") |
library(glmnet)
mydata = read.table("../../../../TrainingSet/FullSet/ReliefF/large_intestine.csv",head=T,sep=",")
x = as.matrix(mydata[,4:ncol(mydata)])
y = as.matrix(mydata[,1])
set.seed(123)
glm = cv.glmnet(x,y,nfolds=10,type.measure="mse",alpha=0.04,family="gaussian",standardize=TRUE)
sink('./large_intestine_017.txt',append=TRUE)
print(glm$glmnet.fit)
sink()
| /Model/EN/ReliefF/large_intestine/large_intestine_017.R | no_license | esbgkannan/QSMART | R | false | false | 364 | r | library(glmnet)
mydata = read.table("../../../../TrainingSet/FullSet/ReliefF/large_intestine.csv",head=T,sep=",")
x = as.matrix(mydata[,4:ncol(mydata)])
y = as.matrix(mydata[,1])
set.seed(123)
glm = cv.glmnet(x,y,nfolds=10,type.measure="mse",alpha=0.04,family="gaussian",standardize=TRUE)
sink('./large_intestine_017.txt',append=TRUE)
print(glm$glmnet.fit)
sink()
|
% Generated by roxygen2 (4.0.1.99): do not edit by hand
\docType{package}
\name{geohexr}
\alias{geohexr}
\alias{geohexr-package}
\title{geohexr.}
\description{
geohexr.
}
| /man/geohexr.Rd | no_license | akiatoji/geohexr | R | false | false | 172 | rd | % Generated by roxygen2 (4.0.1.99): do not edit by hand
\docType{package}
\name{geohexr}
\alias{geohexr}
\alias{geohexr-package}
\title{geohexr.}
\description{
geohexr.
}
|
testlist <- list(G = numeric(0), Rn = numeric(0), atmp = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), ra = numeric(0), relh = -1.72131968218895e+83, rs = numeric(0), temp = c(8.5728629954997e-312, 1.56898424065867e+82, 8.96970809549085e-158, -1.3258495253834e-113, 2.79620616433656e-119, -6.80033518839696e+41, 2.68298522855314e-211, 1444042902784.06, 6.68889884134308e+51, -4.05003163986346e-308, -3.52601820453991e+43, -1.49815227045093e+197, -2.61605817623304e+76, -1.18078903777423e-90, 1.86807199752012e+112, -5.58551357556946e+160, 2.00994342527714e-162, 1.81541609400943e-79, 7.89363005545928e+139, 2.3317908961407e-93, 2.16562581831091e+161))
result <- do.call(meteor:::ET0_PenmanMonteith,testlist)
str(result) | /meteor/inst/testfiles/ET0_PenmanMonteith/AFL_ET0_PenmanMonteith/ET0_PenmanMonteith_valgrind_files/1615839111-test.R | no_license | akhikolla/updatedatatype-list3 | R | false | false | 826 | r | testlist <- list(G = numeric(0), Rn = numeric(0), atmp = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), ra = numeric(0), relh = -1.72131968218895e+83, rs = numeric(0), temp = c(8.5728629954997e-312, 1.56898424065867e+82, 8.96970809549085e-158, -1.3258495253834e-113, 2.79620616433656e-119, -6.80033518839696e+41, 2.68298522855314e-211, 1444042902784.06, 6.68889884134308e+51, -4.05003163986346e-308, -3.52601820453991e+43, -1.49815227045093e+197, -2.61605817623304e+76, -1.18078903777423e-90, 1.86807199752012e+112, -5.58551357556946e+160, 2.00994342527714e-162, 1.81541609400943e-79, 7.89363005545928e+139, 2.3317908961407e-93, 2.16562581831091e+161))
result <- do.call(meteor:::ET0_PenmanMonteith,testlist)
str(result) |
# FLTag -
# FLR4SCRS/R/FLTag.R
# Reference:
# Notes:
setGeneric("I", function(object,...)
standardGeneric("I"))
setGeneric('O', function(object, ...)
standardGeneric("O"))
setGeneric('computeTag.n', function(object, ...)
standardGeneric("computeTag.n"))
setGeneric('computeTag.p', function(object, ...)
standardGeneric("computeTag.p"))
setGeneric('computeTag.r', function(object, ...)
standardGeneric("computeTag.r"))
setGeneric('computeStock.n', function(object, ...)
standardGeneric("computeStock.n"))
setMethod('I', signature(object='FLQuant'),
function(object,...){
dmns <-dimnames(object)
dmns[[1]] <-ac((dims(object)$minyear-dims(object)$max):(dims(object)$maxyear- dims(object)$min))
names(dmns)[1]<-"quant"
flc <-FLQuant(NA,dimnames=dmns)
t. <-as.data.frame(object)
t.$cohort <-t.$year-t.$age
flc[] <-daply(t.,c("cohort","year","unit","season","area","iter"),function(x) sum(x$data))
return(flc)})
setMethod('O', signature(object='FLQuant'),
function(object,...){
dmns <-dimnames(object)
dmns[[1]] <-ac((dims(object)$maxyear-dims(object)$max):(dims(object)$minyear-dims(object)$min))
names(dmns)[1]<-"age"
flc <-FLQuant(NA,dimnames=dmns)
t. <-as.data.frame(object)
t.$age <-t.$year-t.$quant
t. <-t.[!is.na(t.$data),]
flc[] <-daply(t.,c("age","year","unit","season","area","iter"),function(x) sum(x$data))
return(flc)})
setMethod('computeTag.p', signature(object='FLTag'),
function(object,...)
tagP*exp(-harvest-m)[-1,-1])
setMethod('computeTag.n', signature(object='FLTag'),
function(object,...)
harvest/(harvest+m)*pTag*(1-exp(-harvest-m)))
setMethod('computeTag.r', signature(object='FLTag'),
function(object,...)
harvest/(harvest+m)*stock.n*(1-exp(-harvest-m)))
setMethod('computeStock.n', signature(object='FLTag'),
function(object,...)
stock.n*exp(-harvest-m)[-1,-1])
#loglAR1(m(ple4), m(ple4))
| /R/methodsFLTag.R | no_license | laurieKell/FLTag | R | false | false | 2,059 | r | # FLTag -
# FLR4SCRS/R/FLTag.R
# Reference:
# Notes:
setGeneric("I", function(object,...)
standardGeneric("I"))
setGeneric('O', function(object, ...)
standardGeneric("O"))
setGeneric('computeTag.n', function(object, ...)
standardGeneric("computeTag.n"))
setGeneric('computeTag.p', function(object, ...)
standardGeneric("computeTag.p"))
setGeneric('computeTag.r', function(object, ...)
standardGeneric("computeTag.r"))
setGeneric('computeStock.n', function(object, ...)
standardGeneric("computeStock.n"))
setMethod('I', signature(object='FLQuant'),
function(object,...){
dmns <-dimnames(object)
dmns[[1]] <-ac((dims(object)$minyear-dims(object)$max):(dims(object)$maxyear- dims(object)$min))
names(dmns)[1]<-"quant"
flc <-FLQuant(NA,dimnames=dmns)
t. <-as.data.frame(object)
t.$cohort <-t.$year-t.$age
flc[] <-daply(t.,c("cohort","year","unit","season","area","iter"),function(x) sum(x$data))
return(flc)})
setMethod('O', signature(object='FLQuant'),
function(object,...){
dmns <-dimnames(object)
dmns[[1]] <-ac((dims(object)$maxyear-dims(object)$max):(dims(object)$minyear-dims(object)$min))
names(dmns)[1]<-"age"
flc <-FLQuant(NA,dimnames=dmns)
t. <-as.data.frame(object)
t.$age <-t.$year-t.$quant
t. <-t.[!is.na(t.$data),]
flc[] <-daply(t.,c("age","year","unit","season","area","iter"),function(x) sum(x$data))
return(flc)})
setMethod('computeTag.p', signature(object='FLTag'),
function(object,...)
tagP*exp(-harvest-m)[-1,-1])
setMethod('computeTag.n', signature(object='FLTag'),
function(object,...)
harvest/(harvest+m)*pTag*(1-exp(-harvest-m)))
setMethod('computeTag.r', signature(object='FLTag'),
function(object,...)
harvest/(harvest+m)*stock.n*(1-exp(-harvest-m)))
setMethod('computeStock.n', signature(object='FLTag'),
function(object,...)
stock.n*exp(-harvest-m)[-1,-1])
#loglAR1(m(ple4), m(ple4))
|
update.packages(ask=FALSE) | /r/update.r | permissive | catalandres/dotfiles | R | false | false | 26 | r | update.packages(ask=FALSE) |
#devtools::install_github('https://github.com/daqana/dqshiny')
library(shinydashboard)
library(reactable)
library(dqshiny)
library(tidyverse)
library(ggplot2)
source('functions.R')
dat <- rio::import('All_Years_Cleaned_Data.csv')
student_groups_vector <- c(
'ALL Students',
'Economically Disadvantaged',
'Black',
'White',
'Not Economically Disadvantaged',
'Students With Disability',
'Students Without Disability'
)
sidebar_menu <-
dashboardSidebar(
sidebarMenu(
menuItem("Chart", tabName = 'graph', icon = icon('bar-chart-o')),
menuItem("Table", tabName = 'table1', icon = icon('table')),
menuItem("Data Download", tabName = 'downloader_tab', icon = icon('save')),
menuItem(
'Groups of Interest',
tabname = 'slider',
icon = icon('user'),
## this puts the option in a drop down
selectInput(
'groups',
"Click to select 1+ group(s):",
multiple = TRUE,
selected = student_groups_vector,
choices = student_groups_vector
)
),
## install the package with this
## devtools::install_github('https://github.com/daqana/dqshiny')
dqshiny::autocomplete_input(
'school_names_manual',
'Type school name for only one plot',
options = unique(dat$instn_name),
value = "Appling County High School",
width = NULL,
placeholder = 'autofill on',
max_options = 0,
hide_values = FALSE
)
)
)
body_tabs <-
tabItems(
tabItem('graph',
plotOutput("plot1", height = 600),
box(downloadButton("plot_downloader", "Download Plot", icon = icon('save')))),
tabItem('table1',
reactable::reactableOutput("table1"),
box(downloadButton("downloadData", label = "Download Selected Data"))
),
tabItem('downloader_tab',
box(downloadButton("data_downloader", "Download All Data", icon = icon('download')))
)
)
ui <- dashboardPage(
dashboardHeader(title = "Loan & Klaas Final"),
sidebar_menu,
dashboardBody(
# Boxes need to be put in a row (or column)
fluidPage(
#title = 'plots',
body_tabs)
),
skin = c('black'))
server <- function(input, output) {
datasetInput <-reactive({ dat %>%
select_groups(groups_of_interest = input$groups) %>%
select_schools(schools_of_interest = input$school_names_manual) %>%
mutate_if(is.numeric, round, 2) %>%
reactable(filterable = T)
}
)
# reactive_school_name <- reactive({input$school_names_manual})
output$plot1 <- renderPlot({
plots <- grad_year_plots(
dat,
groups_of_interest = input$groups,
schools_of_interest = input$school_names_manual)
plt <- plots$plot[[1]]
plt + theme_minimal(base_size = 18) + theme(legend.position = 'bottom')
})
table_download <-reactive({dat %>%
select_groups(groups_of_interest = input$groups) %>%
select_schools(schools_of_interest = input$school_names_manual) %>%
mutate_if(is.numeric, round, 2)})
output$table1 <- renderReactable({
table_download() %>%
reactable(filterable = T)
})
output$data_downloader <- downloadHandler(
filename = 'full_data.csv',
content = function(file) {
write.csv(dat, file)
}
)
output$downloadData <- downloadHandler(
filename = function() {
paste("Data", input$school_names_manual,".csv", sep = " ") #customize school name for data
},
content = function(file) {
write.csv(table_download(), file)
}
)
output$plot_downloader <- downloadHandler(
filename = function() {
paste("Plot", input$school_names_manual,".png", sep = " ") #customize school name for plot
},
content = function(file){
plots <- grad_year_plots(
dat,
groups_of_interest = input$groups,
schools_of_interest = input$school_names_manual)
plt <- plots$plot[[1]]
ggsave(file, width = 10, plot=plt) #change the width to 10 to prevent the legend from clipping
}
)
}
shinyApp(ui, server)
| /GA_Grad_Plots/app.R | permissive | Chhr1s/EDLD_653_Final | R | false | false | 4,732 | r | #devtools::install_github('https://github.com/daqana/dqshiny')
library(shinydashboard)
library(reactable)
library(dqshiny)
library(tidyverse)
library(ggplot2)
source('functions.R')
dat <- rio::import('All_Years_Cleaned_Data.csv')
student_groups_vector <- c(
'ALL Students',
'Economically Disadvantaged',
'Black',
'White',
'Not Economically Disadvantaged',
'Students With Disability',
'Students Without Disability'
)
sidebar_menu <-
dashboardSidebar(
sidebarMenu(
menuItem("Chart", tabName = 'graph', icon = icon('bar-chart-o')),
menuItem("Table", tabName = 'table1', icon = icon('table')),
menuItem("Data Download", tabName = 'downloader_tab', icon = icon('save')),
menuItem(
'Groups of Interest',
tabname = 'slider',
icon = icon('user'),
## this puts the option in a drop down
selectInput(
'groups',
"Click to select 1+ group(s):",
multiple = TRUE,
selected = student_groups_vector,
choices = student_groups_vector
)
),
## install the package with this
## devtools::install_github('https://github.com/daqana/dqshiny')
dqshiny::autocomplete_input(
'school_names_manual',
'Type school name for only one plot',
options = unique(dat$instn_name),
value = "Appling County High School",
width = NULL,
placeholder = 'autofill on',
max_options = 0,
hide_values = FALSE
)
)
)
body_tabs <-
tabItems(
tabItem('graph',
plotOutput("plot1", height = 600),
box(downloadButton("plot_downloader", "Download Plot", icon = icon('save')))),
tabItem('table1',
reactable::reactableOutput("table1"),
box(downloadButton("downloadData", label = "Download Selected Data"))
),
tabItem('downloader_tab',
box(downloadButton("data_downloader", "Download All Data", icon = icon('download')))
)
)
ui <- dashboardPage(
dashboardHeader(title = "Loan & Klaas Final"),
sidebar_menu,
dashboardBody(
# Boxes need to be put in a row (or column)
fluidPage(
#title = 'plots',
body_tabs)
),
skin = c('black'))
server <- function(input, output) {
datasetInput <-reactive({ dat %>%
select_groups(groups_of_interest = input$groups) %>%
select_schools(schools_of_interest = input$school_names_manual) %>%
mutate_if(is.numeric, round, 2) %>%
reactable(filterable = T)
}
)
# reactive_school_name <- reactive({input$school_names_manual})
output$plot1 <- renderPlot({
plots <- grad_year_plots(
dat,
groups_of_interest = input$groups,
schools_of_interest = input$school_names_manual)
plt <- plots$plot[[1]]
plt + theme_minimal(base_size = 18) + theme(legend.position = 'bottom')
})
table_download <-reactive({dat %>%
select_groups(groups_of_interest = input$groups) %>%
select_schools(schools_of_interest = input$school_names_manual) %>%
mutate_if(is.numeric, round, 2)})
output$table1 <- renderReactable({
table_download() %>%
reactable(filterable = T)
})
output$data_downloader <- downloadHandler(
filename = 'full_data.csv',
content = function(file) {
write.csv(dat, file)
}
)
output$downloadData <- downloadHandler(
filename = function() {
paste("Data", input$school_names_manual,".csv", sep = " ") #customize school name for data
},
content = function(file) {
write.csv(table_download(), file)
}
)
output$plot_downloader <- downloadHandler(
filename = function() {
paste("Plot", input$school_names_manual,".png", sep = " ") #customize school name for plot
},
content = function(file){
plots <- grad_year_plots(
dat,
groups_of_interest = input$groups,
schools_of_interest = input$school_names_manual)
plt <- plots$plot[[1]]
ggsave(file, width = 10, plot=plt) #change the width to 10 to prevent the legend from clipping
}
)
}
shinyApp(ui, server)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/events.R
\name{read_events_ndb}
\alias{read_events_ndb}
\title{Read events from a Resmed Noxturnal .ndb file.}
\usage{
read_events_ndb(data_file)
}
\arguments{
\item{data_file}{.ndb file path.}
}
\value{
An events dataframe.
}
\description{
Read events from a Resmed Noxturnal .ndb file.
}
| /man/read_events_ndb.Rd | permissive | cran/rsleep | R | false | true | 368 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/events.R
\name{read_events_ndb}
\alias{read_events_ndb}
\title{Read events from a Resmed Noxturnal .ndb file.}
\usage{
read_events_ndb(data_file)
}
\arguments{
\item{data_file}{.ndb file path.}
}
\value{
An events dataframe.
}
\description{
Read events from a Resmed Noxturnal .ndb file.
}
|
library(DESeq2)
a = read.table (file = "superEnhancer_counts.txt",header = T,sep = "\t",row.names = 1)
coldata = read.table(file = "superEnhancer_names.txt",header = T,sep = "\t")[,]
dso = DESeqDataSetFromMatrix(countData = a,colData = coldata,design = ~ Sample)
dsoA<-DESeq(dso )
write.table((results(dsoA)),file="results.txt",sep = "\t",quote = F)
pdf(file = "PCA.pdf")
plotPCA(rlog(dsoA),intgroup=c("pair"),ntop = 1000)
dev.off()
| /program/DESeq2_analysis.R | no_license | BIT-VS-IT/SuperEnhancer_pipeline | R | false | false | 439 | r | library(DESeq2)
a = read.table (file = "superEnhancer_counts.txt",header = T,sep = "\t",row.names = 1)
coldata = read.table(file = "superEnhancer_names.txt",header = T,sep = "\t")[,]
dso = DESeqDataSetFromMatrix(countData = a,colData = coldata,design = ~ Sample)
dsoA<-DESeq(dso )
write.table((results(dsoA)),file="results.txt",sep = "\t",quote = F)
pdf(file = "PCA.pdf")
plotPCA(rlog(dsoA),intgroup=c("pair"),ntop = 1000)
dev.off()
|
#### Aman ####
############## Assignment 6 - Factor Analysis #####################
##############################################################################
##############################################################################
# clear environment
rm(list = ls())
# defining libraries
library(ggplot2)
library(dplyr)
library(PerformanceAnalytics)
library(data.table)
library(sqldf)
library(nortest)
library(MASS)
library(rpart)
library(class)
library(ISLR)
library(scales)
library(ClustOfVar)
library(GGally)
library(reticulate)
library(ggthemes)
library(RColorBrewer)
library(gridExtra)
library(kableExtra)
library(Hmisc)
library(corrplot)
library(energy)
library(nnet)
library(Hotelling)
library(car)
library(devtools)
library(ggbiplot)
library(factoextra)
library(rgl)
library(FactoMineR)
library(psych)
library(nFactors)
library(scatterplot3d)
# reading data
data <- read.csv('/Users/mac/Downloads/heart_failure_clinical_records_dataset.csv')
str(data)
# Let's quickly revise our correlation plot and see if factor analysis is appropriate
# Correlation plot
M<-cor(data)
head(round(M,2))
corrplot(M, method="color")
#Since most of the correlations are low (Pearson's r < 0.25) ),
#we don't particularly see a need for Factor Analysis since
#we use Factor Analysis to understand the latent factors in the data
#However, we can see that given these are patient details, we may
#try and understand factors such as patient demographics (age, sex),
#patient lifestyle (smoking, diabetes, high bp), patient physiological
#makeup (serum sodidum, creatinine_phosphokinase), patient genetics
#(bp, anaemia). While this is our intuition before we begin,
#only once we see the factor analysis results will we be able to
#comment more appropriately.
#scale the data
data_fact <- as.data.frame(scale(data[,1:12],center = TRUE, scale = TRUE))
# Tests to see if factor analysis is appropriate on the data
KMO(data_fact)
### Bartlett’s test
#We also perform the Bartlett’s test which allows us to
#compare the variance of two or more samples to determine
#whether they are drawn from populations with equal variance.
bartlett.test(data_fact)
# Let us now perform Factor Anaysis on our dataset
# perform factor analysis
data.fa <- factanal(data_fact, factors = 2)
data.fa
#Here, we see high uniqueness (>0.7) for most variables indicating that factors
#don't account well for the variance. But we do note that sex variable
#has the least uniqueness (0.233).
#We also note that cumulative variance explained is only 15.8% which isn't
#great and we may have to use more than 2 factors
#squaring the loadings to assess communality
apply(data.fa$loadings^2,1,sum)
# Let's try and interpret the factors
#We perform three factor models - one with no rotation, one with varimax rotation,
#and finally one with promax rotation and see the results
data.fa.none <- factanal(data_fact, factors = 2, rotation = "none")
data.fa.varimax <- factanal(data_fact, factors = 2, rotation = "varimax")
data.fa.promax <- factanal(data_fact, factors = 2, rotation = "promax")
par(mfrow = c(1,3))
plot(data.fa.none$loadings[,1],
data.fa.none$loadings[,2],
xlab = "Factor 1",
ylab = "Factor 2",
ylim = c(-1,1),
xlim = c(-1,1),
main = "No rotation")
abline(h = 0, v = 0)
plot(data.fa.varimax$loadings[,1],
data.fa.varimax$loadings[,2],
xlab = "Factor 1",
ylab = "Factor 2",
ylim = c(-1,1),
xlim = c(-1,1),
main = "Varimax rotation")
text(data.fa.varimax$loadings[,1]-0.08,
data.fa.varimax$loadings[,2]+0.08,
colnames(data),
col="blue")
abline(h = 0, v = 0)
plot(data.fa.promax$loadings[,1],
data.fa.promax$loadings[,2],
xlab = "Factor 1",
ylab = "Factor 2",
ylim = c(-1,1),
xlim = c(-1,1),
main = "Promax rotation")
abline(h = 0, v = 0)
#We can see that factor 1 corresponds to smoking, sex, platelets,
#, ejection_fraction and diabetes whereas factor 2 corresponds to
#age, anaemia, high bp, serum_creatinine and time among others.
#We cannot clearly name the factors at this point in line with
#our intuition.
# Let's plot the results
### Maximum Likelihood Factor Analysis with 2 factors
# Maximum Likelihood Factor Analysis
# entering raw data and extracting 2 factors,
# with varimax rotation
fit <- factanal(data_fact, 2, rotation="varimax")
# plot factor 1 by factor 2
load <- fit$loadings[,1:2]
plot(load,type="n") # set up plot
text(load,labels=names(data_fact),cex=.7) # add variable names```
# However, there is a better method to first determine number of Factors to Extract
ev <- eigen(cor(data_fact)) # get eigenvalues
ap <- parallel(subject=nrow(data_fact),var=ncol(data_fact),
rep=100,cent=.05)
nS <- nScree(x=ev$values, aparallel=ap$eigen$qevpea)
plotnScree(nS)
#This is interesting now since our interpretation might be more relevant with
#3 factors.
# Factor Analysis (n=3 factors)
data.fa.none <- factanal(data_fact, factors = 3, rotation = "none")
data.fa.none
scatterplot3d(as.data.frame(unclass(data.fa.none$loadings)),
main="3D factor loadings", color=1:ncol(data_fact), pch=20)
pairs(data.fa.none$loadings, col=1:ncol(data_fact),
upper.panel=NULL, main="Factor loadings")
par(xpd=TRUE)
legend('topright', bty='n', pch='o', col=1:ncol(data_fact), y.intersp=0.5,
attr(data.fa.none$loadings, 'dimnames')[[1]], title="Variables")
#This is a lot more interesting since now if we try and interpret the 3 factors we see
#that Factor 1 is sex, smoking dominant while factor 2 is ejection_fraction
#and serum component dominant while factor 3 is age, anaemia, high bp
#dominant. While not exactly the same as intuition, we do note
#that Factor 1 can be interpreted as patient demographics/ lifestyle
#feature as males tend to smoke more, while factor 2 is
#the physiological makeup we discussed about earlier and
#factor 3 is the again patient demographics but also genetics
#as variables with blood pressure and anaemia show up along with age.
### Conclusion -
### Factor 1 - Patient Demographics / Lifestyle
### Factor 2 - Patient Physiological Makeup
### Factor 3 - Patient Demographics / Genetics
# Factor Analysis (n=4 factors)
data.fa.none <- factanal(data_fact, factors = 4, rotation = "none")
data.fa.none
pairs(data.fa.none$loadings, col=1:ncol(data_fact),
upper.panel=NULL, main="Factor loadings")
par(xpd=TRUE)
legend('topright', bty='n', pch='o', col=1:ncol(data_fact), y.intersp=0.5,
attr(data.fa.none$loadings, 'dimnames')[[1]], title="Variables")
#Again an interesting result since if we try and interpret the 4 factors we see
#that Factor 1 is serum_sodium dominant (Physiological makeup),
#while Factor 2 is sex and smoking dominant (Patient Lifestyle)
#and Factor 3 is serum_sodium and high bp dominant (Physiological makeup
# & lifestyle) and Factor 4 is age, anaemia dominant (Patient Demographics
#& genetics). We notice some overlaps here so perhaps, 3 factors would be
#the ideal choice, however do note that p-values aren't significant in
# either results.
### Conclusion -
### Factor 1 - Physiological makeup
### Factor 2 - Patient Lifestyle
### Factor 3 - Physiological makeup & lifestyle
### Factor 4 - Patient demographics & Genetics
### Another method - we can try the psych package as well for n=3 factors
fit.pc <- principal(data_fact, nfactors=3, rotate="varimax")
fit.pc
round(fit.pc$values, 3)
fit.pc$loadings
# Loadings with more digits
for (i in c(1,2,3)) { print(fit.pc$loadings[[1,i]])}
# Communalities
fit.pc$communality
# Play with FA utilities
fa.parallel(data_fact) # See factor recommendation
fa.plot(fit.pc) # See Correlations within Factors
fa.diagram(fit.pc) # Visualize the relationship
vss(data_fact) # See Factor recommendations for a simple structure
#Note: While we see our data isn't perhaps ideal for Factor Analysis,
#we can gauge some interesting results and given this dataset is
##part of a study of only 299 patients, the latent factors
#may be more prominent in the population distribution.
##### This concludes our approach to Factor Analysis in our dataset ######
###############################################################
| /R codes/MVA_Assignment_6.R | permissive | ag77in/HeartFailurePrediction-MVA | R | false | false | 8,230 | r | #### Aman ####
############## Assignment 6 - Factor Analysis #####################
##############################################################################
##############################################################################
# clear environment
rm(list = ls())
# defining libraries
library(ggplot2)
library(dplyr)
library(PerformanceAnalytics)
library(data.table)
library(sqldf)
library(nortest)
library(MASS)
library(rpart)
library(class)
library(ISLR)
library(scales)
library(ClustOfVar)
library(GGally)
library(reticulate)
library(ggthemes)
library(RColorBrewer)
library(gridExtra)
library(kableExtra)
library(Hmisc)
library(corrplot)
library(energy)
library(nnet)
library(Hotelling)
library(car)
library(devtools)
library(ggbiplot)
library(factoextra)
library(rgl)
library(FactoMineR)
library(psych)
library(nFactors)
library(scatterplot3d)
# reading data
data <- read.csv('/Users/mac/Downloads/heart_failure_clinical_records_dataset.csv')
str(data)
# Let's quickly revise our correlation plot and see if factor analysis is appropriate
# Correlation plot
M<-cor(data)
head(round(M,2))
corrplot(M, method="color")
#Since most of the correlations are low (Pearson's r < 0.25) ),
#we don't particularly see a need for Factor Analysis since
#we use Factor Analysis to understand the latent factors in the data
#However, we can see that given these are patient details, we may
#try and understand factors such as patient demographics (age, sex),
#patient lifestyle (smoking, diabetes, high bp), patient physiological
#makeup (serum sodidum, creatinine_phosphokinase), patient genetics
#(bp, anaemia). While this is our intuition before we begin,
#only once we see the factor analysis results will we be able to
#comment more appropriately.
#scale the data
data_fact <- as.data.frame(scale(data[,1:12],center = TRUE, scale = TRUE))
# Tests to see if factor analysis is appropriate on the data
KMO(data_fact)
### Bartlett’s test
#We also perform the Bartlett’s test which allows us to
#compare the variance of two or more samples to determine
#whether they are drawn from populations with equal variance.
bartlett.test(data_fact)
# Let us now perform Factor Anaysis on our dataset
# perform factor analysis
data.fa <- factanal(data_fact, factors = 2)
data.fa
#Here, we see high uniqueness (>0.7) for most variables indicating that factors
#don't account well for the variance. But we do note that sex variable
#has the least uniqueness (0.233).
#We also note that cumulative variance explained is only 15.8% which isn't
#great and we may have to use more than 2 factors
#squaring the loadings to assess communality
apply(data.fa$loadings^2,1,sum)
# Let's try and interpret the factors
#We perform three factor models - one with no rotation, one with varimax rotation,
#and finally one with promax rotation and see the results
data.fa.none <- factanal(data_fact, factors = 2, rotation = "none")
data.fa.varimax <- factanal(data_fact, factors = 2, rotation = "varimax")
data.fa.promax <- factanal(data_fact, factors = 2, rotation = "promax")
par(mfrow = c(1,3))
plot(data.fa.none$loadings[,1],
data.fa.none$loadings[,2],
xlab = "Factor 1",
ylab = "Factor 2",
ylim = c(-1,1),
xlim = c(-1,1),
main = "No rotation")
abline(h = 0, v = 0)
plot(data.fa.varimax$loadings[,1],
data.fa.varimax$loadings[,2],
xlab = "Factor 1",
ylab = "Factor 2",
ylim = c(-1,1),
xlim = c(-1,1),
main = "Varimax rotation")
text(data.fa.varimax$loadings[,1]-0.08,
data.fa.varimax$loadings[,2]+0.08,
colnames(data),
col="blue")
abline(h = 0, v = 0)
plot(data.fa.promax$loadings[,1],
data.fa.promax$loadings[,2],
xlab = "Factor 1",
ylab = "Factor 2",
ylim = c(-1,1),
xlim = c(-1,1),
main = "Promax rotation")
abline(h = 0, v = 0)
#We can see that factor 1 corresponds to smoking, sex, platelets,
#, ejection_fraction and diabetes whereas factor 2 corresponds to
#age, anaemia, high bp, serum_creatinine and time among others.
#We cannot clearly name the factors at this point in line with
#our intuition.
# Let's plot the results
### Maximum Likelihood Factor Analysis with 2 factors
# Maximum Likelihood Factor Analysis
# entering raw data and extracting 2 factors,
# with varimax rotation
fit <- factanal(data_fact, 2, rotation="varimax")
# plot factor 1 by factor 2
load <- fit$loadings[,1:2]
plot(load,type="n") # set up plot
text(load,labels=names(data_fact),cex=.7) # add variable names```
# However, there is a better method to first determine number of Factors to Extract
ev <- eigen(cor(data_fact)) # get eigenvalues
ap <- parallel(subject=nrow(data_fact),var=ncol(data_fact),
rep=100,cent=.05)
nS <- nScree(x=ev$values, aparallel=ap$eigen$qevpea)
plotnScree(nS)
#This is interesting now since our interpretation might be more relevant with
#3 factors.
# Factor Analysis (n=3 factors)
data.fa.none <- factanal(data_fact, factors = 3, rotation = "none")
data.fa.none
scatterplot3d(as.data.frame(unclass(data.fa.none$loadings)),
main="3D factor loadings", color=1:ncol(data_fact), pch=20)
pairs(data.fa.none$loadings, col=1:ncol(data_fact),
upper.panel=NULL, main="Factor loadings")
par(xpd=TRUE)
legend('topright', bty='n', pch='o', col=1:ncol(data_fact), y.intersp=0.5,
attr(data.fa.none$loadings, 'dimnames')[[1]], title="Variables")
#This is a lot more interesting since now if we try and interpret the 3 factors we see
#that Factor 1 is sex, smoking dominant while factor 2 is ejection_fraction
#and serum component dominant while factor 3 is age, anaemia, high bp
#dominant. While not exactly the same as intuition, we do note
#that Factor 1 can be interpreted as patient demographics/ lifestyle
#feature as males tend to smoke more, while factor 2 is
#the physiological makeup we discussed about earlier and
#factor 3 is the again patient demographics but also genetics
#as variables with blood pressure and anaemia show up along with age.
### Conclusion -
### Factor 1 - Patient Demographics / Lifestyle
### Factor 2 - Patient Physiological Makeup
### Factor 3 - Patient Demographics / Genetics
# Factor Analysis (n=4 factors)
data.fa.none <- factanal(data_fact, factors = 4, rotation = "none")
data.fa.none
pairs(data.fa.none$loadings, col=1:ncol(data_fact),
upper.panel=NULL, main="Factor loadings")
par(xpd=TRUE)
legend('topright', bty='n', pch='o', col=1:ncol(data_fact), y.intersp=0.5,
attr(data.fa.none$loadings, 'dimnames')[[1]], title="Variables")
#Again an interesting result since if we try and interpret the 4 factors we see
#that Factor 1 is serum_sodium dominant (Physiological makeup),
#while Factor 2 is sex and smoking dominant (Patient Lifestyle)
#and Factor 3 is serum_sodium and high bp dominant (Physiological makeup
# & lifestyle) and Factor 4 is age, anaemia dominant (Patient Demographics
#& genetics). We notice some overlaps here so perhaps, 3 factors would be
#the ideal choice, however do note that p-values aren't significant in
# either results.
### Conclusion -
### Factor 1 - Physiological makeup
### Factor 2 - Patient Lifestyle
### Factor 3 - Physiological makeup & lifestyle
### Factor 4 - Patient demographics & Genetics
### Another method - we can try the psych package as well for n=3 factors
fit.pc <- principal(data_fact, nfactors=3, rotate="varimax")
fit.pc
round(fit.pc$values, 3)
fit.pc$loadings
# Loadings with more digits
for (i in c(1,2,3)) { print(fit.pc$loadings[[1,i]])}
# Communalities
fit.pc$communality
# Play with FA utilities
fa.parallel(data_fact) # See factor recommendation
fa.plot(fit.pc) # See Correlations within Factors
fa.diagram(fit.pc) # Visualize the relationship
vss(data_fact) # See Factor recommendations for a simple structure
#Note: While we see our data isn't perhaps ideal for Factor Analysis,
#we can gauge some interesting results and given this dataset is
##part of a study of only 299 patients, the latent factors
#may be more prominent in the population distribution.
##### This concludes our approach to Factor Analysis in our dataset ######
###############################################################
|
library(rmr)
rmr.options.set(backend="local")
n = 10
m = 5
p = 10
A = matrix(rnorm(n*(m+1)), nrow=n, ncol=m+1)
A[,1] = as.integer(1:n)
B = matrix(rnorm(m*(p+1)), nrow=m, ncol=p+1)
B[,1] = as.integer(1:m)
write.table(A, file="~/Data/A.csv", sep=",", eol="\r\n", col.names=F, row.names=F)
write.table(B, file="~/Data/B.csv", sep=",", eol="\r\n", col.names=F, row.names=F)
left_mapper = function(null,row){
in_row = row[1]
point_generator = function(out_col) {
lapply(2:length(row), function(in_col)
keyval(c(row=unname(as.integer(in_row)), col=unname(as.integer(out_col))), list(i=in_col-1,val=row[in_col])))
}
rows_points = lapply(1:p, point_generator)
do.call(c, args=rows_points)
}
right_mapper = function(null,row){
in_row = row[1]
point_generator = function(out_row) {
lapply(2:length(row), function(in_col)
keyval(c(row=unname(as.integer(out_row)), col=unname(as.integer(in_col-1))), list(i=in_row,val=row[in_col])))
}
rows_points = lapply(1:n, point_generator)
do.call(c, args=rows_points)
}
is.even = function(num) num%%2 == 0
even_elements = function(v) {
v[is.even(1:length(v))]
}
odd_elements = function(v) {
v[!is.even(1:length(v))]
}
product_reducer = function(out_index, is_and_values){
is = unlist(lapply(is_and_values, function(ival) ival$i))
vals = unlist(lapply(is_and_values, function(ival) ival$val))
sorted_is = order(is)
product = even_elements(vals) * odd_elements(vals)
keyval(out_index["row"], list(col=out_index["col"], val=sum(product)))
}
to_row_reducer = function(row_index, cols_and_vals) {
cols = unlist(lapply(cols_and_vals,function(cv) cv$col))
vals = unlist(lapply(cols_and_vals,function(cv) cv$val))
col_order = order(cols)
keyval(NULL, c(row_index,vals[col_order]))
}
simple_csv_in=make.input.format("csv",sep=",")
left_intermediate = mapreduce("~/Data/A.csv", map = left_mapper, input.format=simple_csv_in)
right_intermediate = mapreduce("~/Data/B.csv", map = right_mapper, input.format=simple_csv_in)
merged_intermediate = mapreduce(list(left_intermediate, right_intermediate), reduce=product_reducer)
final_rows = mapreduce(merged_intermediate, reduce=to_row_reducer)
final_matrix = lapply(from.dfs(final_rows), function(kv)kv$val)
final_matrix = matrix(unlist(final_matrix),nrow=n, ncol=p+1, byrow=T)
final_matrix = final_matrix[order(final_matrix[,1]),2:ncol(final_matrix)]
print(final_matrix) | /Solutions/matrix.R | no_license | RodavLasIlad/rhadoop-examples | R | false | false | 2,405 | r | library(rmr)
rmr.options.set(backend="local")
n = 10
m = 5
p = 10
A = matrix(rnorm(n*(m+1)), nrow=n, ncol=m+1)
A[,1] = as.integer(1:n)
B = matrix(rnorm(m*(p+1)), nrow=m, ncol=p+1)
B[,1] = as.integer(1:m)
write.table(A, file="~/Data/A.csv", sep=",", eol="\r\n", col.names=F, row.names=F)
write.table(B, file="~/Data/B.csv", sep=",", eol="\r\n", col.names=F, row.names=F)
left_mapper = function(null,row){
in_row = row[1]
point_generator = function(out_col) {
lapply(2:length(row), function(in_col)
keyval(c(row=unname(as.integer(in_row)), col=unname(as.integer(out_col))), list(i=in_col-1,val=row[in_col])))
}
rows_points = lapply(1:p, point_generator)
do.call(c, args=rows_points)
}
right_mapper = function(null,row){
in_row = row[1]
point_generator = function(out_row) {
lapply(2:length(row), function(in_col)
keyval(c(row=unname(as.integer(out_row)), col=unname(as.integer(in_col-1))), list(i=in_row,val=row[in_col])))
}
rows_points = lapply(1:n, point_generator)
do.call(c, args=rows_points)
}
is.even = function(num) num%%2 == 0
even_elements = function(v) {
v[is.even(1:length(v))]
}
odd_elements = function(v) {
v[!is.even(1:length(v))]
}
product_reducer = function(out_index, is_and_values){
is = unlist(lapply(is_and_values, function(ival) ival$i))
vals = unlist(lapply(is_and_values, function(ival) ival$val))
sorted_is = order(is)
product = even_elements(vals) * odd_elements(vals)
keyval(out_index["row"], list(col=out_index["col"], val=sum(product)))
}
to_row_reducer = function(row_index, cols_and_vals) {
cols = unlist(lapply(cols_and_vals,function(cv) cv$col))
vals = unlist(lapply(cols_and_vals,function(cv) cv$val))
col_order = order(cols)
keyval(NULL, c(row_index,vals[col_order]))
}
simple_csv_in=make.input.format("csv",sep=",")
left_intermediate = mapreduce("~/Data/A.csv", map = left_mapper, input.format=simple_csv_in)
right_intermediate = mapreduce("~/Data/B.csv", map = right_mapper, input.format=simple_csv_in)
merged_intermediate = mapreduce(list(left_intermediate, right_intermediate), reduce=product_reducer)
final_rows = mapreduce(merged_intermediate, reduce=to_row_reducer)
final_matrix = lapply(from.dfs(final_rows), function(kv)kv$val)
final_matrix = matrix(unlist(final_matrix),nrow=n, ncol=p+1, byrow=T)
final_matrix = final_matrix[order(final_matrix[,1]),2:ncol(final_matrix)]
print(final_matrix) |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/normalization.R
\name{normalize_intensities}
\alias{normalize_intensities}
\title{Normalize intensities}
\usage{
normalize_intensities(ints)
}
\arguments{
\item{ints}{The slice intensities from a proteinGroups.txt file.}
}
\description{
Normalize intensities by dividing every entry by the total sum of
intensities over all slices and proteins. Gives back a data-frame
with normalized intensities.
}
\examples{
proteinGroups_path <-
system.file("extdata", "Conde_9508_sub.txt", package = "pumbaR")
pg <- load_MQ(proteinGroups_path)
ints <- get_intensities(pg)
norm_ints <- normalize_intensities(ints)
}
| /man/normalize_intensities.Rd | permissive | UNIL-PAF/pumbaR | R | false | true | 681 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/normalization.R
\name{normalize_intensities}
\alias{normalize_intensities}
\title{Normalize intensities}
\usage{
normalize_intensities(ints)
}
\arguments{
\item{ints}{The slice intensities from a proteinGroups.txt file.}
}
\description{
Normalize intensities by dividing every entry by the total sum of
intensities over all slices and proteins. Gives back a data-frame
with normalized intensities.
}
\examples{
proteinGroups_path <-
system.file("extdata", "Conde_9508_sub.txt", package = "pumbaR")
pg <- load_MQ(proteinGroups_path)
ints <- get_intensities(pg)
norm_ints <- normalize_intensities(ints)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/slim_lang.R
\name{addEmpty}
\alias{addEmpty}
\alias{Subpopulation$addEmpty}
\alias{.P$addEmpty}
\title{SLiM method addEmpty}
\usage{
addEmpty(sex)
}
\arguments{
\item{sex}{An object of type null or float or string. Must be of length 1 (a
singleton). The default value is \code{NULL}. See details for description.}
}
\value{
An object of type null or Individual object. Return will be of length 1
(a singleton)
}
\description{
Documentation for SLiM function \code{addEmpty}, which is a method of the SLiM
class \code{Subpopulation}.
Note that the R function is a stub, it does not do anything in R (except bring
up this documentation). It will only do
anything useful when used inside a \code{\link{slim_block}} function further
nested in a \code{\link{slim_script}}
function call, where it will be translated into valid SLiM code as part of a
full SLiM script.
}
\details{
Generates a new offspring individual with empty genomes (i.e.,
containing no mutations), queues it for addition to the target subpopulation,
and returns it. The new offspring will not be visible as a member of the target
subpopulation until the end of the offspring generation life cycle stage. No
recombination() or mutation() callbacks will be called. The target subpopulation
will be used to locate applicable modifyChild() callbacks governing the
generation of the offspring individual (unlike the other addX() methods, because
there is no parental individual to reference). The offspring is considered
to have no parents for the purposes of pedigree tracking. The sex parameter
is treated as in addCrossed(). Note that this method is only for use in nonWF
models. See addCrossed() for further general notes on the addition of new
offspring individuals.
}
\section{Copyright}{
This is documentation for a function in the SLiM software, and has been
reproduced from the official manual,
which can be found here: \url{http://benhaller.com/slim/SLiM_Manual.pdf}. This
documentation is
Copyright © 2016–2020 Philipp Messer. All rights reserved. More information
about SLiM can be found
on the official website: \url{https://messerlab.org/slim/}
}
\author{
Benjamin C Haller (\email{bhaller@benhaller.com}) and Philipp W Messer
(\email{messer@cornell.edu})
}
| /man/addEmpty.Rd | permissive | rdinnager/slimrlang | R | false | true | 2,315 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/slim_lang.R
\name{addEmpty}
\alias{addEmpty}
\alias{Subpopulation$addEmpty}
\alias{.P$addEmpty}
\title{SLiM method addEmpty}
\usage{
addEmpty(sex)
}
\arguments{
\item{sex}{An object of type null or float or string. Must be of length 1 (a
singleton). The default value is \code{NULL}. See details for description.}
}
\value{
An object of type null or Individual object. Return will be of length 1
(a singleton)
}
\description{
Documentation for SLiM function \code{addEmpty}, which is a method of the SLiM
class \code{Subpopulation}.
Note that the R function is a stub, it does not do anything in R (except bring
up this documentation). It will only do
anything useful when used inside a \code{\link{slim_block}} function further
nested in a \code{\link{slim_script}}
function call, where it will be translated into valid SLiM code as part of a
full SLiM script.
}
\details{
Generates a new offspring individual with empty genomes (i.e.,
containing no mutations), queues it for addition to the target subpopulation,
and returns it. The new offspring will not be visible as a member of the target
subpopulation until the end of the offspring generation life cycle stage. No
recombination() or mutation() callbacks will be called. The target subpopulation
will be used to locate applicable modifyChild() callbacks governing the
generation of the offspring individual (unlike the other addX() methods, because
there is no parental individual to reference). The offspring is considered
to have no parents for the purposes of pedigree tracking. The sex parameter
is treated as in addCrossed(). Note that this method is only for use in nonWF
models. See addCrossed() for further general notes on the addition of new
offspring individuals.
}
\section{Copyright}{
This is documentation for a function in the SLiM software, and has been
reproduced from the official manual,
which can be found here: \url{http://benhaller.com/slim/SLiM_Manual.pdf}. This
documentation is
Copyright © 2016–2020 Philipp Messer. All rights reserved. More information
about SLiM can be found
on the official website: \url{https://messerlab.org/slim/}
}
\author{
Benjamin C Haller (\email{bhaller@benhaller.com}) and Philipp W Messer
(\email{messer@cornell.edu})
}
|
testlist <- list(bytes1 = c(62720L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), pmutation = 0)
result <- do.call(mcga:::ByteCodeMutation,testlist)
str(result) | /mcga/inst/testfiles/ByteCodeMutation/libFuzzer_ByteCodeMutation/ByteCodeMutation_valgrind_files/1612803051-test.R | no_license | akhikolla/updatedatatype-list3 | R | false | false | 257 | r | testlist <- list(bytes1 = c(62720L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), pmutation = 0)
result <- do.call(mcga:::ByteCodeMutation,testlist)
str(result) |
readImage=function(fL){
mType=substring(fL,first=regexpr("\\.[^\\.]*$", fL)+1)
if(mType=='svg'){
if(!grepl('xml',readLines(fL,n = 1))) stop('svg not standalone')
paste0(
"data:image/svg+xml;utf8,"
,as.character(xml2::read_xml(fL))
)
}else{
base64enc::dataURI(file = fL,mime = sprintf('image/%s',mType))
}
} | /R/readImage.R | no_license | timelyportfolio/slickR | R | false | false | 345 | r | readImage=function(fL){
mType=substring(fL,first=regexpr("\\.[^\\.]*$", fL)+1)
if(mType=='svg'){
if(!grepl('xml',readLines(fL,n = 1))) stop('svg not standalone')
paste0(
"data:image/svg+xml;utf8,"
,as.character(xml2::read_xml(fL))
)
}else{
base64enc::dataURI(file = fL,mime = sprintf('image/%s',mType))
}
} |
#' Checks if Package is On CRAN/In Local Library
#'
#' Checks CRAN to determine if a package exists.
#'
#' @param package Name of package.
#' @param local logical. If \code{TRUE} checks user's local library for
#' existence; if \code{FALSE} \href{http://cran.r-project.org/}{CRAN} for the
#' package.
#' @keywords exists package
#' @export
#' @examples
#' \dontrun{
#' p_exists(pacman)
#' p_exists(pacman, FALSE)
#' p_exists(I_dont_exist)
#' }
p_exists <-
function (package, local = FALSE) {
## check if package is an object
if(!object_check(package) || !is.character(package)){
package <- as.character(substitute(package))
}
p_egg(package)
if (!local){
available_packages <- rownames(utils::available.packages())
package %in% available_packages
} else {
local_packages <- list.files(.libPaths())
package %in% local_packages
}
}
| /pacman/R/p_exists.R | no_license | ingted/R-Examples | R | false | false | 943 | r | #' Checks if Package is On CRAN/In Local Library
#'
#' Checks CRAN to determine if a package exists.
#'
#' @param package Name of package.
#' @param local logical. If \code{TRUE} checks user's local library for
#' existence; if \code{FALSE} \href{http://cran.r-project.org/}{CRAN} for the
#' package.
#' @keywords exists package
#' @export
#' @examples
#' \dontrun{
#' p_exists(pacman)
#' p_exists(pacman, FALSE)
#' p_exists(I_dont_exist)
#' }
p_exists <-
function (package, local = FALSE) {
## check if package is an object
if(!object_check(package) || !is.character(package)){
package <- as.character(substitute(package))
}
p_egg(package)
if (!local){
available_packages <- rownames(utils::available.packages())
package %in% available_packages
} else {
local_packages <- list.files(.libPaths())
package %in% local_packages
}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/kimma_lm.R
\name{kimma_lm}
\alias{kimma_lm}
\title{Run kimma linear model}
\usage{
kimma_lm(model_lm, to_model_gene, gene, use_weights, metrics)
}
\arguments{
\item{model_lm}{Character model created in kmFit}
\item{to_model_gene}{Data frame formatted in kmFit, subset to gene of interest}
\item{gene}{Character of gene to model}
\item{use_weights}{Logical if gene specific weights should be used in model. Default is FALSE}
\item{metrics}{Logical if should calculate model fit metrics such as AIC, BIC, R-squared. Default is FALSE}
}
\value{
Linear model results data frame for 1 gene
}
\description{
Run kimma linear model
}
\keyword{internal}
| /man/kimma_lm.Rd | permissive | BIGslu/kimma | R | false | true | 727 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/kimma_lm.R
\name{kimma_lm}
\alias{kimma_lm}
\title{Run kimma linear model}
\usage{
kimma_lm(model_lm, to_model_gene, gene, use_weights, metrics)
}
\arguments{
\item{model_lm}{Character model created in kmFit}
\item{to_model_gene}{Data frame formatted in kmFit, subset to gene of interest}
\item{gene}{Character of gene to model}
\item{use_weights}{Logical if gene specific weights should be used in model. Default is FALSE}
\item{metrics}{Logical if should calculate model fit metrics such as AIC, BIC, R-squared. Default is FALSE}
}
\value{
Linear model results data frame for 1 gene
}
\description{
Run kimma linear model
}
\keyword{internal}
|
GO_Barplot <- function(data = GOresult,
plotname = "Barplot(GO).pdf",
outputworkdic=TRUE
) {
stopifnot(is.logical(outputworkdic))
#data preprocessing
BP_data <- data$`BP_result`
CC_data <- data$`CC_result`
MF_data <- data$`MF_result`
BP_rank <- BP_data[order(BP_data[,"p.adjust"]),]
CC_rank <- CC_data[order(CC_data[,"p.adjust"]),]
MF_rank <- MF_data[order(MF_data[,"p.adjust"]),]
#extract the top 20 data
if(nrow(BP_rank)>20){
BP_PlotData <- BP_rank[1:20,c("Description", "Count")] }else{
BP_PlotData <- BP_rank[,c("Description", "Count")] }
if(nrow(CC_rank)>20){
CC_PlotData <- CC_rank[1:20,c("Description", "Count")] }else{
CC_PlotData <- CC_rank[,c("Description", "Count")] }
if(nrow(MF_rank)>20){
MF_PlotData <- MF_rank[1:20,c("Description", "Count")] }else{
MF_PlotData <- MF_rank[,c("Description", "Count")] }
#rbind
PlotData <- rbind(BP_PlotData, CC_PlotData, MF_PlotData)
Data <- as.numeric(PlotData[,"Count"])
name <- as.character(PlotData[,"Description"])
#plot
if(outputworkdic==TRUE){
pdf(plotname, width = 10.8+0.1365*nrow(PlotData), height = 5.28+0.045*max(nchar(name)))
}
else if(outputworkdic==FALSE){
pdf(paste(GO_Barplot_path, paste0(comp_name,'_',plotname), sep = "\\" ), width = 10.8+0.1365*nrow(PlotData), height = 5.28+0.045*max(nchar(name)))
}
if(0.0378*nchar(name[1]) >= 1.2){
par(mai=c(0.045*max(nchar(name))+0.28,0.0378*nchar(name[1]),1,0.6))
}else{
par(mai = c(0.045*max(nchar(name))+0.28,1.2,1,0.6))
}
xbar=barplot(Data, space =0.5, las = 2, col =c(rep("firebrick1",nrow(BP_PlotData)),rep("goldenrod1",nrow(CC_PlotData)),rep("deepskyblue2",nrow(MF_PlotData))),
border = NA, main = 'Gene Function Classification (GO)', ylab = 'Numbers of genes', xpd = T, axisnames = T,
cex.main=1, cex.axis = 0.7, ylim=c(0, max(Data)+3))
legend("topright", legend = c("Biological Process","Cellular Component","Molecular Function"), fill=c("firebrick1","goldenrod1","deepskyblue2"),cex = 0.7, border = NA)
text(x=xbar, y=-(0.02*max(Data)+0.12), labels = name, srt = 50, adj = 1, xpd = T, cex = 0.7)
dev.off()
} | /code_source/8_GO_Barplot.R | no_license | nameOnStone/object_R | R | false | false | 2,122 | r | GO_Barplot <- function(data = GOresult,
plotname = "Barplot(GO).pdf",
outputworkdic=TRUE
) {
stopifnot(is.logical(outputworkdic))
#data preprocessing
BP_data <- data$`BP_result`
CC_data <- data$`CC_result`
MF_data <- data$`MF_result`
BP_rank <- BP_data[order(BP_data[,"p.adjust"]),]
CC_rank <- CC_data[order(CC_data[,"p.adjust"]),]
MF_rank <- MF_data[order(MF_data[,"p.adjust"]),]
#extract the top 20 data
if(nrow(BP_rank)>20){
BP_PlotData <- BP_rank[1:20,c("Description", "Count")] }else{
BP_PlotData <- BP_rank[,c("Description", "Count")] }
if(nrow(CC_rank)>20){
CC_PlotData <- CC_rank[1:20,c("Description", "Count")] }else{
CC_PlotData <- CC_rank[,c("Description", "Count")] }
if(nrow(MF_rank)>20){
MF_PlotData <- MF_rank[1:20,c("Description", "Count")] }else{
MF_PlotData <- MF_rank[,c("Description", "Count")] }
#rbind
PlotData <- rbind(BP_PlotData, CC_PlotData, MF_PlotData)
Data <- as.numeric(PlotData[,"Count"])
name <- as.character(PlotData[,"Description"])
#plot
if(outputworkdic==TRUE){
pdf(plotname, width = 10.8+0.1365*nrow(PlotData), height = 5.28+0.045*max(nchar(name)))
}
else if(outputworkdic==FALSE){
pdf(paste(GO_Barplot_path, paste0(comp_name,'_',plotname), sep = "\\" ), width = 10.8+0.1365*nrow(PlotData), height = 5.28+0.045*max(nchar(name)))
}
if(0.0378*nchar(name[1]) >= 1.2){
par(mai=c(0.045*max(nchar(name))+0.28,0.0378*nchar(name[1]),1,0.6))
}else{
par(mai = c(0.045*max(nchar(name))+0.28,1.2,1,0.6))
}
xbar=barplot(Data, space =0.5, las = 2, col =c(rep("firebrick1",nrow(BP_PlotData)),rep("goldenrod1",nrow(CC_PlotData)),rep("deepskyblue2",nrow(MF_PlotData))),
border = NA, main = 'Gene Function Classification (GO)', ylab = 'Numbers of genes', xpd = T, axisnames = T,
cex.main=1, cex.axis = 0.7, ylim=c(0, max(Data)+3))
legend("topright", legend = c("Biological Process","Cellular Component","Molecular Function"), fill=c("firebrick1","goldenrod1","deepskyblue2"),cex = 0.7, border = NA)
text(x=xbar, y=-(0.02*max(Data)+0.12), labels = name, srt = 50, adj = 1, xpd = T, cex = 0.7)
dev.off()
} |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/nrrd-io.R
\name{read.nrrd}
\alias{read.nrrd}
\alias{read.nrrd.header}
\title{Read nrrd file into an array in memory}
\usage{
read.nrrd(file, origin = NULL, ReadData = TRUE, AttachFullHeader = TRUE,
Verbose = FALSE, ReadByteAsRaw = c("unsigned", "all", "none"))
read.nrrd.header(file, Verbose = FALSE)
}
\arguments{
\item{file}{Path to a nrrd (or a connection for \code{read.nrrd.header})}
\item{origin}{Add a user specified origin (x,y,z) to the returned object}
\item{ReadData}{When FALSE just return attributes (i.e. the nrrd header)}
\item{AttachFullHeader}{Include the full nrrd header as an attribute of the
returned object (default TRUE)}
\item{Verbose}{Status messages while reading}
\item{ReadByteAsRaw}{Either a character vector or a logical vector specifying
when R should read 8 bit data as an R \code{raw} vector rather than
\code{integer} vector.}
}
\value{
An \code{array} object, optionally with attributes from the nrrd
header.
A list with elements for the key nrrd header fields
}
\description{
Read nrrd file into an array in memory
Read the (text) header of a NRRD format file
}
\details{
\code{read.nrrd} reads data into a raw array. If you wish to
generate a \code{\link{im3d}} object that includes spatial calibration (but
is limited to representing 3D data) then you should use
\code{\link{read.im3d}}.
ReadByteAsRaw=unsigned (the default) only reads unsigned byte data as a raw
array. This saves quite a bit of space and still allows data to be used for
logical indexing.
}
\seealso{
\code{\link{write.nrrd}}, \code{\link{read.im3d}}
}
| /man/read.nrrd.Rd | no_license | naveedst/nat | R | false | true | 1,670 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/nrrd-io.R
\name{read.nrrd}
\alias{read.nrrd}
\alias{read.nrrd.header}
\title{Read nrrd file into an array in memory}
\usage{
read.nrrd(file, origin = NULL, ReadData = TRUE, AttachFullHeader = TRUE,
Verbose = FALSE, ReadByteAsRaw = c("unsigned", "all", "none"))
read.nrrd.header(file, Verbose = FALSE)
}
\arguments{
\item{file}{Path to a nrrd (or a connection for \code{read.nrrd.header})}
\item{origin}{Add a user specified origin (x,y,z) to the returned object}
\item{ReadData}{When FALSE just return attributes (i.e. the nrrd header)}
\item{AttachFullHeader}{Include the full nrrd header as an attribute of the
returned object (default TRUE)}
\item{Verbose}{Status messages while reading}
\item{ReadByteAsRaw}{Either a character vector or a logical vector specifying
when R should read 8 bit data as an R \code{raw} vector rather than
\code{integer} vector.}
}
\value{
An \code{array} object, optionally with attributes from the nrrd
header.
A list with elements for the key nrrd header fields
}
\description{
Read nrrd file into an array in memory
Read the (text) header of a NRRD format file
}
\details{
\code{read.nrrd} reads data into a raw array. If you wish to
generate a \code{\link{im3d}} object that includes spatial calibration (but
is limited to representing 3D data) then you should use
\code{\link{read.im3d}}.
ReadByteAsRaw=unsigned (the default) only reads unsigned byte data as a raw
array. This saves quite a bit of space and still allows data to be used for
logical indexing.
}
\seealso{
\code{\link{write.nrrd}}, \code{\link{read.im3d}}
}
|
if (exists("A_A")) remove("A_A")
if (exists("A_U")) remove("A_U")
if (exists("C_A")) remove("C_A")
if (exists("C_U")) remove("C_U")
A_U<-c(92710,90085,80809,85977,94802,80040,105577,74784,77845,79678,73922,90981,96079,76931,76361,82873,76114,78470,75277,83844,75930,78514,78136,74591,76473,76104,86966,98003,123623,141054,116141,86014,95191,74868,75295,75896,78209,75211,76295,84625,98047,79749,76699,75893,76630,74912,91525,82150,74672,77540)
A_A<-c(287192,96426,90396,83582,89111,90408,81799,80456,80735,79885,75971,76705,89731,78503,77504,81621,77467,80955,81338,81879,77962,76998,80242,78023,83491,80443,80269,85482,130389,104433,117277,108767,87043,108931,79228,82189,81144,79198,77833,80372,82813,75985,78619,80205,81755,81562,79655,84933,92954,78531)
if (exists("A_U")) boxplot.stats(A_U)
if (exists("A_A")) boxplot.stats(A_A)
if (exists("C_U")) boxplot.stats(C_U)
if (exists("C_A")) boxplot.stats(C_A)
if (exists("A_U")) summary(A_U)
if (exists("A_A")) summary(A_A)
if (exists("C_U")) summary(C_U)
if (exists("C_A")) summary(C_A)
if (exists("A_U")) boxplot(A_A,A_U,col="lightblue",horizontal=TRUE,log="x",match=TRUE,names=c("(A_A)","(A_U)"),notch=TRUE)
if (exists("C_U")) boxplot(C_A,C_U,col="lightblue",horizontal=TRUE,log="x",match=TRUE,names=c("(C_A)","(C_U)"),notch=TRUE)
| /REPSI_Tool_02.00_Mesaurement_Data/Query_99999_YYYY-MM-DD_HH-MI-SS.HS.R/Query_87402_2007-01-30_14-42-11.046.R | permissive | walter-weinmann/repsi-tool | R | false | false | 1,284 | r | if (exists("A_A")) remove("A_A")
if (exists("A_U")) remove("A_U")
if (exists("C_A")) remove("C_A")
if (exists("C_U")) remove("C_U")
A_U<-c(92710,90085,80809,85977,94802,80040,105577,74784,77845,79678,73922,90981,96079,76931,76361,82873,76114,78470,75277,83844,75930,78514,78136,74591,76473,76104,86966,98003,123623,141054,116141,86014,95191,74868,75295,75896,78209,75211,76295,84625,98047,79749,76699,75893,76630,74912,91525,82150,74672,77540)
A_A<-c(287192,96426,90396,83582,89111,90408,81799,80456,80735,79885,75971,76705,89731,78503,77504,81621,77467,80955,81338,81879,77962,76998,80242,78023,83491,80443,80269,85482,130389,104433,117277,108767,87043,108931,79228,82189,81144,79198,77833,80372,82813,75985,78619,80205,81755,81562,79655,84933,92954,78531)
if (exists("A_U")) boxplot.stats(A_U)
if (exists("A_A")) boxplot.stats(A_A)
if (exists("C_U")) boxplot.stats(C_U)
if (exists("C_A")) boxplot.stats(C_A)
if (exists("A_U")) summary(A_U)
if (exists("A_A")) summary(A_A)
if (exists("C_U")) summary(C_U)
if (exists("C_A")) summary(C_A)
if (exists("A_U")) boxplot(A_A,A_U,col="lightblue",horizontal=TRUE,log="x",match=TRUE,names=c("(A_A)","(A_U)"),notch=TRUE)
if (exists("C_U")) boxplot(C_A,C_U,col="lightblue",horizontal=TRUE,log="x",match=TRUE,names=c("(C_A)","(C_U)"),notch=TRUE)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/warpVCF.R
\name{warpVCF}
\alias{warpVCF}
\title{Warping utility}
\usage{
warpVCF(x, t_srs, nodata = NULL, filename, res = 30, method = "bilinear",
mc.cores = 1, run = TRUE, ...)
}
\arguments{
\item{x}{character or list of character, the filenames of files to be
warpped. The list can easily be retrieved using a call such as
\code{list.files('/path/to/data/', full.names=TRUE)}}
\item{t_srs}{character. proj4 expression of the output (\code{filename})
file.}
\item{nodata}{numeric. Value that should not get interpolated in the
resampling. Can take multiple values (i.e.: \code{c(220, 210, 211)}). No
need to specify the nodata value if that one is included in the file header.}
\item{filename}{character. filename of the output file, with full path.}
\item{res}{numeric. output resolution.}
\item{method}{character. resampling method. See
\url{http://www.gdal.org/gdalwarp.html}}
\item{mc.cores}{Numeric. Only relevant if \code{length(nodata) > 1}. Number
of workers.}
\item{run}{logical. should the warping be executed. If set to false, a
gdalwarp command string is generated, but not executed.}
\item{\dots}{Extra switches passed to \code{gdalwarp}, see
\url{http://www.gdal.org/gdalwarp.html}.}
}
\value{
A character, the gdalwarp command. If you inted to copy/past it in a
terminal, you can use \code{print()}, with \code{quote=FALSE}.
}
\description{
Warps (mosaic, reproject, resample), raster files to a projection set by the
user. The function works by calling \code{gdalwarp}, which needs to be
installed on the system.
}
\details{
Requires gdal to be installed on the system, and the the gdal binary folder
should be added to the system path. On windows systems, gdal can be install
via FWTools, OSGeo4W or QGIS.
}
\section{Warning }{
For parallel implementation, see warning section of
\code{\link{mclapply}}
}
\examples{
\dontrun{
pr <- getPR('Belize')
pr
dir = tempdir()
downloadPR(pr, year=2000, dir=dir)
unpackVCF(pr=pr, year=2000, searchDir=dir, dir=sprintf('\%s/\%s',dir,'extract/'))
x <- list.files(sprintf('\%s/\%s',dir,'extract/'), full.names=TRUE)
filename <- sprintf('\%s.tif', rasterTmpFile())
warpVCF(x=x, t_srs='+proj=laea +lat_0=-10 +lon_0=-70 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs', nodata = c(200, 210, 211, 220), filename=filename, '-multi')
a <- raster(filename)
}
}
\author{
Loic Dutrieux
}
\references{
\url{http://www.gdal.org/gdalwarp.html}
}
\keyword{gdal}
\keyword{landsat}
| /man/warpVCF.Rd | no_license | sonthuybacha/VCF | R | false | true | 2,519 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/warpVCF.R
\name{warpVCF}
\alias{warpVCF}
\title{Warping utility}
\usage{
warpVCF(x, t_srs, nodata = NULL, filename, res = 30, method = "bilinear",
mc.cores = 1, run = TRUE, ...)
}
\arguments{
\item{x}{character or list of character, the filenames of files to be
warpped. The list can easily be retrieved using a call such as
\code{list.files('/path/to/data/', full.names=TRUE)}}
\item{t_srs}{character. proj4 expression of the output (\code{filename})
file.}
\item{nodata}{numeric. Value that should not get interpolated in the
resampling. Can take multiple values (i.e.: \code{c(220, 210, 211)}). No
need to specify the nodata value if that one is included in the file header.}
\item{filename}{character. filename of the output file, with full path.}
\item{res}{numeric. output resolution.}
\item{method}{character. resampling method. See
\url{http://www.gdal.org/gdalwarp.html}}
\item{mc.cores}{Numeric. Only relevant if \code{length(nodata) > 1}. Number
of workers.}
\item{run}{logical. should the warping be executed. If set to false, a
gdalwarp command string is generated, but not executed.}
\item{\dots}{Extra switches passed to \code{gdalwarp}, see
\url{http://www.gdal.org/gdalwarp.html}.}
}
\value{
A character, the gdalwarp command. If you inted to copy/past it in a
terminal, you can use \code{print()}, with \code{quote=FALSE}.
}
\description{
Warps (mosaic, reproject, resample), raster files to a projection set by the
user. The function works by calling \code{gdalwarp}, which needs to be
installed on the system.
}
\details{
Requires gdal to be installed on the system, and the the gdal binary folder
should be added to the system path. On windows systems, gdal can be install
via FWTools, OSGeo4W or QGIS.
}
\section{Warning }{
For parallel implementation, see warning section of
\code{\link{mclapply}}
}
\examples{
\dontrun{
pr <- getPR('Belize')
pr
dir = tempdir()
downloadPR(pr, year=2000, dir=dir)
unpackVCF(pr=pr, year=2000, searchDir=dir, dir=sprintf('\%s/\%s',dir,'extract/'))
x <- list.files(sprintf('\%s/\%s',dir,'extract/'), full.names=TRUE)
filename <- sprintf('\%s.tif', rasterTmpFile())
warpVCF(x=x, t_srs='+proj=laea +lat_0=-10 +lon_0=-70 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs', nodata = c(200, 210, 211, 220), filename=filename, '-multi')
a <- raster(filename)
}
}
\author{
Loic Dutrieux
}
\references{
\url{http://www.gdal.org/gdalwarp.html}
}
\keyword{gdal}
\keyword{landsat}
|
library(extremis)
### Name: cdensity
### Title: Kernel Smoothed Scedasis Density
### Aliases: cdensity cdensity.default
### ** Examples
data(lse)
attach(lse)
Y <- data.frame(DATE[-1], -diff(log(ROYAL.DUTCH.SHELL.B)))
T <- dim(Y)[1]
k <- floor((0.4258597) * T / (log(T)))
fit <- cdensity(Y, kernel = "biweight", bw = 0.1 / sqrt(7),
threshold = sort(Y[, 2])[T - k])
plot(fit)
plot(fit, original = FALSE)
| /data/genthat_extracted_code/extremis/examples/cdensity.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 426 | r | library(extremis)
### Name: cdensity
### Title: Kernel Smoothed Scedasis Density
### Aliases: cdensity cdensity.default
### ** Examples
data(lse)
attach(lse)
Y <- data.frame(DATE[-1], -diff(log(ROYAL.DUTCH.SHELL.B)))
T <- dim(Y)[1]
k <- floor((0.4258597) * T / (log(T)))
fit <- cdensity(Y, kernel = "biweight", bw = 0.1 / sqrt(7),
threshold = sort(Y[, 2])[T - k])
plot(fit)
plot(fit, original = FALSE)
|
### R code from vignette source 'nlcv.Rnw'
###################################################
### code chunk number 1: init
###################################################
if(!dir.exists("./graphs")) dir.create("./graphs")
###################################################
### code chunk number 2: Setting
###################################################
options(width=65)
set.seed(123)
###################################################
### code chunk number 3: LoadLib
###################################################
library(nlcv)
###################################################
### code chunk number 4: Simulation
###################################################
EsetRandom <- simulateData(nCols = 40, nRows = 1000, nEffectRows = 0, nNoEffectCols = 0)
###################################################
### code chunk number 5: Simulation
###################################################
EsetStrongSignal <- simulateData(nCols = 40, nRows = 1000, nEffectRows = 10,
nNoEffectCols = 0, betweenClassDifference = 3, withinClassSd = 0.5)
###################################################
### code chunk number 6: Simulation
###################################################
EsetWeakSignal <- simulateData(nCols = 40, nRows = 1000, nEffectRows = 5,
nNoEffectCols = 0, betweenClassDifference = 1, withinClassSd = 0.6)
###################################################
### code chunk number 7: Simulation
###################################################
EsetStrongHeteroSignal <- simulateData(nCols = 40, nRows = 1000, nEffectRows = 5,
nNoEffectCols = 5, betweenClassDifference = 3, withinClassSd = 0.5)
###################################################
### code chunk number 8: Simulation
###################################################
EsetWeakHeteroSignal <- simulateData(nCols = 40, nRows = 1000, nEffectRows = 5,
nNoEffectCols = 5, betweenClassDifference = 1, withinClassSd = 0.6)
###################################################
### code chunk number 9: Simulation
###################################################
geneX <- 1
myData <- EsetStrongHeteroSignal
xx <- pData(myData)$type
yy <- exprs(myData)[geneX,]
myTitle <- rownames(exprs(myData))[geneX]
pdf(file = "./graphs/plotGeneSHS.pdf")
boxplot(yy~xx,col='grey',xlab='',ylab='', main = myTitle, axes=FALSE)
text(xx,yy,labels=colnames(exprs(myData)),col='blue',pos=4,cex=0.7)
axis(1, at=1:2, labels=levels(xx));axis(2, las=2)
dev.off()
###################################################
### code chunk number 10: nlcv (eval = FALSE)
###################################################
## nlcvTT_SS <- nlcv(EsetStrongSignal, classVar = "type", nRuns = 2,
## fsMethod = "t.test", verbose = TRUE)
###################################################
### code chunk number 11: nlcv load_objects_20runs
###################################################
# No Signal - Random data
data("nlcvRF_R"); data("nlcvTT_R")
# Strong Signal
data("nlcvRF_SS"); data("nlcvTT_SS")
# Weak Signal
data("nlcvRF_WS"); data("nlcvTT_WS")
# Strong, heterogeneous Signal
data("nlcvRF_SHS"); data("nlcvTT_SHS")
# Weak, heterogeneous Signal
data("nlcvRF_WHS"); data("nlcvTT_WHS")
###################################################
### code chunk number 12: nlcv run_objects_20runs
###################################################
# # Sidenote: nlcvRF_SS (loaded in the previous chunk) was obtained with following code
# nlcvRF_SS <- nlcv(EsetStrongSignal, classVar = "type", nRuns = 20, fsMethod = "randomForest", verbose = TRUE)
# save(nlcvRF_SS, file = "nlcvRF_SS.rda")
# nlcvTT_SS <- nlcv(EsetStrongSignal, classVar = "type", nRuns = 20, fsMethod = "t.test", verbose = TRUE)
# save(nlcvTT_SS, file = "nlcvTT_SS.rda")
#
# Similarly for any other dataset, like EsetWeakSignal, WeakHeteroSignal, StrongHeteroSignal and EsetRandom
###################################################
### code chunk number 13: mcrPlot_RandomData
###################################################
# plot MCR versus number of features
pdf(file = "./graphs/mcrPlot_nlcv_R.pdf", width = 10, height = 5)
layout(matrix(1:4, ncol = 2), height = c(6, 1, 6, 1))
mcrPlot_RF_R <- mcrPlot(nlcvRF_R, plot = TRUE, optimalDots = TRUE,
layout = FALSE, main = 'RF selection')
mcrPlot_TT_R <- mcrPlot(nlcvTT_R, plot = TRUE, optimalDots = TRUE,
layout = FALSE, main = 'T selection')
layout(1)
dev.off()
###################################################
### code chunk number 14: scoresPlot_RandomData
###################################################
pdf(file = "./graphs/ScoresPlot_nlcv_R.pdf", width = 10, height = 6)
scoresPlot(nlcvRF_R, "randomForest", 5)
dev.off()
###################################################
### code chunk number 15: selGenes
###################################################
outtable <- topTable(nlcvRF_R, n = 10)
xtable(outtable, label = "tab:selGenes_R",
caption="Top 10 features across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 16: Simulation
###################################################
geneX <- 1
myData <- EsetStrongSignal
xx <- pData(myData)$type
yy <- exprs(myData)[geneX,]
myTitle <- rownames(exprs(myData))[geneX]
pdf(file = "./graphs/plotGeneSS.pdf")
boxplot(yy~xx,col='grey',xlab='',ylab='', main = myTitle, axes=FALSE)
text(xx,yy,labels=colnames(exprs(myData)),col='blue',pos=4,cex=0.7)
axis(1, at=1:2, labels=levels(xx));axis(2, las=2)
dev.off()
###################################################
### code chunk number 17: RandomData
###################################################
# plot MCR versus number of features
pdf(file = "./graphs/mcrPlot_nlcv_SS.pdf", width = 10, height = 5)
layout(matrix(1:4, ncol = 2), height = c(6, 1, 6, 1))
mcrPlot_SSF_SS <- mcrPlot(nlcvRF_SS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'RF selection')
mcrPlot_TT_SS <- mcrPlot(nlcvTT_SS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'T selection')
dev.off()
###################################################
### code chunk number 18: RandomData
###################################################
pdf(file = "./graphs/ScoresPlot_nlcv_SS.pdf", width = 10, height = 6)
scoresPlot(nlcvRF_SS, "randomForest", 5)
dev.off()
###################################################
### code chunk number 19: selGenes
###################################################
outtable <- topTable(nlcvRF_SS, n = 12)
xtable(outtable, label = "tab:selGenes_SS",
caption="Top 20 features across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 20: Simulation
###################################################
geneX <- 1
myData <- EsetWeakSignal
xx <- pData(myData)$type
yy <- exprs(myData)[geneX,]
myTitle <- rownames(exprs(myData))[geneX]
pdf(file = "./graphs/plotGeneWS.pdf")
boxplot(yy~xx,col='grey',xlab='',ylab='', main = myTitle, axes=FALSE)
text(xx,yy,labels=colnames(exprs(myData)),col='blue',pos=4,cex=0.7)
axis(1, at=1:2, labels=levels(xx));axis(2, las=2)
dev.off()
###################################################
### code chunk number 21: RandomData
###################################################
# plot MCR versus number of features
pdf(file = "./graphs/mcrPlot_nlcv_WS.pdf", width = 10, height = 5)
layout(matrix(1:4, ncol = 2), height = c(6, 1, 6, 1))
mcrPlot_WSF_WS <- mcrPlot(nlcvRF_WS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'RF selection')
mcrPlot_TT_WS <- mcrPlot(nlcvTT_WS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'T selection')
dev.off()
###################################################
### code chunk number 22: ScoresPlot_nlcv_WS
###################################################
pdf(file = "./graphs/ScoresPlot_nlcv_WS.pdf", width = 10, height = 6)
scoresPlot(nlcvRF_WS, "svm", 7)
dev.off()
###################################################
### code chunk number 23: selGenesNlcvTT_WS
###################################################
outtable <- topTable(nlcvTT_WS, n = 7)
xtable(outtable, label = "tab:selGenes_WS1",
caption="Top 20 features selected with t-test across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 24: selGenesNlcvRF_WS
###################################################
outtable <- topTable(nlcvRF_WS, n = 7)
xtable(outtable, label = "tab:selGenes_WS2",
caption="Top 20 features selected with RF variable importance across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 25: Simulation
###################################################
geneX <- 1
myData <- EsetStrongHeteroSignal
xx <- pData(myData)$type
yy <- exprs(myData)[geneX,]
myTitle <- rownames(exprs(myData))[geneX]
pdf(file = "./graphs/plotGeneSHS.pdf")
boxplot(yy~xx,col='grey',xlab='',ylab='', main = myTitle, axes=FALSE)
text(xx,yy,labels=colnames(exprs(myData)),col='blue',pos=4,cex=0.7)
axis(1, at=1:2, labels=levels(xx));axis(2, las=2)
dev.off()
###################################################
### code chunk number 26: mcrPlot_nlcv_SHS
###################################################
# plot MCR versus number of features
pdf(file = "./graphs/mcrPlot_nlcv_SHS.pdf", width = 10, height = 5)
layout(matrix(1:4, ncol = 2), height = c(6, 1, 6, 1))
mcrPlot_SHSF_SHS <- mcrPlot(nlcvRF_SHS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'RF selection')
mcrPlot_TT_SHS <- mcrPlot(nlcvTT_SHS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'T selection')
dev.off()
###################################################
### code chunk number 27: scoresPlots
###################################################
pdf(file = "./graphs/ScoresPlot_nlcv_SHS.pdf", width = 10, height = 6)
scoresPlot(nlcvTT_SHS, "pam", 7)
dev.off()
pdf(file = "./graphs/ScoresPlot_nlcv_SHS2.pdf", width = 10, height = 6)
scoresPlot(nlcvTT_SHS, "randomForest", 7)
dev.off()
pdf(file = "./graphs/ScoresPlot_nlcv_SHS3.pdf", width = 10, height = 6)
scoresPlot(nlcvRF_SHS, "randomForest", 7)
dev.off()
###################################################
### code chunk number 28: selGenes
###################################################
outtable <- topTable(nlcvTT_SHS, n = 7)
xtable(outtable, label = "tab:selGenes_SHS1",
caption="Top 20 features selected with t-test across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 29: selGenes
###################################################
outtable <- topTable(nlcvRF_SHS, n = 7)
xtable(outtable, label = "tab:selGenes_SHS2",
caption="Top 20 features selected with RF variable importance across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 30: Simulation
###################################################
geneX <- 1:4
myData <- EsetWeakHeteroSignal
xx <- pData(myData)$type
pdf(file = "./graphs/plotGeneWHS.pdf")
par(mfrow=c(2,2))
for (i in 1:4){
yy <- exprs(myData)[geneX[i],]
myTitle <- rownames(exprs(myData))[geneX[i]]
boxplot(yy~xx,col='grey',xlab='',ylab='', main = myTitle, axes=FALSE)
text(xx,yy,labels=colnames(exprs(myData)),col='blue',pos=4,cex=0.85)
axis(1, at=1:2, labels=levels(xx));axis(2, las=2)
}
par(mfrow=c(1,1))
dev.off()
###################################################
### code chunk number 31: RandomData
###################################################
# plot MCR versus number of features
pdf(file = "./graphs/mcrPlot_nlcv_WHS.pdf", width = 10, height = 5)
layout(matrix(1:4, ncol = 2), height = c(6, 1, 6, 1))
mcrPlot_WHSF_WHS <- mcrPlot(nlcvRF_WHS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'RF selection')
mcrPlot_TT_WHS <- mcrPlot(nlcvTT_WHS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'T selection')
dev.off()
###################################################
### code chunk number 32: RandomData
###################################################
pdf(file = "./graphs/ScoresPlot_nlcv_WHS.pdf", width = 10, height = 6)
scoresPlot(nlcvTT_WHS, "pam", 2)
dev.off()
pdf(file = "./graphs/ScoresPlot_nlcv_WHS0.pdf", width = 10, height = 6)
scoresPlot(nlcvTT_WHS, "pam", 10)
dev.off()
pdf(file = "./graphs/ScoresPlot_nlcv_WHS2.pdf", width = 10, height = 6)
scoresPlot(nlcvTT_WHS, "randomForest", 15)
dev.off()
pdf(file = "./graphs/ScoresPlot_nlcv_WHS3.pdf", width = 10, height = 6)
scoresPlot(nlcvRF_WHS, "randomForest", 5)
dev.off()
###################################################
### code chunk number 33: selGenes
###################################################
outtable <- topTable(nlcvTT_WHS, n = 10)
xtable(outtable, label = "tab:selGenes_WHS1",
caption="Top 20 features selected with t-test across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 34: selGenes
###################################################
outtable <- topTable(nlcvRF_WHS, n = 10)
xtable(outtable, label = "tab:selGenes_WHS2",
caption="Top 20 features selected with RF variable importance across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 35: sessionInfo
###################################################
toLatex(sessionInfo())
| /inst/doc/nlcv.R | no_license | cran/nlcv | R | false | false | 13,539 | r | ### R code from vignette source 'nlcv.Rnw'
###################################################
### code chunk number 1: init
###################################################
if(!dir.exists("./graphs")) dir.create("./graphs")
###################################################
### code chunk number 2: Setting
###################################################
options(width=65)
set.seed(123)
###################################################
### code chunk number 3: LoadLib
###################################################
library(nlcv)
###################################################
### code chunk number 4: Simulation
###################################################
EsetRandom <- simulateData(nCols = 40, nRows = 1000, nEffectRows = 0, nNoEffectCols = 0)
###################################################
### code chunk number 5: Simulation
###################################################
EsetStrongSignal <- simulateData(nCols = 40, nRows = 1000, nEffectRows = 10,
nNoEffectCols = 0, betweenClassDifference = 3, withinClassSd = 0.5)
###################################################
### code chunk number 6: Simulation
###################################################
EsetWeakSignal <- simulateData(nCols = 40, nRows = 1000, nEffectRows = 5,
nNoEffectCols = 0, betweenClassDifference = 1, withinClassSd = 0.6)
###################################################
### code chunk number 7: Simulation
###################################################
EsetStrongHeteroSignal <- simulateData(nCols = 40, nRows = 1000, nEffectRows = 5,
nNoEffectCols = 5, betweenClassDifference = 3, withinClassSd = 0.5)
###################################################
### code chunk number 8: Simulation
###################################################
EsetWeakHeteroSignal <- simulateData(nCols = 40, nRows = 1000, nEffectRows = 5,
nNoEffectCols = 5, betweenClassDifference = 1, withinClassSd = 0.6)
###################################################
### code chunk number 9: Simulation
###################################################
geneX <- 1
myData <- EsetStrongHeteroSignal
xx <- pData(myData)$type
yy <- exprs(myData)[geneX,]
myTitle <- rownames(exprs(myData))[geneX]
pdf(file = "./graphs/plotGeneSHS.pdf")
boxplot(yy~xx,col='grey',xlab='',ylab='', main = myTitle, axes=FALSE)
text(xx,yy,labels=colnames(exprs(myData)),col='blue',pos=4,cex=0.7)
axis(1, at=1:2, labels=levels(xx));axis(2, las=2)
dev.off()
###################################################
### code chunk number 10: nlcv (eval = FALSE)
###################################################
## nlcvTT_SS <- nlcv(EsetStrongSignal, classVar = "type", nRuns = 2,
## fsMethod = "t.test", verbose = TRUE)
###################################################
### code chunk number 11: nlcv load_objects_20runs
###################################################
# No Signal - Random data
data("nlcvRF_R"); data("nlcvTT_R")
# Strong Signal
data("nlcvRF_SS"); data("nlcvTT_SS")
# Weak Signal
data("nlcvRF_WS"); data("nlcvTT_WS")
# Strong, heterogeneous Signal
data("nlcvRF_SHS"); data("nlcvTT_SHS")
# Weak, heterogeneous Signal
data("nlcvRF_WHS"); data("nlcvTT_WHS")
###################################################
### code chunk number 12: nlcv run_objects_20runs
###################################################
# # Sidenote: nlcvRF_SS (loaded in the previous chunk) was obtained with following code
# nlcvRF_SS <- nlcv(EsetStrongSignal, classVar = "type", nRuns = 20, fsMethod = "randomForest", verbose = TRUE)
# save(nlcvRF_SS, file = "nlcvRF_SS.rda")
# nlcvTT_SS <- nlcv(EsetStrongSignal, classVar = "type", nRuns = 20, fsMethod = "t.test", verbose = TRUE)
# save(nlcvTT_SS, file = "nlcvTT_SS.rda")
#
# Similarly for any other dataset, like EsetWeakSignal, WeakHeteroSignal, StrongHeteroSignal and EsetRandom
###################################################
### code chunk number 13: mcrPlot_RandomData
###################################################
# plot MCR versus number of features
pdf(file = "./graphs/mcrPlot_nlcv_R.pdf", width = 10, height = 5)
layout(matrix(1:4, ncol = 2), height = c(6, 1, 6, 1))
mcrPlot_RF_R <- mcrPlot(nlcvRF_R, plot = TRUE, optimalDots = TRUE,
layout = FALSE, main = 'RF selection')
mcrPlot_TT_R <- mcrPlot(nlcvTT_R, plot = TRUE, optimalDots = TRUE,
layout = FALSE, main = 'T selection')
layout(1)
dev.off()
###################################################
### code chunk number 14: scoresPlot_RandomData
###################################################
pdf(file = "./graphs/ScoresPlot_nlcv_R.pdf", width = 10, height = 6)
scoresPlot(nlcvRF_R, "randomForest", 5)
dev.off()
###################################################
### code chunk number 15: selGenes
###################################################
outtable <- topTable(nlcvRF_R, n = 10)
xtable(outtable, label = "tab:selGenes_R",
caption="Top 10 features across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 16: Simulation
###################################################
geneX <- 1
myData <- EsetStrongSignal
xx <- pData(myData)$type
yy <- exprs(myData)[geneX,]
myTitle <- rownames(exprs(myData))[geneX]
pdf(file = "./graphs/plotGeneSS.pdf")
boxplot(yy~xx,col='grey',xlab='',ylab='', main = myTitle, axes=FALSE)
text(xx,yy,labels=colnames(exprs(myData)),col='blue',pos=4,cex=0.7)
axis(1, at=1:2, labels=levels(xx));axis(2, las=2)
dev.off()
###################################################
### code chunk number 17: RandomData
###################################################
# plot MCR versus number of features
pdf(file = "./graphs/mcrPlot_nlcv_SS.pdf", width = 10, height = 5)
layout(matrix(1:4, ncol = 2), height = c(6, 1, 6, 1))
mcrPlot_SSF_SS <- mcrPlot(nlcvRF_SS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'RF selection')
mcrPlot_TT_SS <- mcrPlot(nlcvTT_SS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'T selection')
dev.off()
###################################################
### code chunk number 18: RandomData
###################################################
pdf(file = "./graphs/ScoresPlot_nlcv_SS.pdf", width = 10, height = 6)
scoresPlot(nlcvRF_SS, "randomForest", 5)
dev.off()
###################################################
### code chunk number 19: selGenes
###################################################
outtable <- topTable(nlcvRF_SS, n = 12)
xtable(outtable, label = "tab:selGenes_SS",
caption="Top 20 features across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 20: Simulation
###################################################
geneX <- 1
myData <- EsetWeakSignal
xx <- pData(myData)$type
yy <- exprs(myData)[geneX,]
myTitle <- rownames(exprs(myData))[geneX]
pdf(file = "./graphs/plotGeneWS.pdf")
boxplot(yy~xx,col='grey',xlab='',ylab='', main = myTitle, axes=FALSE)
text(xx,yy,labels=colnames(exprs(myData)),col='blue',pos=4,cex=0.7)
axis(1, at=1:2, labels=levels(xx));axis(2, las=2)
dev.off()
###################################################
### code chunk number 21: RandomData
###################################################
# plot MCR versus number of features
pdf(file = "./graphs/mcrPlot_nlcv_WS.pdf", width = 10, height = 5)
layout(matrix(1:4, ncol = 2), height = c(6, 1, 6, 1))
mcrPlot_WSF_WS <- mcrPlot(nlcvRF_WS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'RF selection')
mcrPlot_TT_WS <- mcrPlot(nlcvTT_WS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'T selection')
dev.off()
###################################################
### code chunk number 22: ScoresPlot_nlcv_WS
###################################################
pdf(file = "./graphs/ScoresPlot_nlcv_WS.pdf", width = 10, height = 6)
scoresPlot(nlcvRF_WS, "svm", 7)
dev.off()
###################################################
### code chunk number 23: selGenesNlcvTT_WS
###################################################
outtable <- topTable(nlcvTT_WS, n = 7)
xtable(outtable, label = "tab:selGenes_WS1",
caption="Top 20 features selected with t-test across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 24: selGenesNlcvRF_WS
###################################################
outtable <- topTable(nlcvRF_WS, n = 7)
xtable(outtable, label = "tab:selGenes_WS2",
caption="Top 20 features selected with RF variable importance across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 25: Simulation
###################################################
geneX <- 1
myData <- EsetStrongHeteroSignal
xx <- pData(myData)$type
yy <- exprs(myData)[geneX,]
myTitle <- rownames(exprs(myData))[geneX]
pdf(file = "./graphs/plotGeneSHS.pdf")
boxplot(yy~xx,col='grey',xlab='',ylab='', main = myTitle, axes=FALSE)
text(xx,yy,labels=colnames(exprs(myData)),col='blue',pos=4,cex=0.7)
axis(1, at=1:2, labels=levels(xx));axis(2, las=2)
dev.off()
###################################################
### code chunk number 26: mcrPlot_nlcv_SHS
###################################################
# plot MCR versus number of features
pdf(file = "./graphs/mcrPlot_nlcv_SHS.pdf", width = 10, height = 5)
layout(matrix(1:4, ncol = 2), height = c(6, 1, 6, 1))
mcrPlot_SHSF_SHS <- mcrPlot(nlcvRF_SHS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'RF selection')
mcrPlot_TT_SHS <- mcrPlot(nlcvTT_SHS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'T selection')
dev.off()
###################################################
### code chunk number 27: scoresPlots
###################################################
pdf(file = "./graphs/ScoresPlot_nlcv_SHS.pdf", width = 10, height = 6)
scoresPlot(nlcvTT_SHS, "pam", 7)
dev.off()
pdf(file = "./graphs/ScoresPlot_nlcv_SHS2.pdf", width = 10, height = 6)
scoresPlot(nlcvTT_SHS, "randomForest", 7)
dev.off()
pdf(file = "./graphs/ScoresPlot_nlcv_SHS3.pdf", width = 10, height = 6)
scoresPlot(nlcvRF_SHS, "randomForest", 7)
dev.off()
###################################################
### code chunk number 28: selGenes
###################################################
outtable <- topTable(nlcvTT_SHS, n = 7)
xtable(outtable, label = "tab:selGenes_SHS1",
caption="Top 20 features selected with t-test across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 29: selGenes
###################################################
outtable <- topTable(nlcvRF_SHS, n = 7)
xtable(outtable, label = "tab:selGenes_SHS2",
caption="Top 20 features selected with RF variable importance across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 30: Simulation
###################################################
geneX <- 1:4
myData <- EsetWeakHeteroSignal
xx <- pData(myData)$type
pdf(file = "./graphs/plotGeneWHS.pdf")
par(mfrow=c(2,2))
for (i in 1:4){
yy <- exprs(myData)[geneX[i],]
myTitle <- rownames(exprs(myData))[geneX[i]]
boxplot(yy~xx,col='grey',xlab='',ylab='', main = myTitle, axes=FALSE)
text(xx,yy,labels=colnames(exprs(myData)),col='blue',pos=4,cex=0.85)
axis(1, at=1:2, labels=levels(xx));axis(2, las=2)
}
par(mfrow=c(1,1))
dev.off()
###################################################
### code chunk number 31: RandomData
###################################################
# plot MCR versus number of features
pdf(file = "./graphs/mcrPlot_nlcv_WHS.pdf", width = 10, height = 5)
layout(matrix(1:4, ncol = 2), height = c(6, 1, 6, 1))
mcrPlot_WHSF_WHS <- mcrPlot(nlcvRF_WHS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'RF selection')
mcrPlot_TT_WHS <- mcrPlot(nlcvTT_WHS, plot = TRUE, optimalDots = TRUE, layout = FALSE, main = 'T selection')
dev.off()
###################################################
### code chunk number 32: RandomData
###################################################
pdf(file = "./graphs/ScoresPlot_nlcv_WHS.pdf", width = 10, height = 6)
scoresPlot(nlcvTT_WHS, "pam", 2)
dev.off()
pdf(file = "./graphs/ScoresPlot_nlcv_WHS0.pdf", width = 10, height = 6)
scoresPlot(nlcvTT_WHS, "pam", 10)
dev.off()
pdf(file = "./graphs/ScoresPlot_nlcv_WHS2.pdf", width = 10, height = 6)
scoresPlot(nlcvTT_WHS, "randomForest", 15)
dev.off()
pdf(file = "./graphs/ScoresPlot_nlcv_WHS3.pdf", width = 10, height = 6)
scoresPlot(nlcvRF_WHS, "randomForest", 5)
dev.off()
###################################################
### code chunk number 33: selGenes
###################################################
outtable <- topTable(nlcvTT_WHS, n = 10)
xtable(outtable, label = "tab:selGenes_WHS1",
caption="Top 20 features selected with t-test across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 34: selGenes
###################################################
outtable <- topTable(nlcvRF_WHS, n = 10)
xtable(outtable, label = "tab:selGenes_WHS2",
caption="Top 20 features selected with RF variable importance across all runs of the nested loop cross-validation.")
###################################################
### code chunk number 35: sessionInfo
###################################################
toLatex(sessionInfo())
|
change.col = "tomato"
#* @get /hello
hw <- function(){
return("Hello world!")
}
#* @post /operation
operation <- function(a, b){
as.numeric(a) + as.numeric(b)
}
#* @get /iris/<sp>/<n:int>
function(n, sp){
iris %>% dplyr::filter(Species == sp) %>%
.[as.integer(n), ]
}
#' @filter logger
function(req){
print(paste0(date(), " - ",
req$REMOTE_ADDR, " - ",
req$REQUEST_METHOD, " ",
req$PATH_INFO))
forward()
}
#* @get /ggp2dens
#* @png
ggp2dens <- function(seed = rnorm(1), fill.colour = "tomato", alpha = 1.0){
library(ggplot2)
set.seed(seed)
p <- data.frame(x = rnorm(100)) %>%
ggplot(aes(x)) + geom_density(fill = fill.colour, alpha = alpha)
print(p)
}
#* @get /ggp2dens_color
#* @png
ggp2dens_col <- function(seed = rnorm(1)){
library(ggplot2)
set.seed(seed)
p <- data.frame(x = rnorm(100)) %>%
ggplot(aes(x)) + geom_density(fill = change.col)
print(p)
}
#* @get /chenge_color
change_color <- function(){
change.col <<- "skyblue"
}
| /2016/160312_api_with_plumber/first_api.R | no_license | uribo/hatena_blog | R | false | false | 1,027 | r | change.col = "tomato"
#* @get /hello
hw <- function(){
return("Hello world!")
}
#* @post /operation
operation <- function(a, b){
as.numeric(a) + as.numeric(b)
}
#* @get /iris/<sp>/<n:int>
function(n, sp){
iris %>% dplyr::filter(Species == sp) %>%
.[as.integer(n), ]
}
#' @filter logger
function(req){
print(paste0(date(), " - ",
req$REMOTE_ADDR, " - ",
req$REQUEST_METHOD, " ",
req$PATH_INFO))
forward()
}
#* @get /ggp2dens
#* @png
ggp2dens <- function(seed = rnorm(1), fill.colour = "tomato", alpha = 1.0){
library(ggplot2)
set.seed(seed)
p <- data.frame(x = rnorm(100)) %>%
ggplot(aes(x)) + geom_density(fill = fill.colour, alpha = alpha)
print(p)
}
#* @get /ggp2dens_color
#* @png
ggp2dens_col <- function(seed = rnorm(1)){
library(ggplot2)
set.seed(seed)
p <- data.frame(x = rnorm(100)) %>%
ggplot(aes(x)) + geom_density(fill = change.col)
print(p)
}
#* @get /chenge_color
change_color <- function(){
change.col <<- "skyblue"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.