# Run the power analysis but sample ever two years
power <- power.trend.random.occupancy.analytical(
initial.psi=x$psi,
p=x$p,
per.change.per.year=x$per.change.per.year,
time.period=x$time.period,
S=x$S, K=x$K, years.visit=seq(1,x$time.period,2) )
power})
plotdata <- res.every.two.years
plotdata$K2 <- paste("Visits =",sprintf("%2.0f", plotdata$K), sep="")
plotdata$time.period2 <- paste("Over ", sprintf("%2.0f",plotdata$time.period)," years",sep="")
res.every.two.years <- plyr::adply(scenarios, 1, function(x){
# Run the power analysis but sample ever two years
power <- power.trend.random.occupancy.analytical(
initial.psi=x$psi,
p=x$p,
per.change.per.year=x$per.change.per.year,
time.period=x$time.period,
S=x$S, K=x$K, years.visit=seq(1,x$time.period,2) )
power})
plotdata <- res.every.two.years
plotdata$K2 <- paste("Visits =",sprintf("%2.0f", plotdata$K), sep="")
plotdata$time.period2 <- paste("Over ", sprintf("%2.0f",plotdata$time.period)," years",sep="")
powerplot.2years <- ggplot(data=plotdata, aes(x=S, y=power.1s.knownsigma, color=factor(per.decline), linetype=factor(per.decline)))+
ggtitle("Power to detect percentage decline in logit(occupancy)",
subtitle=paste( plotdata$K[1]," visits/year; alpha= ", plotdata$alpha[2], "; Monitoring every two years",sep=""))+
theme(plot.title = element_text(hjust = 0.5))+
xlab("Number of sites measured every two years")+
ylab("Power to detect trend (one sided)")+
#geom_point()+
geom_line()+
ylim(c(0,1))+
facet_wrap(~Species, ncol=2)+
geom_hline(yintercept=0.80)+
labs(color="Percent\ndecline", linetype="Percent\ndecline")+
theme(legend.justification=c(1,0), legend.position=c(1,0))+
geom_text(data=study, aes(x=Inf, y=0,
label=paste("p   = ",formatC(p,digits=2,format="f"),sep=""), color=NULL, linetype=NULL), hjust=1)+
geom_text(data=study, aes(x=Inf, y=0,
label=paste("psi = ",formatC(psi,digits=2,format="f"),sep=""), color=NULL, linetype=NULL), hjust=1,vjust=-1.5)
powerplot.2years
plotdata <- res.every.two.years
plotdata$K2 <- paste("Visits =",sprintf("%2.0f", plotdata$K), sep="")
plotdata$time.period2 <- paste("Over ", sprintf("%2.0f",plotdata$time.period)," years",sep="")
plotdata$per.change.per.year <- round(plotdata$per.change.per.year,1)
powerplot.2years <- ggplot(data=plotdata, aes(x=S, y=power.1s.knownsigma,
color=factor(per.change.per.year), linetype=factor(time.period)))+
ggtitle("Power to detect percentage decline in logit(occupancy)",
subtitle=paste( plotdata$K[1]," visits/year; alpha= ", plotdata$alpha[2], "; Monitoring every two years",sep=""))+
theme(plot.title = element_text(hjust = 0.5))+
xlab("Number of sites measured every two years")+
ylab("Power to detect trend (one sided)")+
#geom_point()+
geom_line()+
ylim(c(0,1))+
facet_wrap(~Species, ncol=2)+
geom_hline(yintercept=0.80)+
labs(color="Percent\nchange\nper year", linetype="Time\nPeriod\n(years)")+
theme(legend.justification=c(1,0), legend.position=c(1,0))+
geom_text(data=study, aes(x=Inf, y=0,
label=paste("p   = ",formatC(p,digits=2,format="f"),sep=""), color=NULL, linetype=NULL), hjust=1)+
geom_text(data=study, aes(x=Inf, y=0,
label=paste("psi = ",formatC(psi,digits=2,format="f"),sep=""), color=NULL, linetype=NULL), hjust=1,vjust=-1.5)
powerplot.2years
ggsave(plot=powerplot.2years,
file=file.path("Results",'plots-powerplot-every-2years-knownsigma.png'), h=6, w=6, units="in", dpi=300)
##### what happens if measure every years
# E.g. years 1, 3, 5, 7, 9   or 1, 3, 5, 7, 19, 11, 13
scenarios <- expand.grid(S=seq(30,100,10), per.change.per.year=per.change.per.year, time.period=c(9,15), K=c(2))
scenarios <- plyr::ddply(study, "Species", function(x, scenarios){
data.frame(x, scenarios)
}, scenarios=scenarios)
head(scenarios)
res.every.two.years <- plyr::adply(scenarios, 1, function(x){
# Run the power analysis but sample ever two years
power <- power.trend.random.occupancy.analytical(
initial.psi=x$psi,
p=x$p,
per.change.per.year=x$per.change.per.year,
time.period=x$time.period,
S=x$S, K=x$K, years.visit=seq(1,x$time.period,2) )
power})
plotdata <- res.every.two.years
plotdata$K2 <- paste("Visits =",sprintf("%2.0f", plotdata$K), sep="")
plotdata$time.period2 <- paste("Over ", sprintf("%2.0f",plotdata$time.period)," years",sep="")
plotdata$per.change.per.year <- round(plotdata$per.change.per.year,1)
powerplot.2years <- ggplot(data=plotdata, aes(x=S, y=power.1s.knownsigma,
color=factor(per.change.per.year), linetype=factor(time.period)))+
ggtitle("Power to detect percentage decline in logit(occupancy)",
subtitle=paste( plotdata$K[1]," visits/year; alpha= ", plotdata$alpha[2], "; Monitoring every two years",sep=""))+
theme(plot.title = element_text(hjust = 0.5))+
xlab("Number of sites measured every two years")+
ylab("Power to detect trend (one sided)")+
#geom_point()+
geom_line()+
ylim(c(0,1))+
facet_wrap(~Species, ncol=2)+
geom_hline(yintercept=0.80)+
labs(color="Percent\nchange\nper year", linetype="Time\nPeriod\n(years)")+
theme(legend.justification=c(1,0), legend.position=c(1,0))+
geom_text(data=study, aes(x=Inf, y=0,
label=paste("p   = ",formatC(p,digits=2,format="f"),sep=""), color=NULL, linetype=NULL), hjust=1)+
geom_text(data=study, aes(x=Inf, y=0,
label=paste("psi = ",formatC(psi,digits=2,format="f"),sep=""), color=NULL, linetype=NULL), hjust=1,vjust=-1.5)
powerplot.2years
ggsave(plot=powerplot.2years,
file=file.path("Results",'plots-powerplot-every-2years-knownsigma.png'), h=6, w=6, units="in", dpi=300)
help(render)
library(rmarkdown)
help(render)
setwd("~/Dropbox/Stat-R/CourseNotes/sampledata/RMarkdown/SingleReport")
setwd("~/Dropbox/Stat-R/CourseNotes/sampledata/RMarkdown/MultipleReports")
help(render)
cereal <- read.csv('cereal.csv',
header=TRUE, as.is=TRUE, strip.white=TRUE)
xtabs(~mfr, data=cereal)
help(mkdir)
help("dir")
# create the directory for the reports
file.create("reports")
# create the directory for the reports
file.create("reports")
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::ddply(cereal, "mfr", function (my.cereal){
rmarkdown::render('Report.Rmd',  # file 2
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".html", sep=''),
output_dir = 'reports')
})
# create the directory for the reports
dir.create("reports")
# create the directory for the reports
dir.create("reports")
# create the directory for the reports
dir.create("reports")
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::ddply(cereal, "mfr", function (my.cereal){
rmarkdown::render('Report.Rmd',  # file 2
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".html", sep=''),
output_dir = 'reports')
})
xtabs(~mfr, data=cereal)
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::ddply(cereal[ cereal$mfr %in% c("A","G")], "mfr", function (my.cereal){
rmarkdown::render('Report.Rmd',  # file 2
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".html", sep=''),
output_dir = 'reports')
})
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::ddply(cereal[ cereal$mfr %in% c("A","G"),], "mfr", function (my.cereal){
rmarkdown::render('Report.Rmd',  # file 2
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".html", sep=''),
output_dir = 'reports')
})
help("pandoc.table")
# Links for RMarkdown help
# Information about RMarkdown is at: http://rmarkdown.rstudio.com
# Chunk options      https://yihui.name/knitr/options/
# Dealing with word templates and Rmarkdown
#    http://stackoverflow.com/questions/41982700/how-to-properly-number-headings-in-word-from-a-rmarkdown-document
#    http://rmarkdown.rstudio.com/articles_docx.html
#    http://rmarkdown.rstudio.com/word_document_format.html
# Here we open the libraries needed and source any other code as needed
knitr::opts_chunk$set(echo = TRUE)
library(car)
library(emmeans)
library(ggplot2)
library(gridExtra)
library(knitr)
library(pander)
library(plyr)
library(readxl)
library(reshape2)
source('http://www.stat.sfu.ca/~cschwarz/Stat-650/Notes/MyPrograms/schwarz.functions.r')
# Get the raw data and do editing. This won't appear in the report, but gives you
# an audit trail of what you did to the raw data before creating the rest of the
# template
cereal <- my.cereal  # this is the chunk that will be analysed.
my.cereal <- cereal
# Links for RMarkdown help
# Information about RMarkdown is at: http://rmarkdown.rstudio.com
# Chunk options      https://yihui.name/knitr/options/
# Dealing with word templates and Rmarkdown
#    http://stackoverflow.com/questions/41982700/how-to-properly-number-headings-in-word-from-a-rmarkdown-document
#    http://rmarkdown.rstudio.com/articles_docx.html
#    http://rmarkdown.rstudio.com/word_document_format.html
# Here we open the libraries needed and source any other code as needed
knitr::opts_chunk$set(echo = TRUE)
library(car)
library(emmeans)
library(ggplot2)
library(gridExtra)
library(knitr)
library(pander)
library(plyr)
library(readxl)
library(reshape2)
source('http://www.stat.sfu.ca/~cschwarz/Stat-650/Notes/MyPrograms/schwarz.functions.r')
# Get the raw data and do editing. This won't appear in the report, but gives you
# an audit trail of what you did to the raw data before creating the rest of the
# template
cereal <- my.cereal  # this is the chunk that will be analysed.
# Define new variables and factors (for categorical variables). CHeck the structure of the data frame
cereal$shelfF <- factor(cereal$shelf)
# Comput the summary statstics for each shelf
cereal$shelfc <- recode(cereal$shelf,
" 1='Low'; 2='Middle'; 3='High' ")
xtabs(~shelfc+shelf, data=cereal)
cereal$shelfcF <- factor(cereal$shelfc, levels=c("Low","Middle","High"), order=TRUE)
report <- plyr::ddply(cereal, c("shelfcF"), plyr::summarize,
ncereal = length(calories),
mean    = round(mean(calories),1),
min     = min(calories),
max     = max(calories),
sd      = round(sd(calories),1))
# Create the output table
colnames(report) <- c(
"Shelf",
"n",
"Mean\ncalories\nper\nserving",
"Min\ncalories\nper\nserving",
"Max\ncalories\nper\nserving",
"SD\ncalories\nper\nserving"
)
pandoc.table(report,
caption="Summary statistics on calories per serving",
justify='lrrrrr',
split.cells=c(1,1,1,1,1,1))
plot <- ggplot(data=cereal, aes(x=fat, y=calories))+
ggtitle("Calories by fat")+
geom_point( position=position_jitter(h=.2, w=.2))+
ylab("Calories per serving")
plot
calories.fit <- lm(calories ~ fat, data=cereal)
calories.pvalue <- anova(calories.fit)$"Pr(>F)"[1]
sugars.fit <- lm(sugars ~ shelfcF, data=cereal)
calories.fit <- lm(calories ~ fat, data=cereal)
calories.pvalue <- anova(calories.fit)$"Pr(>F)"[1]
anova(calories.fit)
plot <- ggplot(data=cereal, aes(x=fat, y=calories))+
ggtitle("Calories by fat")+
geom_point( position=position_jitter(h=.2, w=.2))+
ylab("Calories per serving")+
geom_smooth(method="lm", se=FALSE)
plot
help(pvalues)
help("pval")
??p-values
format.pval(calories.pvalue,eps=.001
)
# Generate multiple reports from a single RMarkdown documents
# You need two files.
#   This file which select the data to be analyzed and repeatively calls the Rmarkdown file
#   The RMarkdown document which generates the report
# File 1: Should be an R-Script
# contains a loop that iteratively calls an Rmarkdown file (i.e. File 2)
# load packages
library(knitr)
library(markdown)
library(rmarkdown)
cereal <- read.csv('cereal.csv',
header=TRUE, as.is=TRUE, strip.white=TRUE)
xtabs(~mfr, data=cereal)
# create the directory for the reports
dir.create("reports")
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::d_ply(cereal[ cereal$mfr %in% c("A","G"),], "mfr", function (my.cereal){
rmarkdown::render('Report.Rmd',  # file 2
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".html", sep=''),
output_dir = 'reports')
})
# for pdf reports
#   rmarkdown::render(input = "/Users/majerus/Desktop/R/auto_reporting/test/r_script_pdf.Rmd",
#           output_format = "pdf_document",
#           output_file = paste("test_report_", car, Sys.Date(), ".pdf", sep=''),
#           output_dir = "/Users/majerus/Desktop/R/auto_reporting/test/reports")
}
xtabs(~mfr, data=cereal)
help("render")
# Generate multiple reports from a single RMarkdown documents
# You need two files.
#   This file which select the data to be analyzed and repeatively calls the Rmarkdown file
#   The RMarkdown document which generates the report
# File 1: Should be an R-Script
# contains a loop that iteratively calls an Rmarkdown file (i.e. File 2)
# load packages
library(knitr)
library(markdown)
library(rmarkdown)
cereal <- read.csv('cereal.csv',
header=TRUE, as.is=TRUE, strip.white=TRUE)
xtabs(~mfr, data=cereal)
# create the directory for the reports
dir.create("reports")
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::d_ply(cereal[ cereal$mfr %in% c("K","G"),], "mfr", function (my.cereal){
rmarkdown::render('Report.Rmd',  # file 2
output_format="all",
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".html", sep=''),
output_dir = 'reports')
})
# for pdf reports
#   rmarkdown::render(input = "/Users/majerus/Desktop/R/auto_reporting/test/r_script_pdf.Rmd",
#           output_format = "pdf_document",
#           output_file = paste("test_report_", car, Sys.Date(), ".pdf", sep=''),
#           output_dir = "/Users/majerus/Desktop/R/auto_reporting/test/reports")
}
# Generate multiple reports from a single RMarkdown documents
# You need two files.
#   This file which select the data to be analyzed and repeatively calls the Rmarkdown file
#   The RMarkdown document which generates the report
# File 1: Should be an R-Script
# contains a loop that iteratively calls an Rmarkdown file (i.e. File 2)
# load packages
library(knitr)
library(markdown)
library(rmarkdown)
cereal <- read.csv('cereal.csv',
header=TRUE, as.is=TRUE, strip.white=TRUE)
xtabs(~mfr, data=cereal)
# create the directory for the reports
dir.create("reports")
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::d_ply(cereal[ cereal$mfr %in% c("K","G"),], "mfr", function (my.cereal){
rmarkdown::render('Report.Rmd',  # file 2
output_format="all",
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".html", sep=''),
output_dir = 'reports')
})
# Generate multiple reports from a single RMarkdown documents
# You need two files.
#   This file which select the data to be analyzed and repeatively calls the Rmarkdown file
#   The RMarkdown document which generates the report
# File 1: Should be an R-Script
# contains a loop that iteratively calls an Rmarkdown file (i.e. File 2)
# load packages
library(knitr)
library(markdown)
library(rmarkdown)
cereal <- read.csv('cereal.csv',
header=TRUE, as.is=TRUE, strip.white=TRUE)
xtabs(~mfr, data=cereal)
# create the directory for the reports
dir.create("reports")
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::d_ply(cereal[ cereal$mfr %in% c("K","G"),], "mfr", function (my.cereal){
rmarkdown::render('Report.Rmd',  # file 2
output_format="all",
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".html", sep=''),
output_dir = 'reports')
})
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::d_ply(cereal[ cereal$mfr %in% c("K","G"),], "mfr", function (my.cereal){
browser()
rmarkdown::render('Report.Rmd',  # file 2
output_format="all",
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".html", sep=''),
output_dir = 'reports')
})
paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".html", sep='')
rmarkdown::render('Report.Rmd',  # file 2
output_format="all",
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".html", sep=''),
output_dir = 'reports')
type="pdf"
rmarkdown::render('Report.Rmd',  # file 2
output_format=type,
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".", type, sep=''),
output_dir = 'reports')
type="pdf_document"
substr(type,1,-1+regexpr("_", type,fixed=TRUE)
)
rmarkdown::render('Report.Rmd',  # file 2
output_format=type,
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".",
substr(type,1,-1+regexpr("_", type,fixed=TRUE)), sep=''),
output_dir = 'reports')
# Generate multiple reports from a single RMarkdown documents
# You need two files.
#   This file which select the data to be analyzed and repeatively calls the Rmarkdown file
#   The RMarkdown document which generates the report
# File 1: Should be an R-Script
# contains a loop that iteratively calls an Rmarkdown file (i.e. File 2)
# load packages
library(knitr)
library(markdown)
library(rmarkdown)
cereal <- read.csv('cereal.csv',
header=TRUE, as.is=TRUE, strip.white=TRUE)
xtabs(~mfr, data=cereal)
# create the directory for the reports
dir.create("reports")
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::d_ply(cereal[ cereal$mfr %in% c("K","G"),], "mfr", function (my.cereal, types){
browser()
rmarkdown::render('Report.Rmd',  # file 2
output_format=type,
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".",
substr(type,1,-1+regexpr("_", type,fixed=TRUE)), sep=''),
output_dir = 'reports')
}, type="pdf_document")
# Generate multiple reports from a single RMarkdown documents
# You need two files.
#   This file which select the data to be analyzed and repeatively calls the Rmarkdown file
#   The RMarkdown document which generates the report
# File 1: Should be an R-Script
# contains a loop that iteratively calls an Rmarkdown file (i.e. File 2)
# load packages
library(knitr)
library(markdown)
library(rmarkdown)
cereal <- read.csv('cereal.csv',
header=TRUE, as.is=TRUE, strip.white=TRUE)
xtabs(~mfr, data=cereal)
# create the directory for the reports
dir.create("reports")
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::d_ply(cereal[ cereal$mfr %in% c("K","G"),], "mfr", function (my.cereal, types){
#browser()
rmarkdown::render('Report.Rmd',  # file 2
output_format=type,
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".",
substr(type,1,-1+regexpr("_", type,fixed=TRUE)), sep=''),
output_dir = 'reports')
}, type="pdf_document")
# Generate multiple reports from a single RMarkdown documents
# You need two files.
#   This file which select the data to be analyzed and repeatively calls the Rmarkdown file
#   The RMarkdown document which generates the report
# File 1: Should be an R-Script
# contains a loop that iteratively calls an Rmarkdown file (i.e. File 2)
# load packages
library(knitr)
library(markdown)
library(rmarkdown)
cereal <- read.csv('cereal.csv',
header=TRUE, as.is=TRUE, strip.white=TRUE)
xtabs(~mfr, data=cereal)
# create the directory for the reports
dir.create("reports")
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::d_ply(cereal[ cereal$mfr %in% c("K","G"),], "mfr", function (my.cereal, type){
#browser()
rmarkdown::render('Report.Rmd',  # file 2
output_format=type,
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".",
substr(type,1,-1+regexpr("_", type,fixed=TRUE)), sep=''),
output_dir = 'reports')
}, type="pdf_document")
# Generate multiple reports from a single RMarkdown documents
# You need two files.
#   This file which select the data to be analyzed and repeatively calls the Rmarkdown file
#   The RMarkdown document which generates the report
# File 1: Should be an R-Script
# contains a loop that iteratively calls an Rmarkdown file (i.e. File 2)
# load packages
library(knitr)
library(markdown)
library(rmarkdown)
cereal <- read.csv('cereal.csv',
header=TRUE, as.is=TRUE, strip.white=TRUE)
xtabs(~mfr, data=cereal)
# create the directory for the reports
dir.create("reports")
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::d_ply(cereal[ cereal$mfr %in% c("K","G"),], "mfr", function (my.cereal, type){
#browser()
rmarkdown::render('Report.Rmd',  # file 2
output_format=type,
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".",
substr(type,1,-1+regexpr("_", type,fixed=TRUE)), sep=''),
output_dir = 'reports')
}, type="word_document")
# Generate multiple reports from a single RMarkdown documents
# You need two files.
#   This file which select the data to be analyzed and repeatively calls the Rmarkdown file
#   The RMarkdown document which generates the report
# File 1: Should be an R-Script
# contains a loop that iteratively calls an Rmarkdown file (i.e. File 2)
# load packages
library(knitr)
library(markdown)
library(rmarkdown)
cereal <- read.csv('cereal.csv',
header=TRUE, as.is=TRUE, strip.white=TRUE)
xtabs(~mfr, data=cereal)
# create the directory for the reports
dir.create("reports")
# for each manufacturer create a report
# these reports are saved in output_dir with the name specified by output_file
plyr::d_ply(cereal[ cereal$mfr %in% c("K","G"),], "mfr", function (my.cereal, type){
#browser()
rmarkdown::render('Report.Rmd',  # file 2
output_format=type,
output_file =  paste("report_", my.cereal$mfr[1], '_', Sys.Date(), ".",
substr(type,1,-1+regexpr("_", type,fixed=TRUE)), sep=''),
output_dir = 'reports')
}, type="html_document")
# You can use word_document,  pdf_document, html_document etc for the type of file.
# Consult the documentation
