content
stringlengths
0
14.9M
filename
stringlengths
44
136
library(shiny) require(ztable) vector2string=function(v){ temp=paste0(v,collapse="",sep=",") temp1=substr(temp,start=1,stop=nchar(temp)-1) return(temp1) } shinyServer(function(input, output,session) { observe({ myncol=mynrow=c() spanRow=spanCol=c() data1=c() # Generate a ztable i <- as.numeric(input$data) if(i==1) data=head(iris,10) else if(i==2) data=head(mtcars,10) else if(i==3) data=lm(mpg ~ cyl + disp + wt + drat + am, data=mtcars) else if(i==4) data=aov(mpg ~ ., data=mtcars) else if(i==5) data=anova(lm(mpg ~ cyl + disp + wt + drat + am, data=mtcars)) else if(i==6) data=anova(lm(mpg ~ cyl + disp + wt + drat + am, data=mtcars), lm(mpg ~ cyl+wt, data=mtcars)) else if(i==7){ counts <- c(18,17,15,20,10,20,25,13,12) outcome <- gl(3,1,9) treatment <- gl(3,3) data <- glm(counts ~ outcome + treatment, family = poisson()) } else if(i==8){ counts <- c(18,17,15,20,10,20,25,13,12) outcome <- gl(3,1,9) treatment <- gl(3,3) fit <- glm(counts ~ outcome + treatment, family = poisson()) data<-anova(fit) } else if(i==9){ data(USArrests) data <- prcomp(USArrests) } else if(i==10){ data(USArrests) pr1 <- prcomp(USArrests) data=summary(pr1) } else if(i==11){ DNase1 <- subset(DNase, Run == 1) data <- nls(density ~ SSlogis(log(conc), Asym, xmid, scal),DNase1) } z<-ztable(data) z$spanCol=NULL z$spanRow=NULL myncol<-ncol(z$x) mynrow<-nrow(z$x) size=as.numeric(input$size) z$caption=input$caption z$include.colnames=input$colname z$include.rownames=input$rowname if(input$Tabset=="Data") { spanRow<-z$spanRow spanCol<-z$spanCol updateSelectInput(session,"cols",choices=(2-input$rowname):(ncol(z$x)+1)) updateSelectInput(session,"ccols",choices=(2-input$rowname):(ncol(z$x)+1)) updateSelectInput(session,"rows",choices=(2-input$colname):(nrow(z$x)+1)) updateSelectInput(session,"crows",choices=(2-input$colname):(nrow(z$x)+1)) updateSelectInput(session,"color",selected="platinum") updateSelectInput(session,"rowcolor",selected="pink") updateSelectInput(session,"ccolor",selected="orange") updateTextInput(session,"caption",value=paste("Table ",i,". This table is for demonstration of ztable",sep="")) updateRadioButtons(session,"caption.position",selected="c") updateCheckboxInput(session,"addcgroup",value=FALSE) updateCheckboxInput(session,"addrgroup",value=FALSE) updateNumericInput(session,"cspan.rgroup",min=1,max=ncol(z$x),value=1,step=1) updateSelectInput(session,'spanColRow',choices=2:(nrow(z$x)+1),selected=3) updateSliderInput(session,"spanCol",min=2,max=ncol(z$x)+1,value=c(2,2)) updateSelectInput(session,"spanColColor",selected="yellow") updateSelectInput(session,'spanRowCol',choices=2:(ncol(z$x)+1),selected=ncol(z$x)+1) updateSliderInput(session,"spanRow",min=2,max=nrow(z$x)+1, value=c(nrow(z$x)+1,nrow(z$x)+1)) updateSelectInput(session,"spanRowColor",selected="lightcyan") if(!is.null(z$cgroup)) { updateTextInput(session,'cgroup',value=vector2string(z$cgroup[1,])) updateTextInput(session,'n.cgroup',value=vector2string(z$n.cgroup[1,])) updateCheckboxInput(session,"addcgroup",value=TRUE) } if(!is.null(z$rgroup)) { updateTextInput('rgroup',value=vector2string(z$rgroup)) updateTextInput('n.rgroup',value=vectorsstring(z$n.rgroup)) updateNumericInput(session,"cspan.rgroup",min=1,max=ncol(z$x),value=z$cspan.rgroup,step=1) updateCheckboxInput(session,"addrgroup",value=TRUE) } updateSelectInput(session,"vladd",choices=(2-input$rowname):(ncol(z$x)+2)) updateSelectInput(session,"vldel",choices=(2-input$rowname):(ncol(z$x)+2)) updateSelectInput(session,"hladd",choices=1:(nrow(z$x)-1)) updateSelectInput(session,"hldel",choices=1:(nrow(z$x)-1)) } z$caption.position=input$caption.position z$caption.placement=input$caption.placement if(!is.null(input$rows)) { brow=as.integer(input$rows) z=addRowColor(z,rows=brow,input$rowcolor) } if(!is.null(input$cols)) { b=as.integer(input$cols) z=addColColor(z,cols=b,input$color) } if((!is.null(input$ccols))&(!is.null(input$crows))) { bcol=as.integer(input$ccols) brow=as.integer(input$crows) z=addCellColor(z,cols=bcol,rows=brow,input$ccolor) } if((!is.null(input$fcols))&(!is.null(input$frows))) { bcol=as.integer(input$fcols) brow=as.integer(input$frows) z=addFrontColor(z,cols=bcol,rows=brow,input$fcolor) } if(input$addcgroup) { mycgroup=unlist(strsplit(input$cgroup,",",fixed=TRUE)) myncgroup=unlist(strsplit(input$n.cgroup,",",fixed=TRUE)) csum=as.integer(myncgroup) if(sum(csum) <= ncol(z$x)) z=addcgroup(z,mycgroup,csum) } if(input$addrgroup) { myrgroup=unlist(strsplit(input$rgroup,",",fixed=TRUE)) mynrgroup=unlist(strsplit(input$n.rgroup,",",fixed=TRUE)) rsum=as.integer(mynrgroup) if(sum(rsum) <= nrow(z$x)) z=addrgroup(z,myrgroup,rsum,input$cspan.rgroup) } if(input$spanCol[1]!=input$spanCol[2]) { z=spanCol(z,row=as.integer(input$spanColRow), from=input$spanCol[1],to=input$spanCol[2],color=input$spanColColor) spanCol<-z$spanCol } if(input$spanRow[1]!=input$spanRow[2]) { z=spanRow(z,col=as.integer(input$spanRowCol), from=input$spanRow[1],to=input$spanRow[2],color=input$spanRowColor) spanRow<-z$spanRow } if(is.null(input$vladd)) myadd=NULL else myadd=as.integer(input$vladd) if(is.null(input$vldel)) mydel=NULL else mydel=as.integer(input$vldel) z=vlines(z,type=as.integer(input$vltype),add=myadd,del=mydel) if(is.null(input$hladd)) myadd=NULL else myadd=as.integer(input$hladd) if(is.null(input$hldel)) mydel=NULL else mydel=as.integer(input$hldel) z=hlines(z,type=as.integer(input$hltype),add=myadd,del=mydel) output$overview <- renderPrint({ print(z,type="html",size=size) }) output$a_out<-renderPrint({ i <- as.numeric(input$data) if(i==1) data1="head(iris,10)" else if(i==2) data1="head(mtcars,10)" else if(i==3) data1="lm(mpg ~ cyl + disp + wt + drat + am, data=mtcars)" else if(i==4) data1="aov(mpg ~ ., data=mtcars)" else if(i==5) { cat("fit=lm(mpg ~ cyl + disp + wt + drat + am,data=mtcars)\n") data1="anova(fit)" } else if(i==6) { cat("fit1=lm(mpg ~ cyl + disp + wt + drat + am, data=mtcars)\n") cat("fit2=lm(mpg ~ cyl+wt, data=mtcars)\n") data1="anova(fit1,fit2)" } else if(i==7) { cat("counts <- c(18,17,15,20,10,20,25,13,12)\noutcome <- gl(3,1,9)\ntreatment <- gl(3,3)\n") cat("out=glm(counts ~ outcome + treatment, family = poisson())\n") data1="out" } else if(i==8) { cat("counts <- c(18,17,15,20,10,20,25,13,12)\noutcome <- gl(3,1,9)\ntreatment <- gl(3,3)\n") cat("out=glm(counts ~ outcome + treatment, family = poisson())\n") data1="anova(out)" } else if(i==9){ cat("data(USArrests)\n") data1 <- "prcomp(USArrests)" } else if(i==10){ cat("data(USArrests)\n") cat("out=summary(prcomp(USArrests))\n") data1="out" } else if(i==11){ cat("DNase1 <- subset(DNase, Run == 1)\n") cat("out <- nls(density ~ SSlogis(log(conc), Asym, xmid, scal),DNase1)\n") data1="out" } cat(paste("z=ztable( ",data1,", size=",as.numeric(input$size)," )\n",sep="")) if(input$Tabset=="Data") { if(!input$colname) cat("z$include.colname=",input$colname,"\n") if(!input$rowname) cat("z$include.rowname=",input$rowname,"\n") } else if(input$Tabset=="Caption") { cat("z$caption=",deparse(input$caption),"\n") if(input$caption.placement!="top") cat("z$caption.placement=",deparse(input$caption.placement),"\n") if(input$caption.position!="c") cat("z$caption.position=",deparse(input$caption.position),"\n") } else if(input$Tabset=="addColColor"){ if(!is.null(input$cols)){ b=as.integer(input$cols) sb=b[1] if(length(b)>1){ for(i in 2:length(b)) sb=paste(sb,b[i],sep=",") } cat(paste("z=addColColor(z,cols=c(",sb, "),color=",deparse(input$color),")\n",sep="")) } } else if(input$Tabset=="spanCol"){ if(input$spanCol[1]!=input$spanCol[2]){ cat(paste("z=spanCol(z,row=",input$spanColRow, ",from=",input$spanCol[1],",to=",input$spanCol[2], ",color=",deparse(input$spanColColor),")\n",sep="")) } } else if(input$Tabset=="spanRow"){ if(input$spanRow[1]!=input$spanRow[2]){ cat(paste("z=spanRow(z,col=",input$spanRowCol, ",from=",input$spanRow[1],",to=",input$spanRow[2], ",color=",deparse(input$spanRowColor),")\n",sep="")) } } else if(input$Tabset=="addRowColor"){ if(!is.null(input$rows)){ brow=as.integer(input$rows) sbrow=brow[1] if(length(brow)>1){ for(i in 2:length(brow)) sbrow=paste(sbrow,brow[i],sep=",") } cat(paste("z=addRowColor(z,rows=c(",sbrow, "),color=",deparse(input$rowcolor),")\n",sep="")) } } else if(input$Tabset=="addCellColor"){ if(!is.null(input$crows)){ brow=as.integer(input$crows) sbrow=brow[1] if(length(brow)>1){ for(i in 2:length(brow)) sbrow=paste(sbrow,brow[i],sep=",") } bcol=as.integer(input$ccols) sbcol=bcol[1] if(length(bcol)>1){ for(i in 2:length(bcol)) sbcol=paste(sbcol,bcol[i],sep=",") } cat(paste("z=addCellColor(z,rows=c(",sbrow, "),cols=c(",sbcol,"),color=",deparse(input$ccolor),")\n",sep="")) } } else if(input$Tabset=="addFrontColor"){ if(!is.null(input$frows)){ brow=as.integer(input$frows) sbrow=brow[1] if(length(brow)>1){ for(i in 2:length(brow)) sbrow=paste(sbrow,brow[i],sep=",") } bcol=as.integer(input$fcols) sbcol=bcol[1] if(length(bcol)>1){ for(i in 2:length(bcol)) sbcol=paste(sbcol,bcol[i],sep=",") } cat(paste("z=addFrontColor(z,rows=c(",sbrow, "),cols=c(",sbcol,"),color=",deparse(input$fcolor),")\n",sep="")) } } else if(input$Tabset=="addcgroup"){ if(input$addcgroup>0) { mycgroup=unlist(strsplit(input$cgroup,",",fixed=TRUE)) temp=paste("'",mycgroup[1],"'",sep="") if(length(mycgroup)>1){ for(i in 2:length(mycgroup)) temp=paste(temp,",'",mycgroup[i],"'",sep="") } cat(paste("z=addcgroup(z,cgroup=c(",temp, "),n.cgroup=c(",input$n.cgroup,"))\n",sep="")) myncgroup=unlist(strsplit(input$n.cgroup,",",fixed=TRUE)) csum=as.integer(myncgroup) if(sum(csum) > myncol) cat("## Sum of n.cgroup(",sum(csum), ") must be qual to or lesser than column count(",myncol,")\n") } } else if(input$Tabset=="addrgroup"){ if(input$addrgroup>0) { myrgroup=unlist(strsplit(input$rgroup,",",fixed=TRUE)) temp=paste("'",myrgroup[1],"'",sep="") if(length(myrgroup)>1){ for(i in 2:length(myrgroup)) temp=paste(temp,",'",myrgroup[i],"'",sep="") } cat(paste("z=addrgroup(z,rgroup=c(",temp, "),n.rgroup=c(",input$n.rgroup,"),cspan.rgroup=", input$cspan.rgroup,")\n",sep="")) mynrgroup=unlist(strsplit(input$n.rgroup,",",fixed=TRUE)) rsum=as.integer(mynrgroup) if(sum(rsum) > mynrow) { temp=paste("## Sum of n.rgroup(",sum(rsum), ") must be qual to or lesser than row count(",mynrow,")\n",sep="") cat(temp) if(FALSE) { observe({ session$sendCustomMessage(type = 'testmessage', message = list(text=temp, controller = input$n.rgroup)) }) } } } } else if(input$Tabset=="vlines"){ if(is.null(input$vladd)) sa="NULL" else { a=as.integer(input$vladd) sa=a[1] if(length(a)>1){ for(i in 2:length(a)) sa=paste(sa,a[i],sep=",") } } if(is.null(input$vldel)) sd="NULL" else { d=as.integer(input$vldel) sd=d[1] if(length(d)>1){ for(i in 2:length(d)) sd=paste(sd,d[i],sep=",") } } cat(paste("vlines(z,type=",as.integer(input$vltype), ",add=",sa,",del=",sd,")\n",sep="")) } else if(input$Tabset=="hlines"){ if(is.null(input$hladd)) sa="NULL" else { a=as.integer(input$hladd) sa=a[1] if(length(a)>1){ for(i in 2:length(a)) sa=paste(sa,a[i],sep=",") } } if(is.null(input$hldel)) sd="NULL" else { d=as.integer(input$hldel) sd=d[1] if(length(d)>1){ for(i in 2:length(d)) sd=paste(sd,d[i],sep=",") } } cat(paste("hlines(z,type=",as.integer(input$hltype), ",add=",sa,",del=",sd,")\n",sep="")) } cat("z\n") #cat("input$spanRowCol=",input$spanRowCol,"\n") #cat("input$spanRow=",input$spanRow,"\n") #cat("input$spanColRow=",input$spanColRow,"\n") #cat("input$spanCol=",input$spanCol,"\n") }) output$downloadReport <- downloadHandler( filename = function() { paste('my-report', sep = '.', switch( input$format, PDF = 'pdf', HTML = 'html', Word = 'docx' )) }, content = function(file) { src <- normalizePath('report.Rmd') # temporarily switch to the temp dir, in case you do not have write # permission to the current working directory owd <- setwd(tempdir()) on.exit(setwd(owd)) file.copy(src, 'report.Rmd') library(rmarkdown) out <- render('report.Rmd', switch( input$format, PDF = pdf_document(), HTML = html_document(), Word = word_document() )) file.rename(out, file) } ) }) })
/scratch/gouwar.j/cran-all/cranData/ztable/inst/ztableDemo/server.R
library(shiny) string="This is string" excolors=c("platinum","pink","yellow","orange","lightcyan","white") # Define UI for random distribution application shinyUI(fluidPage( # Application title titlePanel("Demonstration of ztable"), # Sidebar with controls to select the independent variable # and options of plot to generate. Note the use of the # br() element to introduce extra vertical spacing sidebarLayout( sidebarPanel( tabsetPanel(id="Tabset", tabPanel("Data", br(), radioButtons("data", "Select Data and Click the Button:", c("iris" = 1, "mtcars" = 2, "lm" = 3, "aov" = 4,"anova"=5 ,"another anova"=6, "glm" = 7,"another anova"=8,"prcomp"=9, "summary.prcomp"=10,"non-linear least squre"=11)), br(), sliderInput("size", "Select Font Size:", min = 1, max = 10, value = 5), checkboxInput("colname",label="show column names",value=TRUE), checkboxInput("rowname",label="show row names",value=TRUE) ), tabPanel("Caption", br(), textInput("caption","Caption: ","Table 1. This is a demonstration of ztable"), radioButtons("caption.placement", "Caption Placement: ", c("top" = "top", "bottom"="bottom")), radioButtons("caption.position", "Caption Position: ", c("left" = "l", "center"="c","right"="r")) ), tabPanel("addColColor", br(), selectInput('cols','Columns',1:10,multiple=TRUE,selectize=TRUE), selectInput("color","Color",excolors,selectize=TRUE) ), tabPanel("addRowColor", br(), selectInput('rows','Rows',1:10,multiple=TRUE,selectize=TRUE), selectInput("rowcolor","Color",excolors,selectize=TRUE) ), tabPanel("addCellColor", br(), selectInput('crows','Rows',1:10,multiple=TRUE,selectize=TRUE), selectInput('ccols','Columns',1:10,multiple=TRUE,selectize=TRUE), selectInput("ccolor","Color",excolors,selectize=TRUE) ), tabPanel("addFrontColor", br(), selectInput('frows','Rows',1:10,multiple=TRUE,selectize=TRUE), selectInput('fcols','Columns',1:10,multiple=TRUE,selectize=TRUE), selectInput("fcolor","Color",excolors,selectize=TRUE) ), tabPanel("addcgroup", br(), textInput('cgroup','cgroup',"Group A,Group B"), textInput('n.cgroup','n.cgroup',"2,3"), checkboxInput("addcgroup","addcgroup",value=FALSE) ), tabPanel("addrgroup", br(), textInput('rgroup','rgroup',"OneTwo,ThreeFour"), textInput('n.rgroup','n.rgroup',"2,2"), numericInput('cspan.rgroup','cspan.rgroup',1), checkboxInput("addrgroup","addrgroup",value=FALSE) ), tabPanel("spanCol", br(), selectInput('spanColRow','Select Row',2:5), sliderInput("spanCol","Select Column Range",min=2,max=5,value=c(2,2)), selectInput("spanColColor","Select Color",excolors,selectize=TRUE) ), tabPanel("spanRow", br(), selectInput('spanRowCol','Select Column',2:5), sliderInput("spanRow","Select Row Range",min=2,max=5,value=c(2,2)), selectInput("spanRowColor","Select Color",excolors,selectize=TRUE) ), tabPanel("vlines", br(), checkboxInput('vltype','add all vertical lines:',value=FALSE), selectInput("vladd","add:",1:5,multiple=TRUE,selectize=TRUE), selectInput("vldel","del:",1:5,multiple=TRUE,selectize=TRUE) ), tabPanel("hlines", br(), checkboxInput('hltype','add all horizontal lines:',value=FALSE), selectInput("hladd","add:",1:5,multiple=TRUE,selectize=TRUE), selectInput("hldel","del:",1:5,multiple=TRUE,selectize=TRUE) ) )), # Show a tabset that includes a plot, summary, and table view # of the generated distribution mainPanel( radioButtons('format', 'Export report format:', c('PDF', 'HTML'), inline = TRUE), checkboxGroupInput("latexOption", "LaTex Option:", c("longtable" = "1", "sidewaystable" = "2")), downloadButton('downloadReport'), hr(), verbatimTextOutput('a_out'), htmlOutput("overview") ) ) ) )
/scratch/gouwar.j/cran-all/cranData/ztable/inst/ztableDemo/ui.R
--- title: "Make a Heatmap Table using `ztable`" author: "Keon-Woong Moon" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{heatmapTable} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = NA, message=FALSE ) ``` ## Installation You can install R package "ztable" from CRAN. Current version is 0.1.8. ```{r,eval=FALSE} install.packages("ztable") ``` To make a heatmap table, you have to install the developmental version of ztable from github. Current github version is 0.2.0. ```{r,eval=FALSE} if(!require(devtools)) install.packages("devtools") devtools::install_github("cardiomoon/ztable") ``` ## Introduction A heat map (or heatmap) is a graphical representation of data where the individual values contained in a matrix are represented as colors. You can summarize the the diagnosis and smoking status of 857 patients of acute coronary syndrome(acs) using table() function. ```{r} require(moonBook) x=table(acs$Dx,acs$smoking) x ``` ## Basic Table You can make `html` or `LaTex` table easily with ztable. ```{r,results="asis"} library(ztable) library(magrittr) options(ztable.type="html") z=ztable(x) print(z,caption="Table 1. Basic Table") ``` ## Formatting the Table You can change the background color and font color of `ztable` using addCellColor function. For example, you can change the cell color of the 3rd row, 2nd column. Please keep in mind that the ztable count colname and rowname. ```{r,results="asis"} z %>% addCellColor(4,3,bg="orange",color="white") %>% print(caption="Table 2. Add Cell Color") ``` ## Conditional Formatting You can select rows with logical expression. You can select cols with column name. ```{r,results='asis'} ztable(head(iris),caption="Table 3. Conditinoal Formatting: Sepal.Width >= 3.5") %>% addRowColor(rows=1,bg="#C90000",color="white") %>% addCellColor(condition=Sepal.Width>=3.5,cols=Sepal.Width,color="red") ``` ## Make a Heatmap Table You can make a heatmap table in which background colors representing the values. With makeHeatmap() function, you can make a heatmap table easily. The makeHeatmap() function apply the "Reds" palette from RColorBrewer package. ```{r,results="asis"} z %>% makeHeatmap() %>% print(caption="Table 4. Heatmap Table") ``` ## Heatmap Table with desired palette You can change the palette with palette argument. For example, you can use the "Blue" palette. ```{r,results='asis'} ztable(head(mtcars)) %>% makeHeatmap(palette="Blues") %>% print(caption="Table 5. Heatmap table with 'Blue' palette") ``` ## Heatmap Table with user-defined palette With the gradientColor() function, you makes sequential colour gradient palette easily. ```{r,fig.width=8,out.width='100%'} mycolor=gradientColor(low="yellow",mid="orange",high="red",n=20,plot=TRUE) mycolor ``` ```{r,results='asis'} ztable(head(mtcars[1:5])) %>% makeHeatmap(mycolor=mycolor) %>% print(caption="Table 6. Heatmap table with user-defined palette") ``` ## Heatmap Table with non-numeric data You can make heatmap table with data containing non-numeric columns. Only columns with numeric data affected by this function. ```{r,results='asis'} ztable(head(acs[1:10])) %>% makeHeatmap %>% print(caption="Table 7. Heatmap table with non-numeric data") ``` ## Selected Columnwise Heatmap Table You can make selected columnwise heatmap table. You can select columns with `cols` argument. To make columnwise heatmap table, set the `margin` argument 2. ```{r,results='asis'} ztable(head(mtcars)) %>% makeHeatmap(palette="YlOrRd",cols=c(1,3,4),margin=2) %>% print(caption="Table 8. Columnwise heatmap table") ``` ## Selected Rowwise Heatmap Table You can make selected columnwise heatmap table. You can select rows with `rows` argument. To make rowwise heatmap table, set the `margin` argument 1. ```{r,results='asis'} ztable(t(head(mtcars))) %>% makeHeatmap(palette="YlOrRd",rows=c(1,3,4),margin=1) %>% print(caption="Table 9. Rowwise heatmap table") ```
/scratch/gouwar.j/cran-all/cranData/ztable/vignettes/heatmapTable.Rmd
--- title: "Package ztable" author: "Keon-Woong Moon" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{ztable} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- # Introduction ## Table Show Package "ztable" make everything possible about table. Basically, An object of "ztable" made from a data.frame. The default output format of ztable is RStudio::viewer or web-browser format(type="viewer"). So if you want to use ztable in a "html" format, you should change the parameter ztable.type to "html". If you want to use ztable in latex format, you should change the parameter ztable.type to "latex". ```{r,results='asis'} library(ztable) library(magrittr) options(ztable.type="html") z=ztable(head(iris)) z ``` You can change the position of data in each cell by adjusting the parameter "align". ```{r,results='asis'} z=ztable(head(iris),align="cccccc") z ``` You can change background color and font color with addRowColor() function. ```{r,results='asis'} z <- ztable(head(iris)) z <- addRowColor(z, rows=1,bg="#C90000",color="white") print(z) ``` The pipe operator("%>%") from magrittr package can simplify your R code. ```{r,results='asis'} ztable(head(iris)) %>% addRowColor(rows=1,bg="#C90000",color="white") %>% print ``` You can add column groups to ztable using addcgroup function. The n.cgroup means how much columns included in each row group. ```{r,results='asis'} cgroup=c("Sepal","Petal","Species") n.cgroup=c(2,2,1) z <- ztable(head(iris)) %>% addcgroup(cgroup=cgroup,n.cgroup=n.cgroup) z ``` You can add row groups to ztable using addrgroup function. The n.rgroup means how much rows included in each row group. The cspan.rgroup means how much columns occupied by row group name. ```{r,results='asis'} rgroup=c("OneToThree","Four","FiveToSix") n.rgroup=c(3,1,2) z <- z %>% addrgroup(rgroup=rgroup,n.rgroup=n.rgroup,cspan.rgroup=1) z print(z,type="latex") ``` You can add another colname(subcolname), the N count for example. The length of subcolnames should be same with column count of data.frame. You can use "NA" and the column name spans 2 rows. ```{r,results='asis'} ncount=c(123,120,123,124) sub=paste("(N=",ncount,")",sep="") z=addSubColNames(z,c(sub,NA)) z ``` You can merge cells by spanRow or spanCol function. ```{r,results='asis'} z=spanRow(z,col=2,from=4,to=7,bg="lightcyan",color="red") z=spanRow(z,col=3,from=5,to=7,"platinum","blue") z=spanRow(z,col=4,from=6,to=7,"cyan") z=spanRow(z,col=5,from=5,to=7,"yellow") z=spanRow(z,col=6,from=3,to=5,"yellow") z z=spanCol(z,row=2,from=3,to=4,"yellow") z=spanCol(z,row=3,from=4,to=5,"lightblue") z ``` You can add or adjust vertical lines of table by vlines function ```{r,results='asis'} vlines(z,type="all") # type=1 gets same result z <- vlines(z,type="none") # type=0 gets same result z z <- z %>% vlines(add=c(1,2,5)) z ``` Please note that if you add vertical lines between groups, the space between groups(empty columns) disappeared and vice versa. ## Merge two tables You can bind two or more data.frame by cbind function. ```{r,results='asis'} t1=head(iris,10)[,c(1,3,5)] t2=tail(iris,10)[,c(1,3,5)] t=cbind(t1,t2) z=ztable(t,caption="Table 1. Top 10 and Last 10 Data from iris",align="ccccccc") z ``` And then, you can add column groups, row groups, add row colors, add column colors, add cell colors, and merge cells ```{r,results='asis'} cgroup=c("Top 10","Last 10") n.cgroup=c(3,3) z=addcgroup(z,cgroup=cgroup,n.cgroup=n.cgroup) z rgroup=c("Top 1-3","Top 4-5",NA," Top 7-10") n.rgroup=c(3,2,1,4) z=addrgroup(z,rgroup=rgroup,n.rgroup=n.rgroup,cspan.rgroup=1) z z <- z %>% addRowColor(c(5,10),"pink") %>% addColColor(4,"amber") %>% addCellColor(rows=c(5,10),cols=4,"red","white") z z <- z %>% spanCol(row=2,from=2,to=3,"lightcyan","red") %>% spanRow(col=7,from=7,to=8,"cyan") z hlines(z,type=1) ``` And you can adjust vertical lines, too. ```{r,results='asis'} vlines(z,type=0) # No vertical lines vlines(z,type=1) # Vertical lines for all column ``` # Basic Use Package "ztable" consist of one function: ztable. It's main function is creating zebra zebra striping tables(tables with alternating row colors) in both Latex and html formats easily from mainly data.frame or an R object such as matrix, lm, aov, anova, glm and coxph objects. It is fully customizable and you can get similar tables in both latex and html format without changing source. The default output is RStudio::viewer, but you can get html format by adding just one sentence. ```{r, eval=FALSE} options(ztable.type="html") ``` It's usage is somewhat similar to xtable, but very simple. ## data.frame ### Basic Use It's use is very simple. Just use 'ztable()' function. You can get the zebra striping table by set the parameter zebra=1 (default value is NULL) ```{r,results="asis",message=FALSE} require(ztable) options(ztable.type="html") options(ztable.zebra=1) options(ztable.zebra.color="platinum") options(ztable.colnames.bold=TRUE) ztable(head(mtcars)) ``` ### Tailoring zebra striping You can get non-zebra table by change parameter zebra=NULL or change zebra striping on even rows by zebra=2. ```{r,results='asis'} ztable(head(mtcars),zebra=NULL,size=3, caption="Table 1. Non-zebra Table with small size") ``` ### Customize the caption and the font size You can change the position of table by using parameter position. You can use "r" for right position, "l" for left position and "c" for center position(default). You can change the color of zebra striping by change the parameter zebra.color. You can also change the size of font from 1 to 10(default is 5). You can change the caption.placement("top" or "bottom") and caption.position("c" for center / "r" for right/ "l" for left). ```{r,results='asis'} ztable(head(mtcars[c(1:7)]),zebra=2,zebra.color="lightcyan",size=7, caption="Table 2. Left-sided caption at botom with large font", caption.placement="bottom",caption.position="l") ``` ## aov object 'ztable()' can be used for 'aov' object. When used for 'aov' object, the function call is added as footer to the table. The parameter 'show.footer' can be used whether or not include footer in the table. Default value is TRUE. ```{r,results="asis"} out <- aov(mpg ~ ., data=mtcars) ztable(out) ``` ## Linear model : 'lm' object 'ztable()' can be used for 'lm' object. When used for 'lm' object, the function call is added as footer to the table, too. ```{r,results='asis'} fit <- lm(mpg ~ cyl + disp + wt + drat + am, data=mtcars) ztable(fit) ``` ## Analysis of Variance Table : 'anova' object 'ztable()' can be used for 'anova' object to show the anova table. When used for 'anova' object, headings of anova are added as headings to the table. The parameter 'show.footer' can be used whether or not include footer in the table. Dafault value is TRUE. ```{r,results='asis'} a=anova(fit) ztable(a) ``` This is examples of another 'anova' object. The models in this anova tables showed as table headings. You can decide whether or not include the headings in the table by using parameter 'show.heading'(default: TRUE). ```{r,results='asis'} fit2 <- lm(mpg ~ cyl+wt, data=mtcars) b=anova(fit2,fit) ztable(b) ztable(b,show.heading=FALSE) ``` ## Generalized linear model ; 'glm' object 'ztable()' can be used for 'glm'(generalized linear model) object. In this time, 'ztable()' shows the **odds ratio(OR) and 95% confidence interval** as well as standard R output. ```{r,results='asis',warning=FALSE} require(survival) data(cancer) attach(colon) out <- glm(status ~ rx+obstruct+adhere+nodes+extent, data=colon, family=binomial) ztable(out) ``` Again, 'ztable()' also shows the anova table of this model. ```{r,results='asis'} anova(out) ztable(anova(out)) ``` ## More 'aov' object ```{r,results='asis'} op <- options(contrasts = c("contr.helmert", "contr.poly")) npk.aov <- aov(yield ~ block + N*P*K, npk) ztable(npk.aov,zebra=1) ``` ## More 'lm' object ```{r,results='asis'} ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14) trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69) group <- gl(2, 10, 20, labels = c("Ctl","Trt")) weight <- c(ctl, trt) lm.D9 <- lm(weight ~ group) ztable(lm.D9) ztable(anova(lm.D9),align="|c|rrrr|r|") ``` ## More 'glm' object ```{r,results='asis'} counts <- c(18,17,15,20,10,20,25,13,12) outcome <- gl(3,1,9) treatment <- gl(3,3) d.AD <- data.frame(treatment, outcome, counts) glm.D93 <- glm(counts ~ outcome + treatment, family = poisson()) ztable(glm.D93) ``` ## Principal Components Analysis : 'prcomp' object 'ztable()' can be used in principal components analysis. Followings are examples of ztable() of 'prcomp' object. ```{r,results='asis',message=FALSE} data(USArrests) pr1 <- prcomp(USArrests) ztable(pr1) ztable(summary(pr1)) ``` ## Survival Analysis : 'coxph' object 'ztable()' can be used in survival analysis. When used for Cox proportional hazard model, 'ztable()' showed the hazard ratio and 95% confidence interval ready for publication to medical journal. ```{r,results='asis',message=FALSE} colon$TS = Surv(time,status==1) out=coxph(TS~rx+obstruct+adhere+differ+extent+surg+node4,data=colon) ztable(out) ``` ## Nonlinear Least Squares: 'nls' object 'ztable()' can be used to determine the nonlinear (weighted) least-squares estimates of the parameters of a nonlinear model. Followings are examples of ztable() of 'nls' object. ```{r,comment=NA} require(graphics) DNase1 <- subset(DNase, Run == 1) ## using a selfStart model fm1DNase1 <- nls(density ~ SSlogis(log(conc), Asym, xmid, scal),DNase1) summary(fm1DNase1) ``` ```{r,results='asis',message=FALSE} ztable(fm1DNase1) ``` ## Maximum-likelihood Fitting of Univariate Distributions 'ztable()' can be used in maximum-likelihood fitting of univariate distributions. Followings are examples of ztable() of 'fitdistr' object. ```{r,results='asis'} require(MASS) set.seed(123) x <- rgamma(100, shape = 5, rate = 0.1) a=fitdistr(x, "gamma") ztable(a) x3 <- rweibull(100, shape = 4, scale = 100) b=fitdistr(x3, "weibull") ztable(b) ``` ## Customize the zebra striping colors If you wanted to use several colors for zebra striping, you can set the parameter 'zebra' to zero(e.g. zebra=0) and set the 'zebra.color' parameter with vector of your favorite colors. Your favorite colors are used to zebra striping. For your convienience, ten colors are predifned for this purpose. The predefined colors are: c("peach","peach-orange","peachpuff","peach-yellow","pear","pearl","peridot","periwinkle","pastelred", "pastelgray"). ```{r,results='asis',message=FALSE} ztable(head(mtcars,15),zebra=0,zebra.color=NULL) ``` The color names used for this purpose are predefined in the data 'zcolors' included in 'ztable' package. Please type '?zcolors' in R console for help file or just type 'zcolors'. You can see 749 color names defined in data 'zcolors'. ## Vertical striping If you wanted to vertical striping table, you can get it by set the parameter zebra.type 2. You can change the ztables parameters when printing. ```{r,results='asis'} z1=ztable(head(iris),zebra=2) z1 print(z1,zebra.type=2) print(z1,zebra=1,zebra.type=2,zebra.colnames=TRUE) ``` ## More tailoring zebra striping You can update parameters of ztable with 'update_ztable' function. ```{r,results='asis'} options(ztable.zebra.color=NULL) (z1=ztable(head(iris),zebra=0,zebra.type=2)) ``` You can change the background color of colnames rows by setting zebra.colnames=TRUE. ```{r,results='asis'} update_ztable(z1,colnames.bold=TRUE,zebra.colnames=TRUE) ``` You can customize the striping when printing. ```{r,results='asis'} print(z1,zebra.color=c(rep("white",5),"peach"),zebra.colnames=TRUE) ``` ## Change the background color of all cells You can change the background color of all cells by setting the zebra.type=0. ```{r,results='asis'} ztable(head(iris),zebra=0,zebra.type=0) ztable(head(iris),zebra=0,zebra.type=0,zebra.color=zcolors$name,zebra.colnames=TRUE) ``` ## Diagonal striping You can make diagonal striping with use of zebra.color greater/lesser than column length by 1. ```{r,results='asis'} ztable(head(iris),zebra=0,zebra.type=0,zebra.color=1:7,zebra.colnames=TRUE) ztable(head(mtcars[,1:9]),zebra=0,zebra.type=0,zebra.color=1:9,zebra.colnames=TRUE) ``` ## All background colors This is demonstration of All background colors. All 749 colors are available in package ztable. Please type ?zcolors. ```{r,results='asis'} mycolor=rep("white",6) for(i in 1:149){ mycolor=c(mycolor,"white",zcolors$name[((i-1)*5+1):((i-1)*5+5)]) } mycolor=c(mycolor,"white",zcolors$name[c(746:749,1)]) a=c(zcolors$name[1:5]) for(i in 2:149){ a=rbind(a,zcolors$name[((i-1)*5+1):((i-1)*5+5)]) } a=rbind(a,zcolors$name[c(746:749,1)]) a=data.frame(a,stringsAsFactors=FALSE,row.names=NULL) ztable(a,zebra=0,zebra.type=0,zebra.color=mycolor,include.rownames=FALSE, include.colnames=FALSE,longtable=TRUE) ``` ## Place two or more ztables or figures side by side If you wanted to place two or more ztables or figures side by side, you can use function **parallelTables()**. Function **parallelTables()** takes three parameters. The first parameter width is a numeric vector specifies the width to which the tables or figures should be scaled. The second parameter is a list of ztable or names of valid figure. The 3rd parameter 'type' is the type of table to produce. Possible values for type are "latex" or "html". Default value is "latex". See the examples. ```{r,results='asis'} z=ztable(head(mtcars[1:3]),tabular=TRUE,zebra.color="peach-orange") z1=ztable(head(iris[1:3]),tabular=TRUE,zebra=2) parallelTables(width=c(0.5,0.5),list(z,z1),type="html") parallelTables(width=c(0.5,0.5),list(z,"figures/ztable3.png"),type="html") ``` ## mytable object from "moonBook" package 'ztable()' can be used for 'mytable' object made by "mytable" function from "moonBook" package. ```{r,results='asis'} require(moonBook) res=mytable(Dx~.,data=acs) options(ztable.zebra=NULL) z=ztable(res) z vlines(z,type="all") ``` ## cbind.mytable object 'ztable()' can be used for 'cbind.mytable' object made by "mytable" function from "moonBook" package. ```{r,results='asis'} res1=mytable(sex+DM~.,data=acs) z=ztable(res1) z vlines(z,type="all") ``` You can use all ztable related function in this table. ```{r,results='asis'} z=addRowColor(z,c(13,16),"platinum") z=addColColor(z,c(5,8),"pink") z=addCellColor(z,rows=16,cols=c(5,8),bg="orange") z=addCellColor(z,rows=13,cols=5,bg="orange") z ``` You can use pipe from package "magrittr" ```{r,results='asis'} require(magrittr) res1=mytable(sex+DM~.,data=acs) z=ztable(res1) z %>% addRowColor(c(13,16),"platinum") %>% addColColor(c(5,8),"pink") %>% addCellColor(rows=16,cols=c(5,8),bg="orange") %>% addCellColor(rows=13,cols=5,bg="orange") %>% print ``` You can use addSigColor() function to colorized significant rows of ztable.mytable ```{r,results='asis'} res1=mytable(sex~.,data=acs) res1 %>% ztable %>% addSigColor %>% print res2<-mytable(sex+DM~.,data=acs) res2 %>% ztable %>% addSigColor(level=0.1,bg="yellow",color="red") %>% print ```
/scratch/gouwar.j/cran-all/cranData/ztable/vignettes/ztable.Rmd
--- title: "ztable Update" author: "Keon-Woong Moon" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{ztable_update} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = NA ) ``` # Introduction If you are unfamiliar to ztable, please read the ztable vignette: https://CRAN.R-project.org/package=ztable/vignettes/ztable.html ## Installation You can install R package "ztable" from CRAN. Current version is 0.1.8. ```{r,eval=FALSE} install.packages("ztable") ``` You can install the developmental version of ztable from github. Current github version is 0.1.9. ```{r,eval=FALSE} if(!require(devtools)) install.packages("devtools") devtools::install_github("cardiomoon/ztable") ``` ## Make table from a data.frame Package "ztable" make everything possible about table. Basically, An object of "ztable" made from a data.frame. The default output format of ztable is RStudio::viewer or web-browser format(type="viewer"). So if you want to use ztable in a "html" format, you should change the parameter ztable.type to "html". If you want to use ztable in latex format, you should change the parameter ztable.type to "latex". ```{r,results='asis'} library(ztable) library(magrittr) options(ztable.type="html") z=ztable(head(iris),caption="Table 1. Basic Table") z ``` ## Use background and font color You can change background color and font color with bg and color arguments in addRowColor(), addColColor() and addCellColor() functions. ```{r,results='asis'} ztable(head(iris),caption="Table 2. Table with desired background and font colors") %>% addRowColor(rows=1,bg="#C90000",color="white") %>% addCellColor(rows=3,cols=c(4,6), bg="cyan",color="red") ``` ## Conditional Formatting You can select rows with logical expression. You can select cols with column name. ```{r,results='asis'} ztable(head(iris),caption="Table 3. Conditinoal Formatting: Sepal.Width >= 3.5") %>% addRowColor(rows=1,bg="#C90000",color="white") %>% addCellColor(condition=Sepal.Width>=3.5,cols=Sepal.Width,color="red") ``` ```{r,results='asis'} ztable(head(mtcars),caption="Table 4. Cars with mpg > 21 ") %>% addCellColor(condition=mpg>21,cols=1:2,bg="cyan",color="red") ``` ## Use of color palette You can use color palettes from RColorBrewer packages. You can extract colors from palette by using palette2colors() function. ```{r} require(RColorBrewer) reds=palette2colors("Reds") reds ``` You can use the extracted colors to your ztable. ```{r,results='asis'} ztable(head(iris),caption="Table 5. Use of color palette") %>% addColColor(bg=reds) ztable(head(mtcars),caption="Table 6. Use of color palette(2)") %>% addRowColor(bg=palette2colors("Set3")) ``` ## Make a flextable from a ztable You can use ztable for html and latex output. But it is impossible to use ztable in `Microsoft Word` or `Microsoft Powerpoint` output directly. The `officer` package by David Gohel makes it possible to access and manipulate `Microsoft Word` or `Microsoft Powerpoint` document. You can insert a flextable object office documents with officer package. ```{r} require(officer) require(flextable) ft=regulartable(head(iris)) ft ``` You can make a 'Microsoft Word' document with this flextable. ```{r,eval=FALSE} read_docx() %>% body_add_flextable(ft) %>% print(target = "flextable.docx") ``` You can convert an object of class ztable to a flextable object. ```{r,results='asis'} cgroup=c("Sepal","Petal","Species") n.cgroup=c(2,2,1) z <- ztable(head(iris),caption="Table 9. Use of column groups") %>% addcgroup(cgroup=cgroup,n.cgroup=n.cgroup,color=c("red","green","blue")) %>% spanRow(col=4,from=2,to=3,bg="cyan") %>% spanCol(row=5,from=2,to=3,bg="cyan",color="blue") z ztable2flextable(z) ``` ```{r,results='asis'} fit <- lm(mpg ~ cyl + disp + wt + drat + am, data=mtcars) z=ztable(fit,caption="Table 10. Results of Multiple Regression Analysis ") z ztable2flextable(z) ``` You can change the color of rows in which p value is below the desired level(default value is 0.05). ```{r,results='asis'} z1=z %>% addSigColor z1 ztable2flextable(z1) %>% autofit() ``` You can change the significant level and background and font color. ```{r,results='asis'} z2= z %>% addSigColor(level=0.01,bg="yellow",color="red") z2 ztable2flextable(z2) ``` For more options of flextable, please read the flextable vignette at https://davidgohel.github.io/flextable/index.html.
/scratch/gouwar.j/cran-all/cranData/ztable/vignettes/ztable_update.Rmd
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 do_dztpln <- function(x, mu, sig) { .Call(`_ztpln_do_dztpln`, x, mu, sig) } do_dztpln2 <- function(x, mu, sig) { .Call(`_ztpln_do_dztpln2`, x, mu, sig) } do_dztplnm <- function(x, mu, sigma, theta) { .Call(`_ztpln_do_dztplnm`, x, mu, sigma, theta) } do_dztplnm2 <- function(x, mu, sigma, theta) { .Call(`_ztpln_do_dztplnm2`, x, mu, sigma, theta) } do_rztpln <- function(mu, sig) { .Call(`_ztpln_do_rztpln`, mu, sig) } do_rpln <- function(mu, sig) { .Call(`_ztpln_do_rpln`, mu, sig) } do_vec_rztpln2 <- function(n, mu, sig) { .Call(`_ztpln_do_vec_rztpln2`, n, mu, sig) } do_vec2_rztpln2 <- function(n, mu, sig) { .Call(`_ztpln_do_vec2_rztpln2`, n, mu, sig) } do_vec_rztpln1 <- function(n, mu, sig) { .Call(`_ztpln_do_vec_rztpln1`, n, mu, sig) } do_vec2_rztpln1 <- function(n, mu, sig) { .Call(`_ztpln_do_vec2_rztpln1`, n, mu, sig) }
/scratch/gouwar.j/cran-all/cranData/ztpln/R/RcppExports.R
#' The zero-truncated compund poisson-lognormal distributions #' #' Density function and random generation for Zero-Trauncated Poisson Lognormal #' distribution with parameters `mu` and sd `sig`. #' #' A compound Poisson-lognormal distribution is a Poisson probability #' distribution where its parameter \eqn{\lambda} is a random variable with #' lognormal distribution, that is to say \eqn{log\lambda} are normally #' distributed with mean \eqn{\mu} and variance \eqn{\sigma^2} (Bulmer 1974). #' The zero-truncated Poisson-lognormal distribution can be derived from a #' zero-truncated Poisson distribution. #' #' Type 1 ZTPLN truncates zero based on Poisson-lognormal distribution and #' type 2 ZTPLN truncates zero based on zero-truncated Poisson distribution. #' For mathematical details, please see `vignette("ztpln")` #' #' @param n number of random values to return. #' @param x vector of (non-negative integer) quantiles. #' @param mu mean of lognormal distribution. #' @param sig standard deviation of lognormal distribution. #' @param log logical; if TRUE, probabilities p are given as log(p). #' @param type1 logical; if TRUE, Use type 1 ztpln else use type 2. #' @return dztpln gives the (log) density and rztpln generates #' random variates. #' @references Bulmer, M. G. 1974. On Fitting the Poisson Lognormal Distribution to Species-Abundance Data. Biometrics 30:101-110. #' #' @seealso \code{\link{dztplnm}} #' #' @examples #' rztpln(n = 10, mu = 0, sig = 1, type1 = TRUE) #' rztpln(n = 10, mu = 6, sig = 4, type1 = TRUE) #' dztpln(x = 1:5, mu = 1, sig = 2) #' @export dztpln <- function(x, mu, sig, log = FALSE, type1 = TRUE) { if (length(mu) > 1 | length(sig) > 1) stop("Vectorization of parameters not implemented") if (sig < 0) stop("sig needs to be > 0") if (any(!DistributionUtils::is.wholenumber(x))) warning("non integer values in x") if (min(x) <= 0) warning("zero in x") x <- x[x > 0] if (type1) { lik <- do_dztpln(x, mu, sig) } else lik <- do_dztpln2(x, mu, sig) if (log) return(log(lik)) else return(lik) } #' @rdname dztpln #' @export rztpln <- function(n, mu, sig, type1 = TRUE) { if (length(mu) > 1 | length(sig) > 1) stop("Vectorization of parameters not implemented") if (sig < 0) stop("sig needs to be > 0") if (sig > 15) stop("standard deviation > 15 in log-scale is too large") if (type1) do_vec_rztpln1(n, mu, sig) else do_vec_rztpln2(n, mu, sig) }
/scratch/gouwar.j/cran-all/cranData/ztpln/R/dztpln.r
#' The zero-truncated compund poisson-lognormal distributions mixture #' #' Density function and random generation for Zero-Truncated #' Poisson Lognormal distribution with parameters `mu`, `sig`, and `theta`. #' #' Type 1 ZTPLN truncates zero based on Poisson-lognormal distribution and #' type 2 ZTPLN truncates zero based on zero-truncated Poisson distribution. #' For mathematical details, please see `vignette("ztpln")` #' #' @param n number of random values to return. #' @param mu vector of mean of lognormal distribution in sample. #' @param sig vector standard deviation of lognormal distribution in sample. #' @param theta vector of mixture weights #' @param x vector of (non-negative integer) quantiles. #' @param log logical; if TRUE, probabilities p are given as log(p). #' @param type1 logical; if TRUE, Use type 1 ztpln else use type 2. #' @return dztplnm gives the (log) density and rztplnm generates #' random variates. #' function, qpois gives the quantile function, and rpois generates random #' deviates. #' @seealso \code{\link{dztpln}} #' @examples #' rztplnm(n = 100, mu = c(0, 5), sig = c(1, 2), theta = c(0.2, 0.8)) #' dztplnm(x = 1:100, mu = c(0, 5), sig = c(1, 2), theta = c(0.2, 0.8)) #' dztplnm(x = 1:100, mu = c(0, 5), sig = c(1, 2), theta = c(0.2, 0.8), type1 = FALSE) #' @export dztplnm <- function(x, mu, sig, theta, log = FALSE, type1 = TRUE) { if (length(mu) != length(sig) | length(mu) != length(theta) | length(sig) != length(theta)) { stop("The length of vectors of mean, variance and mixture weight need to be same.") } if (sum(theta) != 1) warning("Sum of the mixture weight should be 1.") theta <- theta / sum(theta) if (type1) { lik <- do_dztplnm(x, mu, sig, theta) } else lik <- do_dztplnm2(x, mu, sig, theta) if (log) return(log(lik)) else return(lik) } #' @rdname dztplnm #' @export rztplnm <- function(n, mu, sig, theta, type1 = TRUE) { # theta: mixture weight for the first compoment if (length(mu) != length(sig) | length(mu) != length(theta) | length(sig) != length(theta)) { stop("The length of vectors of mean, variance and mixture weight need to be same.") } if (sum(theta) != 1) warning("Sum of the mixture weight should be 1.") z <- rmultinom(n, 1, theta) z2 <- as.numeric(z * seq(1, length(mu))) z3 <- z2[z2 > 0] if (type1) do_vec2_rztpln1(n, mu[z3], sig[z3]) else do_vec2_rztpln2(n, mu[z3], sig[z3]) }
/scratch/gouwar.j/cran-all/cranData/ztpln/R/dztplnm.r
#' The zero-truncated compund poisson-lognormal distributions and their #' mixtures #' #' Functions for obtaining the density, random deviates and maximum likelihood #' estimates of the zero-truncated Poisson lognormal distributions and their #' mixtures. #' #' @author Masatoshi Katabuchi <mattocci27@gmail.com> #' #' @references Bulmer, M. G. 1974. On Fitting the Poisson Lognormal Distribution to Species-Abundance Data. Biometrics 30:101-110. #' @references Inouye, D., E. Yang, G. Allen, and P. Ravikumar. 2017. A Review of Multivariate Distributions for Count Data Derived from the Poisson Distribution. Wiley interdisciplinary reviews. Computational statistics 9. #' @references Raqab, M. Z., D. Kundu, and F. A. Al-Awadhi. 2019. Compound zero-truncated Poisson normal distribution and its applications. Communications in Statistics - Theory and Methods:1–21. #' #' @keywords internal "_PACKAGE" #' @import Rcpp #' @import stats #' @importFrom DistributionUtils is.wholenumber #' @importFrom mixtools normalmixEM #' @useDynLib ztpln, .registration=TRUE NULL
/scratch/gouwar.j/cran-all/cranData/ztpln/R/ztpln.r
#' MLE for the Zero-truncated Poisson Lognormal distribution #' #' `ztplnMLE` fits the Zero-truncated Poisson lognormal distribution to data and #' estimates parameters mean `mu` and standard deviation `sig` in the lognormal #' distribution #' #' The function searches the maximum likelihood estimates of mean `mu` and #' standard deviation `sig` using the optimization procedures in #' \code{\link{nlminb}}. #' #' @param n a integer vector of counts #' @param lower_mu,upper_mu numeric values of lower and upper bounds for mean of #' the variables's natrual logarithm. #' @param lower_sig,upper_sig numeric values of lower and upper bounds for #' standard deviatoin of the variables's natrual logarithm #' @param type1 logical; if TRUE, Use type 1 ztpln else use type 2. #' @return \item{convergence}{An integer code. 0 indicates successful #' convergence.} #' @return \item{iterations}{Number of iterations performed.} #' @return \item{message}{A character string giving any additional information #' returned by the optimizer, or NULL. For details, see PORT documentation.} #' @return \item{evaluation}{Number of objective function and gradient function #' evaluations} #' @return \item{mu}{Maximum likelihood estimates of mu} #' @return \item{sig}{Maximum likelihood estimates of sig} #' @return \item{loglik}{loglikelihood} #' @examples #' y <- rztpln(100, 3, 2) #' ztplnMLE(y) #' @export ztplnMLE <- function(n, lower_mu = 0, upper_mu = log(max(n)), lower_sig = 0.001, upper_sig = 10, type1 = TRUE) { n <- n[n > 0] # set initial values using medians and sd for fast convergence params <- c(log(median(n)), sd(log(n))) loglik <- function(params, n) { mu <- params[1] sig <- params[2] if (type1) { lik <- do_dztpln(n, mu, sig) } else lik <- do_dztpln2(n, mu, sig) return(-sum(log(lik), na.rm = TRUE)) } # faster than Nelder-Mead and BFGS in optim fit <- try(nlminb(params, # initial parameters loglik, # function to be minimized (i.e., -logLike) gradient = NULL, lower = c(lower_mu, lower_sig), upper = c(upper_mu, upper_sig), n = n, TRUE)) fit$mu <- fit$par[1] fit$sig <- fit$par[2] fit$par <- NULL fit$loglik <- -fit$objective fit$objective <- NULL return(fit) }
/scratch/gouwar.j/cran-all/cranData/ztpln/R/ztplnMLE.r
#' MLE for the Zero-truncated Poisson Lognormal mixture distribtuion #' #' `ztplnmMLE` fits the Zero-truncated Poisson lognormal mixture distribution #' to data and estimates parameters mean `mu`, standard deviation `sig` and #' mixture weight `theta` in the lognormal distribution. #' #' The function searches the maximum likelihood estimators of mean vector `mu`, #' standard deviation vector `sig` and mixture weight vector `theta` using the #' optimization procedures in \code{\link{nlminb}}. #' #' @param n a vector of counts #' @param K number of components #' @param lower_mu,upper_mu numeric values of lower and upper bounds for mean of #' the variables's natural logarithm. #' @param lower_sig,upper_sig numeric values of lower and upper bounds for #' standard deviation of the variables's natural logarithm #' @param lower_theta,upper_theta numeric values of lower and upper bounds for #' mixture weights. #' @param type1 logical; if TRUE, Use type 1 ztpln else use type 2. #' @param message mean of lognormal distribution in sample 3. #' @return \item{convergence}{An integer code. 0 indicates successful #' convergence.} #' @return \item{iterations}{Number of iterations performed.} #' @return \item{message}{A character string giving any additional information #' returned by the optimizer, or NULL. For details, see PORT documentation.} #' @return \item{evaluation}{Number of objective function and gradient function #' evaluations} #' @return \item{mu}{Maximum likelihood estimates of mu} #' @return \item{sig}{Maximum likelihood estimates of sig} #' @return \item{theta}{Maximum likelihood estimates of theta} #' @return \item{loglik}{loglikelihood} #' @examples #' y <- rztplnm(100, c(1, 10), c(2, 1), c(0.2, 0.8)) #' ztplnmMLE(y) #' @export ztplnmMLE <- function(n, K = 2, lower_mu = rep(0, K), upper_mu = rep(log(max(n)), K), lower_sig = rep(0.001, K), upper_sig = rep(10, K), lower_theta = rep(0.001, K), upper_theta = rep(0.999, K), type1 = TRUE, message = FALSE) { if (K == 1) {warning("`ztplnMLE` is faster for K = 1")} n <- n[n > 0] max_abund <- log(max(n)) if (message) { sink("/dev/null") # now suppresses fit0 <- try(mixtools::normalmixEM(log(n), k = K, maxrestart = 20)) sink() } else { fit0 <- try(mixtools::normalmixEM(log(n), k = K, maxrestart = 20)) } # set initial values using normalmixEM for better convergence if (class(fit0) == "try-error") { params <- c(rep(1, 2 * K), rep(1 / K, K)) } else { params <- c(fit0$mu, fit0$sig, fit0$lambda) } loglik <- function(params, n) { mu <- params[1:K] sig <- params[(K + 1):(2 * K)] theta <- params[(2 * K + 1):(3 * K)] theta <- theta / sum(theta) if (type1) { lik <- do_dztplnm(n, mu, sig, theta) } else lik <- do_dztplnm2(n, mu, sig, theta) return(-sum(log(lik), na.rm = TRUE)) } fit <- try(nlminb(start = params, # inital parameters loglik, # function to be minimized (i.e., -logLike) gradient = NULL, lower = c(lower_mu, lower_sig, lower_theta), upper = c(upper_mu, upper_sig, upper_theta), n = n, TRUE)) fit$mu <- fit$par[1:K] fit$sig <- fit$par[(K + 1):(2 * K)] theta <- fit$par[(2 * K + 1):(3 * K)] fit$theta <- theta / sum(theta) fit$par <- NULL fit$loglik <- -fit$objective fit$objective <- NULL return(fit) }
/scratch/gouwar.j/cran-all/cranData/ztpln/R/ztplnmMLE.r
## ---- echo = FALSE, message = FALSE------------------------------------------- knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 7, fig.align = "center") #options(tibble.print_min = 4L, tibble.print_max = 4L) library(ztpln) set.seed(123) ## ---- eval = T---------------------------------------------------------------- library(dplyr) library(tidyr) library(ggplot2) set.seed(123) rztpln(n = 10, mu = 0, sig = 1) rztpln(n = 10, mu = 6, sig = 4) ## ---- eval = T---------------------------------------------------------------- rztplnm(n = 100, mu = c(0, 4), sig = c(0.5, 0.5), theta = c(0.2, 0.8)) %>% log %>% hist(main = "", xlab = "k") ## ---- eval = T---------------------------------------------------------------- y <- rztpln(n = 100, mu = 2, sig = 5, type1 = TRUE) sum(dztpln(y, mu = 2, sig = 5, log = TRUE, type1 = TRUE)) sum(dztpln(y, mu = 2, sig = 5, log = TRUE, type1 = FALSE)) ## ---- eval = T---------------------------------------------------------------- y2 <- rztpln(n = 100, mu = 2, sig = 5, type1 = FALSE) sum(dztpln(y2, mu = 2, sig = 5, log = TRUE, type1 = TRUE)) sum(dztpln(y2, mu = 2, sig = 5, log = TRUE, type1 = FALSE)) ## ----------------------------------------------------------------------------- k1 <- 1 k <- 1000 dat <- tibble(type1 = dztpln(k1:k, mu = 1, sig = 2, type1 = TRUE), type2 = dztpln(k1:k, mu = 1, sig = 2, type1 = FALSE), x = k1:k) %>% pivot_longer(-x, names_to = "type", values_to = "y") ggplot(dat %>% dplyr::filter(x <= 10), aes(x = x, y = y, col = type)) + geom_point() + geom_line() + scale_y_log10() + xlab("k") + ylab("Likelihood") + theme_bw() ## ----------------------------------------------------------------------------- ggplot(dat, aes(x = x, y = y, col = type)) + geom_point() + geom_line() + scale_y_log10() + xlab("k") + ylab("Likelihood") + theme_bw()
/scratch/gouwar.j/cran-all/cranData/ztpln/inst/doc/ztpln.R
--- title: "Zero Truncated Poisson Lognormal Distribution" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Zero Truncated Poisson Lognormal Distribution} %\VignetteEngine{knitr::rmarkdown} #%\usepackage[utf8]{inputenc} --- ```{r, echo = FALSE, message = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 7, fig.align = "center") #options(tibble.print_min = 4L, tibble.print_max = 4L) library(ztpln) set.seed(123) ``` A compound Poisson-lognormal distribution (PLN) is a Poisson probability distribution where its parameter $\lambda$ is a random variable with lognormal distribution, that is to say $log \lambda$ are normally distributed with mean $\mu$ and variance $\sigma^2$ (Bulmer 1974). The density function is $$ \mathcal{PLN} (k ; \mu, \sigma) = \int_0^\infty {Pois}(k; \lambda) \times \mathcal{N}(log\lambda; \mu, \sigma) d\lambda \\ = \frac{1}{\sqrt{2\pi\sigma^2}k!}\int^\infty_0\lambda^{k}exp(-\lambda)exp(\frac{-(log\lambda-\mu)^2}{2\sigma^2})d\lambda, \; \text{where} \; k = 0, 1, 2, ... \; \;\;(1). $$ ## ZTPLN - type 1 The zero-truncated Poisson-lognormal distribution (ZTPLN) at least have two different forms. First, it can be derived from a Poisson-lognormal distribution, $$ \mathcal{PLN}_{zt}(k ; \mu, \sigma) = \frac{\mathcal{PLN}(k ; \mu, \sigma)}{1-\mathcal{PLN}(0 ; \mu, \sigma)}, \; \text{where} \; k = 1, 2, 3, ... \;\;(2). $$ Random samples from ZTPLN (eq 2.) requires the inverse cumulative distribution function of ZTPLN (eq 2.), $$ G_{zt}(x; \lambda) =\sum_{i=1}^k \mathcal{PLN}_{zt}(i ; \mu, \sigma) \;\;(3). $$ Random sampling using $G_{zt}^{-1}$ is not implemented at the moment. Instead, zero values will be discarded from random variates that are generated by the inverse cumulative distribution of PLN. ## ZTPLN - type 2 An alternative form of ZTPLN can be directly derived from a mixture of zero-truncated Poisson distribution and lognormal distribution, $$ \mathcal{PLN}_{zt2} (k ; \mu, \sigma) = \int_0^\infty \frac{{Pois}(k; \lambda)}{1 - Pois(0; \lambda)} \times \mathcal{N}(log\lambda; \mu, \sigma) d\lambda \\ = \frac{1}{\sqrt{2\pi\sigma^2}k!}\int^\infty_0 \frac{\lambda^{k}}{exp(\lambda) - 1}exp(\frac{-(log\lambda-\mu)^2}{2\sigma^2})d\lambda, \; \text{where} \; k = 1, 2, 3,... \; \;\;(4). $$ Random samples from ZTPLN (eq. 3) can be generated by inverse transform sampling with the cumulative distribution function of a zero-truncated Poisson distribution ($F_{zt}$), $$ F_{zt2}^{-1}(x; \lambda) = F^{-1}((1 - Pois(0; \lambda)) x + Pois(0; \lambda); \lambda) \\ = F^{-1}((1 - e^{-\lambda}) x + e^{-\lambda}; \lambda) \;\;\;\;(5) $$ where $F^{-1}_{zt2}$ and $F^{-1}$ are inverse cumulative distribution function for a zero-truncated Poisson distribution and a Poisson distribution, respectively. ## Mixture models A Poisson lognormal ($\mathcal{PLN}$) mixture model with *K* components for variables $\boldsymbol y = (y_1, \ldots, y_N)$ is parameterized by the mixture component weight vector $\boldsymbol \theta = (\theta_1, \ldots, \theta_K)$ such that $0 \le \theta_{k} \le 1$ and $\sum\theta_{k} = 1$, and the mean $\boldsymbol \mu = (\mu_1, \ldots, \mu_K)$ and standard deviation $\boldsymbol \sigma = (\sigma_1, \ldots, \sigma_K)$ of the variable's natural logarithm. The probability mass function ($p$) for a Poisson lognormal mixture is $$ p(\boldsymbol y; {\boldsymbol \mu}, {\boldsymbol \sigma}, {\boldsymbol \theta}) = \sum_{k=1}^{K}\theta_k \mathcal{PLN}(\boldsymbol{y} ; \mu_k, \sigma_k) \; \; (6). $$ Given that each mixture component is zero-truncated, the probability mass function for the zero-truncated Poisson lognormal mixture ($p_{zt}$) is $$ p_{zt}(\boldsymbol y; {\boldsymbol \mu}, {\boldsymbol \sigma}, {\boldsymbol \theta}) = \sum_{k=1}^{K}\theta_k \frac{\mathcal{PLN}(\boldsymbol{y} ; \mu_k, \sigma_k)} {1 - \mathcal{PLN}(0 ; \mu_k, \sigma_k)} \; \; (7) $$ for ZTPLN type 1, and $$ p_{zt2}(\boldsymbol y; {\boldsymbol \mu}, {\boldsymbol \sigma}, {\boldsymbol \theta}) = \sum_{k=1}^{K}\theta_k \mathcal{PLN}_{zt2}(\boldsymbol{y} ; \mu_k, \sigma_k) \; \; (8) $$ for ZTPLN type 2. ## Functions - `dztpln(x, mu, sig, log = FALSE, type1 = TRUE)`: gives the (log) density of a zero truncated poisson lognormal distribution - `rztpln(n, mu, sig, type1 = TRUE)`: random draw from a zero truncated poisson lognormal distribution - `dztplnm(x, mu, sig, theta, log = FALSE, type1 = TRUE)`: gives the (log) density of a zero truncated poisson lognormal distribution mixture. - `ztplnm(n, mu, sig, theta, type1 = TRUE)`: random draw from a zero truncated poisson lognormal distribution mixture. ## Examples ### Random variates We can generate ZTPLN random variates. ```{r, eval = T} library(dplyr) library(tidyr) library(ggplot2) set.seed(123) rztpln(n = 10, mu = 0, sig = 1) rztpln(n = 10, mu = 6, sig = 4) ``` We can also generate mixture of ZTPLN random variates. ```{r, eval = T} rztplnm(n = 100, mu = c(0, 4), sig = c(0.5, 0.5), theta = c(0.2, 0.8)) %>% log %>% hist(main = "", xlab = "k") ``` ### Maximum likelihood estimation Type 1 model (`dztpln(..., type1 = TRUE)`) fits better for type 1 random variates (`rztpln(..., type1 = TRUE)`). ```{r, eval = T} y <- rztpln(n = 100, mu = 2, sig = 5, type1 = TRUE) sum(dztpln(y, mu = 2, sig = 5, log = TRUE, type1 = TRUE)) sum(dztpln(y, mu = 2, sig = 5, log = TRUE, type1 = FALSE)) ``` Type 2 model (`dztpln(..., type1 = FALSE)`) fits better for type 2 random variates (`rztpln(..., type1 = FALSE)`). ```{r, eval = T} y2 <- rztpln(n = 100, mu = 2, sig = 5, type1 = FALSE) sum(dztpln(y2, mu = 2, sig = 5, log = TRUE, type1 = TRUE)) sum(dztpln(y2, mu = 2, sig = 5, log = TRUE, type1 = FALSE)) ``` ### Probability density plots Let’s consider a simple example where random variates follows the same parameters of type 1 and type 2 ZTPLN. We define two different sets of random variates, $\mathcal{PLN}_{zt}(k ;1, 2)$ and $\mathcal{PLN}_{zt2}(k ; 1, 2)$. In this example, when $k$ is small, type 2 ZTPLN shows greater likelihood. ```{r} k1 <- 1 k <- 1000 dat <- tibble(type1 = dztpln(k1:k, mu = 1, sig = 2, type1 = TRUE), type2 = dztpln(k1:k, mu = 1, sig = 2, type1 = FALSE), x = k1:k) %>% pivot_longer(-x, names_to = "type", values_to = "y") ggplot(dat %>% dplyr::filter(x <= 10), aes(x = x, y = y, col = type)) + geom_point() + geom_line() + scale_y_log10() + xlab("k") + ylab("Likelihood") + theme_bw() ``` When $k$ is large, type 1 ZTPLN shows greater likelihood. ```{r} ggplot(dat, aes(x = x, y = y, col = type)) + geom_point() + geom_line() + scale_y_log10() + xlab("k") + ylab("Likelihood") + theme_bw() ``` ## Reference Bulmer, M. G. 1974. On Fitting the Poisson Lognormal Distribution to Species-Abundance Data. Biometrics 30:101-110. Inouye, D., E. Yang, G. Allen, and P. Ravikumar. 2017. A Review of Multivariate Distributions for Count Data Derived from the Poisson Distribution. Wiley interdisciplinary reviews. Computational statistics 9:e1398.
/scratch/gouwar.j/cran-all/cranData/ztpln/inst/doc/ztpln.rmd
--- title: "Zero Truncated Poisson Lognormal Distribution" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Zero Truncated Poisson Lognormal Distribution} %\VignetteEngine{knitr::rmarkdown} #%\usepackage[utf8]{inputenc} --- ```{r, echo = FALSE, message = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 7, fig.align = "center") #options(tibble.print_min = 4L, tibble.print_max = 4L) library(ztpln) set.seed(123) ``` A compound Poisson-lognormal distribution (PLN) is a Poisson probability distribution where its parameter $\lambda$ is a random variable with lognormal distribution, that is to say $log \lambda$ are normally distributed with mean $\mu$ and variance $\sigma^2$ (Bulmer 1974). The density function is $$ \mathcal{PLN} (k ; \mu, \sigma) = \int_0^\infty {Pois}(k; \lambda) \times \mathcal{N}(log\lambda; \mu, \sigma) d\lambda \\ = \frac{1}{\sqrt{2\pi\sigma^2}k!}\int^\infty_0\lambda^{k}exp(-\lambda)exp(\frac{-(log\lambda-\mu)^2}{2\sigma^2})d\lambda, \; \text{where} \; k = 0, 1, 2, ... \; \;\;(1). $$ ## ZTPLN - type 1 The zero-truncated Poisson-lognormal distribution (ZTPLN) at least have two different forms. First, it can be derived from a Poisson-lognormal distribution, $$ \mathcal{PLN}_{zt}(k ; \mu, \sigma) = \frac{\mathcal{PLN}(k ; \mu, \sigma)}{1-\mathcal{PLN}(0 ; \mu, \sigma)}, \; \text{where} \; k = 1, 2, 3, ... \;\;(2). $$ Random samples from ZTPLN (eq 2.) requires the inverse cumulative distribution function of ZTPLN (eq 2.), $$ G_{zt}(x; \lambda) =\sum_{i=1}^k \mathcal{PLN}_{zt}(i ; \mu, \sigma) \;\;(3). $$ Random sampling using $G_{zt}^{-1}$ is not implemented at the moment. Instead, zero values will be discarded from random variates that are generated by the inverse cumulative distribution of PLN. ## ZTPLN - type 2 An alternative form of ZTPLN can be directly derived from a mixture of zero-truncated Poisson distribution and lognormal distribution, $$ \mathcal{PLN}_{zt2} (k ; \mu, \sigma) = \int_0^\infty \frac{{Pois}(k; \lambda)}{1 - Pois(0; \lambda)} \times \mathcal{N}(log\lambda; \mu, \sigma) d\lambda \\ = \frac{1}{\sqrt{2\pi\sigma^2}k!}\int^\infty_0 \frac{\lambda^{k}}{exp(\lambda) - 1}exp(\frac{-(log\lambda-\mu)^2}{2\sigma^2})d\lambda, \; \text{where} \; k = 1, 2, 3,... \; \;\;(4). $$ Random samples from ZTPLN (eq. 3) can be generated by inverse transform sampling with the cumulative distribution function of a zero-truncated Poisson distribution ($F_{zt}$), $$ F_{zt2}^{-1}(x; \lambda) = F^{-1}((1 - Pois(0; \lambda)) x + Pois(0; \lambda); \lambda) \\ = F^{-1}((1 - e^{-\lambda}) x + e^{-\lambda}; \lambda) \;\;\;\;(5) $$ where $F^{-1}_{zt2}$ and $F^{-1}$ are inverse cumulative distribution function for a zero-truncated Poisson distribution and a Poisson distribution, respectively. ## Mixture models A Poisson lognormal ($\mathcal{PLN}$) mixture model with *K* components for variables $\boldsymbol y = (y_1, \ldots, y_N)$ is parameterized by the mixture component weight vector $\boldsymbol \theta = (\theta_1, \ldots, \theta_K)$ such that $0 \le \theta_{k} \le 1$ and $\sum\theta_{k} = 1$, and the mean $\boldsymbol \mu = (\mu_1, \ldots, \mu_K)$ and standard deviation $\boldsymbol \sigma = (\sigma_1, \ldots, \sigma_K)$ of the variable's natural logarithm. The probability mass function ($p$) for a Poisson lognormal mixture is $$ p(\boldsymbol y; {\boldsymbol \mu}, {\boldsymbol \sigma}, {\boldsymbol \theta}) = \sum_{k=1}^{K}\theta_k \mathcal{PLN}(\boldsymbol{y} ; \mu_k, \sigma_k) \; \; (6). $$ Given that each mixture component is zero-truncated, the probability mass function for the zero-truncated Poisson lognormal mixture ($p_{zt}$) is $$ p_{zt}(\boldsymbol y; {\boldsymbol \mu}, {\boldsymbol \sigma}, {\boldsymbol \theta}) = \sum_{k=1}^{K}\theta_k \frac{\mathcal{PLN}(\boldsymbol{y} ; \mu_k, \sigma_k)} {1 - \mathcal{PLN}(0 ; \mu_k, \sigma_k)} \; \; (7) $$ for ZTPLN type 1, and $$ p_{zt2}(\boldsymbol y; {\boldsymbol \mu}, {\boldsymbol \sigma}, {\boldsymbol \theta}) = \sum_{k=1}^{K}\theta_k \mathcal{PLN}_{zt2}(\boldsymbol{y} ; \mu_k, \sigma_k) \; \; (8) $$ for ZTPLN type 2. ## Functions - `dztpln(x, mu, sig, log = FALSE, type1 = TRUE)`: gives the (log) density of a zero truncated poisson lognormal distribution - `rztpln(n, mu, sig, type1 = TRUE)`: random draw from a zero truncated poisson lognormal distribution - `dztplnm(x, mu, sig, theta, log = FALSE, type1 = TRUE)`: gives the (log) density of a zero truncated poisson lognormal distribution mixture. - `ztplnm(n, mu, sig, theta, type1 = TRUE)`: random draw from a zero truncated poisson lognormal distribution mixture. ## Examples ### Random variates We can generate ZTPLN random variates. ```{r, eval = T} library(dplyr) library(tidyr) library(ggplot2) set.seed(123) rztpln(n = 10, mu = 0, sig = 1) rztpln(n = 10, mu = 6, sig = 4) ``` We can also generate mixture of ZTPLN random variates. ```{r, eval = T} rztplnm(n = 100, mu = c(0, 4), sig = c(0.5, 0.5), theta = c(0.2, 0.8)) %>% log %>% hist(main = "", xlab = "k") ``` ### Maximum likelihood estimation Type 1 model (`dztpln(..., type1 = TRUE)`) fits better for type 1 random variates (`rztpln(..., type1 = TRUE)`). ```{r, eval = T} y <- rztpln(n = 100, mu = 2, sig = 5, type1 = TRUE) sum(dztpln(y, mu = 2, sig = 5, log = TRUE, type1 = TRUE)) sum(dztpln(y, mu = 2, sig = 5, log = TRUE, type1 = FALSE)) ``` Type 2 model (`dztpln(..., type1 = FALSE)`) fits better for type 2 random variates (`rztpln(..., type1 = FALSE)`). ```{r, eval = T} y2 <- rztpln(n = 100, mu = 2, sig = 5, type1 = FALSE) sum(dztpln(y2, mu = 2, sig = 5, log = TRUE, type1 = TRUE)) sum(dztpln(y2, mu = 2, sig = 5, log = TRUE, type1 = FALSE)) ``` ### Probability density plots Let’s consider a simple example where random variates follows the same parameters of type 1 and type 2 ZTPLN. We define two different sets of random variates, $\mathcal{PLN}_{zt}(k ;1, 2)$ and $\mathcal{PLN}_{zt2}(k ; 1, 2)$. In this example, when $k$ is small, type 2 ZTPLN shows greater likelihood. ```{r} k1 <- 1 k <- 1000 dat <- tibble(type1 = dztpln(k1:k, mu = 1, sig = 2, type1 = TRUE), type2 = dztpln(k1:k, mu = 1, sig = 2, type1 = FALSE), x = k1:k) %>% pivot_longer(-x, names_to = "type", values_to = "y") ggplot(dat %>% dplyr::filter(x <= 10), aes(x = x, y = y, col = type)) + geom_point() + geom_line() + scale_y_log10() + xlab("k") + ylab("Likelihood") + theme_bw() ``` When $k$ is large, type 1 ZTPLN shows greater likelihood. ```{r} ggplot(dat, aes(x = x, y = y, col = type)) + geom_point() + geom_line() + scale_y_log10() + xlab("k") + ylab("Likelihood") + theme_bw() ``` ## Reference Bulmer, M. G. 1974. On Fitting the Poisson Lognormal Distribution to Species-Abundance Data. Biometrics 30:101-110. Inouye, D., E. Yang, G. Allen, and P. Ravikumar. 2017. A Review of Multivariate Distributions for Count Data Derived from the Poisson Distribution. Wiley interdisciplinary reviews. Computational statistics 9:e1398.
/scratch/gouwar.j/cran-all/cranData/ztpln/vignettes/ztpln.rmd
# -*- coding: utf-8 -*- #' @encoding UTF-8 #' #' @title ztype #' @description How fast can you type R functions on your keyboard? Find out by running a 'zty.pe' game: export R functions as instructions to type to destroy opponents vessels. #' @docType package #' @name ztype #' @examples #' #'\dontrun{ #' require(ztype) #' require(magrittr) #' ztype() # dplyr, ggplot2 and lubridate #' c("lubridate") %>% ztype() #'} #' #' #' #' NULL
/scratch/gouwar.j/cran-all/cranData/ztype/R/doc_package.R
is_installed <- function(package) { suppressWarnings(suppressMessages(isTRUE(require( package, character.only = TRUE )))) } assertthat::on_failure(is_installed) <- function(call, env) { paste0(deparse(call$package), " is not installed") } #' @title gen_set_of_words #' @description extracts all function names from a given list of packages #' @param packages character vector. package(s) to parse and extract function names from #' @export #' @importFrom stringr str_length #' @import assertthat #' @return a character vector #' @examples #' \dontrun{ #' require(ztype) #' require(magrittr) #' c("dplyr","ggplot2","lubridate") %>% gen_set_of_words() #' } gen_set_of_words <- function(packages) { sapply(packages, function(prout) { eval(parse( text = paste0("assertthat::assert_that(is_installed('", prout, "'))") )) }) set_of_words <- unlist(sapply(packages, function(.) { ls(paste0("package:", .)) })) set_of_words[order(str_length(set_of_words))] } #' @title level #' @description generates a collection of words to build a ZType game level #' @param set_of_words a sorted vector of the collection of words to use #' @param quantity an integer the number of words to pick in #' @param difficulty an integer reflecting the level's difficulty #' @export #' @importFrom stats dpois #' @examples #' require(ztype) #' require(magrittr) #' c("dplyr","ggplot2","lubridate") %>% gen_set_of_words() %>% level(10,50) level <- function(set_of_words, quantity, difficulty) { paste(sample( set_of_words, size = quantity, prob = dpois(seq_along(set_of_words), difficulty), replace = TRUE ), collapse = " ") } #' @title gen_set_of_levels #' @description generate a set of levels with increasing difficulty #' @param set_of_words a sorted vector of the collection of words to use #' @param nb the number of levels to generate #' @export #' @importFrom stats dpois #' @examples #' require(ztype) #' require(magrittr) #' c("dplyr","ggplot2","lubridate") %>% gen_set_of_words() %>% #' gen_set_of_levels(10) %>% cat() gen_set_of_levels <- function(set_of_words, nb = 25) { p <- mapply( FUN = level, quantity = 3:(nb + 2), difficulty = seq( from = 1, to = length(set_of_words), length.out = nb ), set_of_words = list(set_of_words) ) paste(p, collapse = "\n\n\n") } #' @title gen_game #' @description generate a ZType game by puhsing a set of levels on the website. #' @param set_of_levels the set of levels to use #' @param open booleen open browser #' @export #' @importFrom rvest html_session html_form set_values submit_form #' @importFrom magrittr %>% #' @importFrom utils browseURL #' @examples #' \dontrun{ #' require(ztype) #' require(magrittr) #' c("dplyr","ggplot2","lubridate") %>% gen_set_of_words() %>% #' gen_set_of_levels(10) %>% #' gen_game() %>% browseURL() #' } #' gen_game <- function(set_of_levels, open = FALSE) { pgsession <- html_session("http://zty.pe/?load") pgform <- html_form(pgsession)[[1]] fake_submit_button <- list( name = NULL, type = "submit", value = NULL, checked = NULL, disabled = NULL, readonly = NULL, required = FALSE ) attr(fake_submit_button, "class") <- "input" pgform[["fields"]][["submit"]] <- fake_submit_button filled_form <- set_values(pgform, `text` = set_of_levels) submit_form(pgsession, filled_form) -> j j$response %>% unclass() %>% .$url -> out if (open) { message("opening : ", out) browseURL(out) } invisible(out) } #' @title ztype #' @description launch a ZType game using function names of R packages #' @param packages a vector containing installed packages from which extract function names #' @param nb number of levels to design in the ZType game #' @export #' @importFrom magrittr %>% #' @examples #' \dontrun{ #' require(ztype) #' require(magrittr) #' ztype()# dplyr, ggplot2 and lubridate #' c("lubridate") %>% ztype() #' } #' ztype <- function(packages = c("dplyr", "ggplot2", "lubridate"), nb = 25) { packages %>% gen_set_of_words() %>% gen_set_of_levels(nb) %>% gen_game(open = TRUE) }
/scratch/gouwar.j/cran-all/cranData/ztype/R/fonction.R
#' @importFrom utils packageDescription .onAttach <- function(libname, pkgname) { # Runs when attached to search() path such as by library() or require() if (interactive()) { pdesc <- packageDescription(pkgname) packageStartupMessage('') packageStartupMessage(pdesc$Package, " ", pdesc$Version, " by Vincent Guyader") packageStartupMessage("-> For help type help('ztype')") packageStartupMessage('') } } # enleve les faux positifs du check globalVariables(c(".")) # faudra mettre les autres pour que le check ne s'enflamme pas trop a cause des NSE
/scratch/gouwar.j/cran-all/cranData/ztype/R/onAttach.R
require(Kendall) zyp.sen <- function(formula, dataframe) { zyp.slopediff <- function(i, xx, yy, n) (yy[1:(n-i)] - yy[(i+1):n]) / (xx[1:(n-i)] - xx[(i+1):n]) if (missing(dataframe)) dataframe <- environment(formula) term <- as.character(attr(terms(formula), "variables")[-1]) x <- dataframe[[term[2]]] y <- dataframe[[term[1]]] n <- length(x) if (length(term) > 2) { stop("Only linear models are accepted") } slopes <- unlist(lapply(1:(n-1), zyp.slopediff, x, y, n)) sni <- which(is.finite(slopes)) slope <- median(slopes[sni]) intercepts <- y - slope * x intercept <- median(intercepts) res <- list(coefficients=c(intercept, slope), slopes = slopes, intercepts = intercepts, rank=2, residuals=(y - slope * x + intercept), x=x, y=y) names(res$coefficients) = c("Intercept", term[2]) class(res) = c("zyp", "lm") return(res) } confint.zyp <- function (object, parm, level = 0.95, ...) { res <- rep(0, 4) dim(res) <- c(2, 2) slopes <- sort(object$slopes) intercepts <- sort(object$intercepts) uquantile <- 1 - (1 - level) / 2 zstat <- qnorm(uquantile) k <- Kendall(object$x, object$y) c.alpha <- sqrt(k$varS) * zstat n.prime <- length(slopes) isect.sd <- sqrt(var(intercepts)) isect.mean <- mean(intercepts) idx <- c(round((n.prime - c.alpha) / 2), round((n.prime + c.alpha) / 2)) rownames(res) <- names(object$coefficients) colnames(res) <- as.character(c((1 - level)/2, 1 - (1 - level)/2)) res[2, ] <- slopes[idx] res[1, ] <- isect.mean + c(-isect.sd * zstat, isect.sd * zstat) return(res) } zyp.zhang <- function(y, x=1:length(y), conf.intervals=TRUE, preserve.range.for.sig.test=FALSE) { data <- as.numeric(as.vector(y)) if(is.logical(x)) stop("x cannot be of type 'logical' (perhaps you meant to specify conf.intervals?)") n <- length(data) t <- x ret <- c(lbound = NA, trend = NA, trendp = NA, ubound = NA, tau = NA, sig = NA, nruns = NA, autocor = NA, valid_frac = NA, linear = NA, intercept = NA, lbound_intercept = NA, ubound_intercept = NA) # Prewhiten the original series c <- acf(data,lag.max=1,plot=FALSE,na.action=na.pass)$acf[2] # Throw out data that is insufficient to compute the autocorrelation function if(is.na(c)) { return(ret) } if(c < 0.05) { y <- data yt <- t } else { y <- ifelse(rep(preserve.range.for.sig.test, n - 1), (data[2:n] - c * data[1:(n-1)]) / (1 - c), data[2:n] - c * data[1:(n-1)]) yt <- t[1:(n-1)] } dmap <- which(!is.na(y)) ynm <- as.numeric(y[dmap]) ytnm <- as.numeric(yt[dmap]) # Throw out crappy data if(length(dmap) <= 3 | length(which(ynm != 0)) < 3 | length(dmap) / n < 0.1) { return(ret) } # Calculate Slope sen <- zyp.sen(ynm~ytnm) trend <- sen$coefficients[2] k <- 1 c0 <- c if(c >= 0.05) { # Use repeated pre-whitening if there is autocorrelation trend0 <- trend while(k<500) { x <- data[1:n] - trend * t c <- acf(x,lag.max=1,plot=FALSE,na.action=na.pass)$acf[2] if(c < 0.05 && abs(c-c0) <= 0.0001) { break; } y <- (data[2:n] - c * data[1:(n-1)]) / (1 - c) dmap <- which(!is.na(y)) ynm <- as.numeric(y[dmap]) ytnm <- as.numeric(yt[dmap]) sen <- zyp.sen(ynm~ytnm) trend <- sen$coefficients[2] # median(na.omit(sen$slopes)) k <- k+1 tpdiff <- abs((trend - trend0) / trend) if(!is.na(tpdiff) && tpdiff <= 0.001 && abs(c-c0)<=0.0001){ break } trend0 <- trend c0 <- c } } Kend <- Kendall(ytnm,ynm) tau <- Kend[1] Bsig <- Kend[2] if(conf.intervals) { ci <- confint(sen) } else { ci <- matrix(rep(NA, 4), nrow=2, ncol=2) } ret <- c(lbound = as.numeric(ci[2, 1]), trend=as.numeric(trend), trendp=(as.numeric(trend) * n), ubound = as.numeric(ci[2, 2]), tau=as.numeric(tau), sig=as.numeric(Bsig), nruns=as.numeric(k), autocor=as.numeric(c0), valid_frac=as.numeric(length(dmap)/length(y)), linear=as.numeric(lm(data~t)$coefficients[2]), intercept=as.numeric(sen$coefficients[1]), lbound_intercept=as.numeric(ci[1,1]), ubound_intercept=as.numeric(ci[1,2])) return(ret) } zyp.yuepilon <- function(y, x=1:length(y), conf.intervals=TRUE, preserve.range.for.sig.test=FALSE) { dat <- as.numeric(as.vector(y)) if(is.logical(x)) stop("x cannot be of type 'logical' (perhaps you meant to specify conf.intervals?)") n <- length(dat) t <- x t.prime <- t[1:(n-1)] y <- dat ret <- c(lbound = NA, trend=NA, trendp=NA, ubound = NA, tau=NA, sig=NA, nruns=NA, autocor=NA, valid_frac=NA, linear=NA, intercept=NA, lbound_intercept = NA, ubound_intercept = NA) dmap <- which(!is.na(y)) ynm <- as.numeric(y[dmap]) tnm <- as.numeric(t[dmap]) # Throw out crappy data if(length(dmap) <= 3 | length(which(ynm != 0)) < 3 | length(dmap) / n < 0.1) { return(ret) } # Calculate Slope sen <- zyp.sen(ynm~tnm) trend <- sen$coefficients[2] # FIXME: ADD CHECK HERE FOR SMALL TREND # Remove trend xt.prime <- dat[1:n] - trend * t # Calculate AR(1) ac <- acf(xt.prime, lag.max=1, plot=FALSE, na.action=na.pass)$acf[2] # Throw out data that is insufficient to compute the autocorrelation function if(is.na(ac)) { return(ret) } yt.prime <- ifelse(rep(preserve.range.for.sig.test, n - 1), (xt.prime[2:n] - ac * xt.prime[1:(n-1)]) / (1 - ac), xt.prime[2:n] - ac * xt.prime[1:(n-1)]) ## Add the trend back into the residual yt <- yt.prime[1:(n-1)] + trend * t.prime dmap.prime <- which(!is.na(yt)) ytnm <- as.numeric(yt[dmap.prime]) t.prime <- t.prime[dmap.prime] # Calculate the Mann-Kendall test for significance on the blended series Kend <- Kendall(t.prime,ytnm) tau <- Kend[1] Bsig <- Kend[2] # Calculate slope on pre-whitened data sen <- zyp.sen(ytnm ~ t.prime) trend <- sen$coefficients[2] if(conf.intervals) { ci <- confint(sen) } else { ci <- matrix(rep(NA, 4), nrow=2, ncol=2) } ret <- c(lbound = as.numeric(ci[2, 1]), trend=as.numeric(trend), trendp=as.numeric(trend) * n, ubound = as.numeric(ci[2, 2]), tau=as.numeric(tau), sig=as.numeric(Bsig), nruns=1, autocor=as.numeric(ac), valid_frac=as.numeric(length(dmap)/length(y)), linear=as.numeric(lm(dat~t)$coefficients[2]), intercept=as.numeric(sen$coefficients[1]), lbound_intercept=as.numeric(ci[1,1]), ubound_intercept=as.numeric(ci[1,2])) return(ret) } # Applies either a Yue Pilon or Zhang trend calculation to a vector of data zyp.trend.vector <- function(y, x=1:length(y), method=c("zhang", "yuepilon"), conf.intervals=TRUE, preserve.range.for.sig.test=FALSE) { if(is.character(x)) stop("x cannot be of type character (perhaps you meant to specify method?)") switch(match.arg(method), zhang = zyp.zhang(y, x, conf.intervals, preserve.range.for.sig.test), yuepilon = zyp.yuepilon(y, x, conf.intervals, preserve.range.for.sig.test) ) } # Applies either a Yue Pilon or Zhang trend calculation to a data frame where there is one station per line with no metadata (and each year/month is a column of data) zyp.trend.dataframe <- function(indat, metadata.cols, method=c("zhang", "yuepilon"), conf.intervals=TRUE, preserve.range.for.sig.test=FALSE) { trend <- switch(match.arg(method), zhang = as.data.frame(t(apply(indat[, (1 + metadata.cols):ncol(indat)], 1, zyp.zhang, conf.intervals=conf.intervals, preserve.range.for.sig.test=preserve.range.for.sig.test))), yuepilon = as.data.frame(t(apply(indat[, (1 + metadata.cols):ncol(indat)], 1, zyp.yuepilon, conf.intervals=conf.intervals, preserve.range.for.sig.test=preserve.range.for.sig.test))) ) if(metadata.cols > 0) { trend <- cbind(indat[,1:metadata.cols], trend) # Preserve metadata column names names(trend)[1:metadata.cols] <- names(indat)[1:metadata.cols] } return (trend) } # Applies either a Yue Pilon or Zhang trend calculation to a file in the format "metadata_1,...,metadata_n,year1,year2,...", where n is the number of metadata columns and the timeseries extending across the row zyp.trend.csv <- function(filename, output.filename, metadata.cols, method=c("zhang", "yuepilon"), conf.intervals=TRUE, csv.header=TRUE, preserve.range.for.sig.test=FALSE) { indat <- read.csv(filename, csv.header) write.csv(zyp.trend.dataframe(indat, metadata.cols, method, conf.intervals, preserve.range.for.sig.test), output.filename, row.names=FALSE) }
/scratch/gouwar.j/cran-all/cranData/zyp/R/zyp.R
# .zz_endpoint_content #' #' Auxiliary function #' #' Decorate an endpoint with a content path #' #' @keywords internal .zz_endpoint_content <- function(endpoint, id) { url <- paste0(endpoint, id, "/content") } # .zz_get_key #' #' Auxiliary function #' #' Get Zamzar key from .Renviron #' #' @keywords internal .zz_get_key <- function(usr) { if (is.null(usr)) { Sys.getenv("ZAMZAR_USR", "") } else { usr <- usr } } # .zz_authenticate #' #' Auxiliary function #' #' Wrapper for httr::authenticate #' #' @keywords internal .zz_authenticate <- function(usr) { httr::authenticate( user = usr, password = "", type = "basic" ) } # .zz_parse_response #' #' Auxiliary function #' #' Wrapper for parsing of responses #' #' @keywords internal .zz_parse_response <- function(response) { content <- httr::content(response, as = "text", encoding = "UTF-8") content <- jsonlite::fromJSON(content, flatten = TRUE) } # .zz_user_agent #' #' Auxiliary wrapper for user agent #' #' @keywords internal .zz_user_agent <- function() { httr::user_agent("zzlite - https://github.com/fkoh111/zzlite") } # .zz_do_paging #' #' Auxiliary function #' #' Function that deals with paging #' #' @keywords internal .zz_do_paging <- function(content, container, endpoint, usr) { if (content[['paging']][['total_count']] > length(content[['data']][['name']])) { storage <- list() counter <- ceiling(content[['paging']][['total_count']] / length(content[['data']][['name']])) for(i in 1:counter) { state_last_target <- content[['paging']][['last']] paged_endpoint <- httr::modify_url(endpoint, query = list(after=state_last_target)) paged_response <- httr::GET(paged_endpoint, config = .zz_authenticate(usr), .zz_user_agent() ) content <- .zz_parse_response(response = paged_response) temp <- data.frame(target = content[['data']][['name']], stringsAsFactors = FALSE) storage[[i]] <- temp } storage <- do.call(rbind, storage) container <- rbind(container, storage) } }
/scratch/gouwar.j/cran-all/cranData/zzlite/R/utils.R
#' Delete file from Zamzar account #' #' Delete file from Zamzar account provided a file id. #' #' Please note that a Zamzar key passed as argument to `usr` takes precedence over a #' Zamzar key extracted from an `.Renviron`. #' #' #' @param id The target id for a file you wish to delete. Most likely returned from ‘zz get info()‘. #' #' @param usr The username/API key you are using. If not set, the function #' will check if a key exists as a `ZAMZAR_USR` variable in `.Renviron` and use that. #' #' See: \url{https://developers.zamzar.com/user} #' #' @param verbose Boolean deciding whether or not verbose status messages #' should be returned. Defaults to `FALSE`. #' #' @export #' @return A status message indicating either success or failure. #' #' @examples #' \dontrun{ #' # An example of zz_delete() with a hardcoded file id #' #' zz_get(id = 12345678) #' } zz_delete <- function(id = NULL, usr = NULL, verbose = FALSE) { if (is.null(id)) { stop("Whoops, seems like you forgot to pass an id!") } usr <- .zz_get_key(usr = usr) endpoint <- zz_config[['prod']][[2]] response <- httr::DELETE(url = paste0(endpoint, id), config = .zz_authenticate(usr), .zz_user_agent() ) if (!response[['status_code']] == 200) { stop(sprintf("Zamzar responded with a status code of: %d", response[['status_code']]) ) } else { if (verbose == FALSE) { res <- response[['status_code']] } else { res <- data.frame(id = id, status_code = response[['status_code']], deleted_at = response[['date']], stringsAsFactors = FALSE) } } return(res) }
/scratch/gouwar.j/cran-all/cranData/zzlite/R/zz_delete.R
#' Accepted formats from Zamzar #' #' Get dataframe of all the formats accepted by Zamzar. Alternatively, a dataframe of formats #' you can convert an origin to. #' #' Please note that a Zamzar key passed as argument to `usr` takes precedence over a #' Zamzar key extracted from an `.Renviron`. #' #' @param origin The origin format you want to convert from. #' If a valid argument is passed to `origin`, `zz_format()` returns a dataframe of: #' #' * `targets`: The formats your origin can be converted to. #' * `costs`: The cost for converting between your origin and a given target. #' #' See also: \url{https://developers.zamzar.com/formats} #' #' If no argument has been passed to `orign`, a dataframe containing all #' the accepted formats by the Zamzar API is returned. #' #' See: \url{https://developers.zamzar.com/formats} #' #' #' @param usr The username/API key you are using. If not set, the function #' will check if a key exists as a `ZAMZAR_USR` variable in `.Renviron` and use that. #' #' See: \url{https://developers.zamzar.com/user} #' #' #' @md #' #' @export #' @return Either a dataframe of formats that you can convert to, or a #' dataframe of accepted origin formats. #' #' @examples #' \dontrun{ #' # Returns a single column dataframe of all the accepted formats #' # for the origin param. #' zz_format(usr = "key") #' #' # Same as above (assuming a valid key in .Renviron). #' zz_format() #' #' # Returns an error since the origin argument isn't recognized by the Zamzar API. #' zz_format(origin = "invalid_origin") #' #' # Returns a dataframe of targets that origin can be converted to, #' # and of the cost of converting to a given target. #' zz_format(origin = "emf") #' } zz_format <- function(origin = NULL, usr = NULL) { usr <- .zz_get_key(usr = usr) if (is.null(origin) || origin == "") { endpoint <- zz_config[['format']][[1]] } else { endpoint <- paste0(zz_config[['format']][[1]], "/", origin) } response <- httr::GET(endpoint, config = .zz_authenticate(usr = usr), .zz_user_agent() ) content <- .zz_parse_response(response = response) if (!response[['status_code']] %in% c(200, 201)) { stop(sprintf("Whoops! Zamzar responded with: %s, and a status code of: %d", content[['errors']][['message']], response[['status_code']]) ) } container <- data.frame(target = content[['data']][['name']], stringsAsFactors = FALSE) # Checking if we should do paging (more than 50) if(length(content[['data']][['name']]) >= 50) { container <- .zz_do_paging(content = content, container = container, endpoint = endpoint, usr = usr) } if (is.null(origin) || origin == "") { res <- container } else { res <- data.frame(target = content[['targets']][['name']], cost = content[['targets']][['credit_cost']], stringsAsFactors = FALSE) } if (response[['status_code']] %in% c(200, 201)) { return(res) } else { stop(sprintf("Whoops! Zamzar responded with: %s, and status code %d.", content[['errors']][['message']], response[['status_code']]) ) } }
/scratch/gouwar.j/cran-all/cranData/zzlite/R/zz_format.R
#' Get file from Zamzar account #' #' Get file from Zamzar account provided a file id. #' Per default `zz_get()` assumes that you're doing development, thus using a #' development endpoint. Set prod boolean to `TRUE` to change this behavior. #' #' On differences between endpoints, see: \url{https://developers.zamzar.com/docs#section-Next_steps} and \url{https://developers.zamzar.com/docs#section-Rate_Limits} #' #' Please note that a Zamzar key passed as argument to `usr` takes precedence over a #' Zamzar key extracted from an `.Renviron`. #' #' #' @param id The target id for a previously passed file. Most likely #' returned from `zz_get_info()`. #' #' @param usr The username/API key you are using. If not set, the function #' will check if a key exists as a `ZAMZAR_USR` variable in `.Renviron` and use that. #' #' See: \url{https://developers.zamzar.com/user} #' #' @param name The name of the file you are fetching from Zamzar. If a name is #' not assigned to the file, then the id of the file will be used as file name. #' #' @param extension The extension of the file you are fetching from Zamzar. #' #' @param overwrite Should `zz_get()` overwrite if a file with the same name already #' exists in directory. Defaults to `FALSE`. #' #' @param prod Boolean deciding whether to use a production endpoint or #' a development endpoint. Defaults to FALSE (That is, development endpoint). #' #' @export #' @return A file written to disk. #' #' @examples #' \dontrun{ #' # An example of zz_get() utilized with hardcoded arguments #' zz_get(id = 12345678, usr = "key", name = "my_avatar", extension = "png") #' #' # An example of zz_get() used in conjunction with zz_get_info() #' # Please note this example assumes a valid key in .Renviron #' response <- zz_get_info(latest = TRUE) #' zz_get(id = response$id, extension = response$extension, prod = TRUE) #' } zz_get <- function(id = NULL, usr = NULL, name = NULL, extension = NULL, overwrite = FALSE, prod = FALSE) { if (is.null(id)) { stop("Whoops, seems like you forgot to pass an id!") } usr <- .zz_get_key(usr = usr) if (is.null(extension)) { stop("Whoops, please let me know the extension of the file I should get.") } if (is.null(name)) { id <- as.character(id) } if (prod == FALSE) { endpoint <- zz_config[['dev']][[2]] } if (prod == TRUE) { endpoint <- zz_config[['prod']][[2]] } # Concatenating an URL url <- .zz_endpoint_content(endpoint = endpoint, id = id) if (!is.null(name)) { id <- name } identifier <- paste0(id, ".", extension) response <- httr::GET(url, httr::write_disk(identifier, overwrite = overwrite), config = .zz_authenticate(usr), .zz_user_agent() ) if (!response$status_code %in% c(200, 201)) { stop(sprintf("Zamzar responded with a status code of: %d", response[['status_code']]) ) } else { message(sprintf("Writing file %s to %s", identifier, getwd())) } # Delete file if status code indicates so if (response[['status_code']] %in% c(404)) { unlink(identifier) } }
/scratch/gouwar.j/cran-all/cranData/zzlite/R/zz_get.R
#' Get info from Zamzar #' #' Get info on files submitted to Zamzar by account. #' #' Per default `zz_get_info()` assumes you want information for the last #' submitted file. To get information on all the files that have been submitted #' within a reasonable time frame, set parameter `latest` to `FALSE`. #' #' Please note: objects returned from `zz_get_info()` doesn't differentiate #' between development or production endpoint. You have to keep track of #' this yourself. #' #' Please note that a Zamzar key passed as argument to `usr` takes precedence over a #' Zamzar key extracted from an `.Renviron`. #' #' #' @param usr The username/API key you are using. If not set, the function #' will check if a key exists as a `ZAMZAR_USR` variable in `.Renviron` and use that. #' #' See: \url{https://developers.zamzar.com/user} #' #' @param latest Boolean deciding whether or not metadata on all files that #' have been submitted within a reasonable time frame should be returned. #' #' If switched to `FALSE`, metadata on all files that have been submitted to #' the Zamzar API within a reasonable time frame will be returned. #' #' Defaults to `TRUE`. #' #' The returned dataframe contains the following columns: #' #' * `id`: The unique file identifier assigned to a file by Zamzar. #' * `extension`: The extension representing the format of the file you can download. #' * `created_at`: The time at which the file was created at the Zamzar servers. #' #'@md #' #' @export #' @return A dataframe. #' #' #' @examples #' \dontrun{ #' # Provided a valid token in .Renvirion, a dataframe of metadata for the last #' # submitted file will be returned. #' zz_get_info() #' #' # Same as above, we're just passing the key in a variable. #' zz_get_info(usr = "key") #' #' # Provided a valid token, will return metadata for all files #' # submitted to the API within a reasonable time frame. #' zz_get_info(usr = "key", latest = FALSE) #' #' # Same as above, we're just utilizing .Renviron. #' zz_get_info(latest = FALSE) #' } zz_get_info <- function(usr = NULL, latest = TRUE) { endpoint <- zz_config[['prod']][[2]] usr <- .zz_get_key(usr = usr) response <- httr::GET(url = endpoint, config = .zz_authenticate(usr), .zz_user_agent() ) content <- .zz_parse_response(response = response) if (!response[['status_code']] == 200) { stop(sprintf("Zamzar responded with %s and a status code of: %d", content[['errors']][['message']], response[['status_code']] ) ) } if (isTRUE(content[['paging']][['total_count']] == 0) && isTRUE(content[['paging']][['limit']] == 50)) { stop("Seems like Zamzar doesn't store any files submitted by this account!") } if (latest == TRUE) { res <- data.frame(id = content[['data']][['id']][[1]], extension = content[['data']][['format']][[1]], created_at = content[['data']][['created_at']][[1]], stringsAsFactors = FALSE) } else { res <- data.frame(id = content[['data']][['id']], extension = content[['data']][['format']], created_at = content[['data']][['created_at']], stringsAsFactors = FALSE) } return(res) }
/scratch/gouwar.j/cran-all/cranData/zzlite/R/zz_get_info.R
#' Post file to Zamzar endpoint #' #' Per default `zz_post()` assumes that you're doing development, thus using a #' development endpoint. Set parameter `prod` to `TRUE` to change this behavior. #' #' On differences between endpoints, see: \url{https://developers.zamzar.com/docs#section-Next_steps} and \url{https://developers.zamzar.com/docs#section-Rate_Limits} #' #' Please note that a Zamzar key passed as argument to `usr` takes precedence over a #' Zamzar key extracted from an `.Renviron`. #' #' #' @param file The path to the file you want to convert. #' #' @param extension The file type you want to convert to. E.g., `png`. #' #' @seealso \code{\link{zz_format}} for a list of formats you can convert to. #' #' @param usr The username/API key you are using. If not set, the function #' will check if a key exists as a `ZAMZAR_USR` variable in `.Renviron` and use that. #' #' See: \url{https://developers.zamzar.com/user} #' #' @param prod Boolean deciding whether to use production or development endpoint. #' Defaults to `FALSE`. #' #' @param verbose Boolean deciding whether or not verbose status messages #' should be returned. Defaults to `FALSE`. #' #' @export #' @return A status message indicating either success or failure. #' #' @examples #' \dontrun{ #' # Per default zz_post uses the development endpoint. #' zz_post(file = "avatar.emf", extension = "png") #' #' # Setting prod parameter to FALSE is the same as above. #' zz_post(file = "avatar.emf", extension = "png", prod = FALSE) #' #' # You need to flip prod to TRUE if you want to use the production endpoint. #' zz_post(file = "avatar.emf", extension = "png", prod = TRUE) #' #' # Remember you can always pass a Zamzar key to the usr parameter if you don't #' # want to use an .Renviron file. #' zz_post(file = "avatar.emf", usr = "key", extension = "png", prod = TRUE) #' #' } zz_post <- function(file = NULL, extension = NULL, usr = NULL, prod = FALSE, verbose = FALSE) { if (is.null(file)) { stop("Whoops, please pass a file!") } if (is.null(extension)) { stop("Excuse me, but I need to know the extension type; please pass it :-)") } usr <- .zz_get_key(usr = usr) if (prod == FALSE) { endpoint <- zz_config[['dev']][[1]] } if (prod == TRUE) { endpoint <- zz_config[['prod']][[1]] } body <- list(source_file = httr::upload_file(path = file), target_format = extension) response <- httr::POST(url = endpoint, config = .zz_authenticate(usr), body = body, .zz_user_agent() ) res <- data.frame(status = response[['status_code']], endpoint = response[['url']], date = response[['date']]) if (verbose == TRUE) { res <- res } else { res <- res[['status']] } return(res) }
/scratch/gouwar.j/cran-all/cranData/zzlite/R/zz_post.R
zz_config <- new.env(parent = emptyenv()) .onLoad <- function(...) { prod <- list( post <- c("https://api.zamzar.com/v1/jobs"), get <- c("https://api.zamzar.com/v1/files/") ) dev <- list( post <- c("https://sandbox.zamzar.com/v1/jobs"), get <- c("https://sandbox.zamzar.com/v1/files/") ) format <- list( format <- c("https://sandbox.zamzar.com/v1/formats") ) assign("prod", prod, envir = zz_config) assign("dev", dev, envir = zz_config) assign("format", format, envir = zz_config) }
/scratch/gouwar.j/cran-all/cranData/zzlite/R/zzz.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
/scratch/gouwar.j/cran-all/cranData/zzlite/inst/doc/A-primer-on-zzlite.R
--- title: "A primer on zzlite" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{A-primer-on-zzlite} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` The `zzlite` package is a collection of wrappers that simplifies communication between R and the [Zamzar Online file conversion](https://developers.zamzar.com/user) API. By utilizing `zzlite` (and thereby the Zamzar API) you can easily convert between [hundreds](https://developers.zamzar.com/formats) of file formats from an R session.* ## The basics The following section serves as a simple introduction to the `zzlite` package. Since Zamzar requires authentication, it is assumed that you have a valid key at your disposal. If not, go sign up via [Zamzar](https://developers.zamzar.com/)s website to get one. ### On Zamzar API keys in `zzlite` There's two ways in which you can pass a Zamzar key to `zzlite`. 1. Either by passing a hard coded Zamzar key as an argument to the `usr` parameter. 2. By leveraging an `.Renviron` file. Simply create a variable called `ZAMZAR_USR` in your `.Renviron` and pass it a Zamzar key. If done successfully, you can skip passing a key to the `usr` parameter whenever you're invoking `zzlite` functions. <center>_Example of .Renviron:_</center> ```sh ZAMZAR_USR=77c39dh6lo03g7598t98h659ihg99b7ny7213q ``` For security reasons, and best practices, the second way is the preferred way to deal with API keys. Therefore the following examples have been made with the `.Renviron` method in mind. ### `zz_format()` In general there's two use cases for the `zz_format()` function. 1. If you're curious about formats accepted by the Zamzar API, invoke `zz_format()` and inspect the supported formats: ```r zzlite::zz_format() #> target #> 1 3g2 #> 2 3ga #> 3 3gp #> 4 3gpp #> 5 7z #> 6 aac #> 7 ac3 #> 8 ai #> 9 asf #> 10 avi #> 11 azw #> 12 azw3 #> 13 bmp #> 14 cab #> 15 cbc #> 16 cbr #> 17 cbz #> 18 cdr #> 19 chm #> 20 csv #> 21 djvu #> 22 doc #> 23 docm #> 24 docx #> 25 dwg #> 26 dxf #> 27 emf #> 28 eml #> 29 eps #> 30 epub #> 31 fb2 #> 32 flac #> 33 flv #> 34 gif #> 35 gvi #> 36 jpg #> 37 lit #> 38 lrf #> 39 lzh #> 40 m4a #> 41 m4r #> 42 m4v #> 43 mkv #> 44 mobi #> 45 mod #> 46 mov #> 47 mp3 #> 48 mp4 #> 49 mpg #> 50 msg #> 51 mts #> 52 odg #> 53 odp #> 54 ods #> 55 odt #> 56 ogg #> 57 pcx #> 58 pdb #> 59 pdf #> 60 pml #> 61 png #> 62 pps #> 63 ppsx #> 64 ppt #> 65 pptm #> 66 pptx #> 67 prc #> 68 ps #> 69 psd #> 70 pub #> 71 ra #> 72 ram #> 73 rar #> 74 rb #> 75 rm #> 76 rmvb #> 77 rtf #> 78 svg #> 79 tar #> 80 tar.bz2 #> 81 tar.gz #> 82 tcr #> 83 tga #> 84 tiff #> 85 ts #> 86 txt #> 87 vob #> 88 wav #> 89 wbmp #> 90 webm #> 91 webp #> 92 wks #> 93 wma #> 94 wmf #> 95 wmv #> 96 wpd #> 97 wps #> 98 xlr #> 99 xls #> 100 xlsm #> 101 xlsx #> 102 xps #> 103 yz1 #> 104 zip ``` 2. If you're curious to know what a format can be converted to, as well as the cost for converting (in Zamzar credit), pass an accepted extension to the origin parameter, e.g.: ```r zzlite::zz_format(origin = "emf") #> target cost #> 1 bmp 1 #> 2 gif 1 #> 3 ico 1 #> 4 jpg 1 #> 5 pcx 1 #> 6 pdf 1 #> 7 png 1 #> 8 ps 1 #> 9 tga 1 #> 10 thumbnail 1 #> 11 tiff 1 #> 12 wbmp 1 #> 13 webp 1 ``` ### `zz_post()` You convert a file from one format to another by invoking `zz_post()` with the appropriate arguments, e.g.: ```r zzlite::zz_post(file = "avatar.emf", extension = "png", prod = TRUE) #> 201 ``` In the example above, `avatar.emf` is the file that we've requested Zamzar to convert. The parameter `extension` is the extension/format we want the file to have _after_ conversion. The `prod` boolean decides whether or not we should use a development endpoint or a production endpoint. For more information on differences between endpoints, see: [test and production environments](https://developers.zamzar.com/docs) in the official Zamzar documentation. Upon completion `zz_post()` will respond with an HTTP status code provided by the API. For details on these, see Zamzars official documentation on [response codes](https://developers.zamzar.com/docs). ### `zz_get_info()` To return a converted file from the Zamzar API, you need to know which file to get. Assuming that we've just posted the `avatar.emf` to Zamzar via `zz_post()` and have received a `201` response from the API, a subsequent invocation of `zz_get_info()` will return a dataframe like this: ```r zzlite::zz_get_info() #> id extension created_at #> 1 61920043 emf 2020-02-02T13:41:53Z ``` This tells us, that a file with id `61920043` and an extension of `emf` is in the top of our stack of files associated with our Zamzar account. Now, since we've asked Zamzar to convert _from_ `emf` _to_ `png`, it might seem a bit strange that id `61920043` isn't a `png` file. The reason for this is simply because Zamzar (in this example) isn't done converting the file. If we wait a few seconds and then do a subsequent call to `zz_get_info()`, then we should see the converted file: ```r zzlite::zz_get_info() #> id extension created_at #> 1 61920045 png 2020-02-02T13:41:55Z ``` And as expected, Zamzar is done with the conversion, and a file with a new id, `61920045`, and an extension of `png`, is now in the top of our stack of files associated with our Zamzar account. Sometimes it is nice to inspect the entire backlog of files for your Zamzar account. It is possible to inspect these by switching the parameter `latest` from `TRUE` to `FALSE` (the parameter defaults to `TRUE`): ```r zzlite::zz_get_info(latest = FALSE) #> id extension created_at #> 1 61920045 png 2020-02-02T13:41:55Z #> 2 61920043 emf 2020-02-02T13:41:53Z ``` Now, how do we _get_ a file that has been converted? ### `zz_get()` We can get a converted file by invoking `zz_get()` with appropriate arguments. A minimal example for obtaining the converted avatar from the previous example would be: ```r zzlite::zz_get(id = 61920045, extension = "png", prod = TRUE) #> Writing file 61920045.png to /Users/whatever/Documents/conversions ``` As indicated by the example above, `zz_get()` will use the id as filename for the file we're _getting_ if no name has been set prior to invocation. The file will be written to the current working directory. A slightly more coherent way to obtain a file, could be something around these lines: ```r df <- zz_get_info(latest = TRUE) zz_get(id = df$id, extension = df$extension, name = "avatar") #> Writing file avatar.gif to /Users/whatever/Documents/conversions ``` ### `zz_delete()` If you need to, you can delete files from your Zamzar stack. Deletion is done by invoking `zz_delete()` with a file `id` obtained via `zz_get_info()`. Building upon the previous example, we could delete the `.png` file we just downloaded: ```r zzlite::zz_delete(id = "61920045") #> 200 ``` If you want more information than a mere status code upon executing `zz_delete()`, switch the `verbose` parameter to `TRUE`. E.g.: ```r zzlite::zz_delete(id = "61920043", verbose = TRUE) #> id status_code deleted_at #> 1 61920043 200 2020-02-02 13:52:33 ``` --- > *Please note that the package has a strict focus on rather simple conversions via Zamzar (implied by the _lite_ suffix in the name). It is intentional that the package doesn't focus on cloud integration etc.
/scratch/gouwar.j/cran-all/cranData/zzlite/inst/doc/A-primer-on-zzlite.Rmd
--- title: "A primer on zzlite" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{A-primer-on-zzlite} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` The `zzlite` package is a collection of wrappers that simplifies communication between R and the [Zamzar Online file conversion](https://developers.zamzar.com/user) API. By utilizing `zzlite` (and thereby the Zamzar API) you can easily convert between [hundreds](https://developers.zamzar.com/formats) of file formats from an R session.* ## The basics The following section serves as a simple introduction to the `zzlite` package. Since Zamzar requires authentication, it is assumed that you have a valid key at your disposal. If not, go sign up via [Zamzar](https://developers.zamzar.com/)s website to get one. ### On Zamzar API keys in `zzlite` There's two ways in which you can pass a Zamzar key to `zzlite`. 1. Either by passing a hard coded Zamzar key as an argument to the `usr` parameter. 2. By leveraging an `.Renviron` file. Simply create a variable called `ZAMZAR_USR` in your `.Renviron` and pass it a Zamzar key. If done successfully, you can skip passing a key to the `usr` parameter whenever you're invoking `zzlite` functions. <center>_Example of .Renviron:_</center> ```sh ZAMZAR_USR=77c39dh6lo03g7598t98h659ihg99b7ny7213q ``` For security reasons, and best practices, the second way is the preferred way to deal with API keys. Therefore the following examples have been made with the `.Renviron` method in mind. ### `zz_format()` In general there's two use cases for the `zz_format()` function. 1. If you're curious about formats accepted by the Zamzar API, invoke `zz_format()` and inspect the supported formats: ```r zzlite::zz_format() #> target #> 1 3g2 #> 2 3ga #> 3 3gp #> 4 3gpp #> 5 7z #> 6 aac #> 7 ac3 #> 8 ai #> 9 asf #> 10 avi #> 11 azw #> 12 azw3 #> 13 bmp #> 14 cab #> 15 cbc #> 16 cbr #> 17 cbz #> 18 cdr #> 19 chm #> 20 csv #> 21 djvu #> 22 doc #> 23 docm #> 24 docx #> 25 dwg #> 26 dxf #> 27 emf #> 28 eml #> 29 eps #> 30 epub #> 31 fb2 #> 32 flac #> 33 flv #> 34 gif #> 35 gvi #> 36 jpg #> 37 lit #> 38 lrf #> 39 lzh #> 40 m4a #> 41 m4r #> 42 m4v #> 43 mkv #> 44 mobi #> 45 mod #> 46 mov #> 47 mp3 #> 48 mp4 #> 49 mpg #> 50 msg #> 51 mts #> 52 odg #> 53 odp #> 54 ods #> 55 odt #> 56 ogg #> 57 pcx #> 58 pdb #> 59 pdf #> 60 pml #> 61 png #> 62 pps #> 63 ppsx #> 64 ppt #> 65 pptm #> 66 pptx #> 67 prc #> 68 ps #> 69 psd #> 70 pub #> 71 ra #> 72 ram #> 73 rar #> 74 rb #> 75 rm #> 76 rmvb #> 77 rtf #> 78 svg #> 79 tar #> 80 tar.bz2 #> 81 tar.gz #> 82 tcr #> 83 tga #> 84 tiff #> 85 ts #> 86 txt #> 87 vob #> 88 wav #> 89 wbmp #> 90 webm #> 91 webp #> 92 wks #> 93 wma #> 94 wmf #> 95 wmv #> 96 wpd #> 97 wps #> 98 xlr #> 99 xls #> 100 xlsm #> 101 xlsx #> 102 xps #> 103 yz1 #> 104 zip ``` 2. If you're curious to know what a format can be converted to, as well as the cost for converting (in Zamzar credit), pass an accepted extension to the origin parameter, e.g.: ```r zzlite::zz_format(origin = "emf") #> target cost #> 1 bmp 1 #> 2 gif 1 #> 3 ico 1 #> 4 jpg 1 #> 5 pcx 1 #> 6 pdf 1 #> 7 png 1 #> 8 ps 1 #> 9 tga 1 #> 10 thumbnail 1 #> 11 tiff 1 #> 12 wbmp 1 #> 13 webp 1 ``` ### `zz_post()` You convert a file from one format to another by invoking `zz_post()` with the appropriate arguments, e.g.: ```r zzlite::zz_post(file = "avatar.emf", extension = "png", prod = TRUE) #> 201 ``` In the example above, `avatar.emf` is the file that we've requested Zamzar to convert. The parameter `extension` is the extension/format we want the file to have _after_ conversion. The `prod` boolean decides whether or not we should use a development endpoint or a production endpoint. For more information on differences between endpoints, see: [test and production environments](https://developers.zamzar.com/docs) in the official Zamzar documentation. Upon completion `zz_post()` will respond with an HTTP status code provided by the API. For details on these, see Zamzars official documentation on [response codes](https://developers.zamzar.com/docs). ### `zz_get_info()` To return a converted file from the Zamzar API, you need to know which file to get. Assuming that we've just posted the `avatar.emf` to Zamzar via `zz_post()` and have received a `201` response from the API, a subsequent invocation of `zz_get_info()` will return a dataframe like this: ```r zzlite::zz_get_info() #> id extension created_at #> 1 61920043 emf 2020-02-02T13:41:53Z ``` This tells us, that a file with id `61920043` and an extension of `emf` is in the top of our stack of files associated with our Zamzar account. Now, since we've asked Zamzar to convert _from_ `emf` _to_ `png`, it might seem a bit strange that id `61920043` isn't a `png` file. The reason for this is simply because Zamzar (in this example) isn't done converting the file. If we wait a few seconds and then do a subsequent call to `zz_get_info()`, then we should see the converted file: ```r zzlite::zz_get_info() #> id extension created_at #> 1 61920045 png 2020-02-02T13:41:55Z ``` And as expected, Zamzar is done with the conversion, and a file with a new id, `61920045`, and an extension of `png`, is now in the top of our stack of files associated with our Zamzar account. Sometimes it is nice to inspect the entire backlog of files for your Zamzar account. It is possible to inspect these by switching the parameter `latest` from `TRUE` to `FALSE` (the parameter defaults to `TRUE`): ```r zzlite::zz_get_info(latest = FALSE) #> id extension created_at #> 1 61920045 png 2020-02-02T13:41:55Z #> 2 61920043 emf 2020-02-02T13:41:53Z ``` Now, how do we _get_ a file that has been converted? ### `zz_get()` We can get a converted file by invoking `zz_get()` with appropriate arguments. A minimal example for obtaining the converted avatar from the previous example would be: ```r zzlite::zz_get(id = 61920045, extension = "png", prod = TRUE) #> Writing file 61920045.png to /Users/whatever/Documents/conversions ``` As indicated by the example above, `zz_get()` will use the id as filename for the file we're _getting_ if no name has been set prior to invocation. The file will be written to the current working directory. A slightly more coherent way to obtain a file, could be something around these lines: ```r df <- zz_get_info(latest = TRUE) zz_get(id = df$id, extension = df$extension, name = "avatar") #> Writing file avatar.gif to /Users/whatever/Documents/conversions ``` ### `zz_delete()` If you need to, you can delete files from your Zamzar stack. Deletion is done by invoking `zz_delete()` with a file `id` obtained via `zz_get_info()`. Building upon the previous example, we could delete the `.png` file we just downloaded: ```r zzlite::zz_delete(id = "61920045") #> 200 ``` If you want more information than a mere status code upon executing `zz_delete()`, switch the `verbose` parameter to `TRUE`. E.g.: ```r zzlite::zz_delete(id = "61920043", verbose = TRUE) #> id status_code deleted_at #> 1 61920043 200 2020-02-02 13:52:33 ``` --- > *Please note that the package has a strict focus on rather simple conversions via Zamzar (implied by the _lite_ suffix in the name). It is intentional that the package doesn't focus on cloud integration etc.
/scratch/gouwar.j/cran-all/cranData/zzlite/vignettes/A-primer-on-zzlite.Rmd