content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
---
title: "xlink"
author: "Wei Xu, Meiling Hao, Yi Zhu"
date: "`r Sys.Date()`"
show_toc: true
slug: xlink
githubEditURL: https://github.com/qiuanzhu/xlink/blob/master/vignettes/xlink.Rmd
output:
rmarkdown::html_vignette:
toc: yes
vignette: >
%\VignetteIndexEntry{An Introduction to xlink}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
# 1. Introduction
**xlink** from [github](https://github.com/qiuanzhu/xlink) is a package for the unified partial likelihood approach for X-chromosome association on time-to-event/ continuous/ binary outcomes. The expression of X-chromosome undergoes three possible biological processes: X-chromosome inactivation (XCI), escape of the X-chromosome inactivation (XCI-E), and skewed X-chromosome inactivation (XCI-S). Although these expressions are included in various predesigned genetic variation chip platforms, the X-chromosome has generally been excluded from the majority of genome-wide association studies analyses; this is most likely due to the lack of a standardized method in handling X-chromosomal genotype data. To analyze the X-linked genetic association for time-to-event outcomes with the actual process unknown, we propose a unified approach of maximizing the partial likelihood over all of the potential biological processes. The proposed method can be used to infer the true biological process and derive unbiased estimates of the genetic association parameters.
## Reference:
> "Xu, Wei, and Meiling Hao. "A unified partial likelihood approach for X‐chromosome association on time‐to‐event outcomes." Genetic epidemiology 42.1 (2018): 80-94." ([via](https://onlinelibrary.wiley.com/doi/abs/10.1002/gepi.22097))
> "Han, D., Hao, M., Qu, L., & Xu, W. (2019). ”A novel model for the X-chromosome inactivation association on survival data." Statistical Methods in Medical Research."
([via](https://www.ncbi.nlm.nih.gov/pubmed/31258049))
# 2. Installation
You can install **xlink** from [github]((https://github.com/qiuanzhu/xlink):
```{r eval=FALSE}
library("devtools")
install_github("qiuanzhu/xlink")
```
#3. Examples
In the following examples, we choose the **model** is "survival" model, which could also applied to "linear" model for continuous response and "binary" for fitting logistic regression model.
## 3.1 Select significant SNPs from XCI or XCI-E model type:
In the sample data with 10 SNPs and 4 clinic covariates,
```{r eval=FALSE}
library("xlink")
head(Rdata)
```
```{r, echo=FALSE, results='asis'}
library(xlink)
knitr::kable(head(Rdata))
```
If the Model type is chosen to be **XCI** and threshold for **MAF_v** is set to be 0.05, the output for snp_1 with coefficient, P value and loglikelihood information
```{r eval=FALSE}
Covars<-c("Age","Smoking","Treatment")
SNPs<-c("snp_1","snp_2")
output<-xlink_fit(os="OS",ostime="OS_time",snps=SNPs,gender="gender",covars=Covars, option =list(type="XCI",MAF_v=0.05),model="survival",data = Rdata)
```
```{r echo=FALSE, results='asis'}
Covars<-c("Age","Smoking","Treatment")
SNPs<-c("snp_1","snp_2")
output<-xlink_fit(os="OS",ostime="OS_time",snps=SNPs,gender="gender",covars=Covars, option =list(type="XCI",MAF_v=0.05),model="survival",data = Rdata)
```
```{r echo=FALSE, results='asis'}
knitr::kable(output[1]$snp_1$coefficients)
knitr::kable(output[1]$snp_1$loglik)
```
## 3.2 Select significant SNPs from all model type:
If the Model type is chosen to be **all** and threshold for **MAF_v** is set to be 0.1, the output for snp_1 with coefficient , P value and log-likelihood function information for **XCI-E**, **XCI** and **XCI-S** respectively,
```{r eval=FALSE}
Covars<-c("Age","Smoking","Treatment")
SNPs<-c("snp_1","snp_2")
output<-xlink_fit(os="OS",ostime="OS_time",snps=SNPs,gender="gender",covars=Covars, option =list(type="all",MAF_v=0.05),model="survival",data = Rdata)
```
For XCI-E model, snp_1 with coefficient, P value and log-likelihood function information
```{r echo=FALSE, results='asis'}
output<-xlink_fit(os="OS",ostime="OS_time",snps=SNPs,gender="gender",covars=Covars, option =list(MAF_v=0.1),model="survival",data = Rdata)
knitr::kable(output$snp_1$`XCI-E`$coefficients)
knitr::kable(output$snp_1$`XCI-E`$loglik)
```
For XCI model, snp_1 with coefficient, P value and log-likelihood function information
```{r echo=FALSE, results='asis'}
knitr::kable(output$snp_1$`XCI`$coefficients)
knitr::kable(output$snp_1$`XCI`$loglik)
```
For XCI-S model, snp_1 with coefficient , log-likelihood function information and **gamma** estimation
```{r echo=FALSE, results='asis'}
knitr::kable(output$snp_1$`XCI-S`$coefficients)
knitr::kable(output$snp_1$`XCI-S`$loglik)
knitr::kable(output$snp_1$`XCI-S`$Gamma , col.names ="Gamma")
```
The best model for snp_1 among model type XCI-E, XCI and XCI-S by using the AIC is
```{r echo=FALSE, results='asis'}
knitr::kable(output$snp_1$`Best model by AIC`, col.names = "Best model by AIC" )
```
## 3.3 Output for the significant SNPs by P value:
By setting the threshold for **pv_thold**, the select output become
```{r eval=FALSE}
Covars<-c("Age","Smoking","Treatment")
SNPs<-c("snp_1","snp_2","snp_3")
result<-xlink_fit(os="OS",ostime ="OS_time",snps=SNPs,gender ="gender",covars=Covars,
option =list(type="all",MAF_v=0.05), model="survival", data = Rdata)
select_output(input=result,pv_thold=10^-5)
```
```{r echo=FALSE, results='asis'}
Covars<-c("Age","Smoking","Treatment")
SNPs<-c("snp_1","snp_2","snp_3")
result<-xlink_fit(os="OS",ostime ="OS_time",snps=SNPs,gender ="gender",covars=Covars,
option =list(type="all",MAF_v=0.05), model="survival", data = Rdata)
knitr::kable( select_output(input=result,pv_thold=10^-5) )
```
| /scratch/gouwar.j/cran-all/cranData/xlink/inst/doc/xlink.Rmd |
---
title: "xlink"
author: "Wei Xu, Meiling Hao, Yi Zhu"
date: "`r Sys.Date()`"
show_toc: true
slug: xlink
githubEditURL: https://github.com/qiuanzhu/xlink/blob/master/vignettes/xlink.Rmd
output:
rmarkdown::html_vignette:
toc: yes
vignette: >
%\VignetteIndexEntry{An Introduction to xlink}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
# 1. Introduction
**xlink** from [github](https://github.com/qiuanzhu/xlink) is a package for the unified partial likelihood approach for X-chromosome association on time-to-event/ continuous/ binary outcomes. The expression of X-chromosome undergoes three possible biological processes: X-chromosome inactivation (XCI), escape of the X-chromosome inactivation (XCI-E), and skewed X-chromosome inactivation (XCI-S). Although these expressions are included in various predesigned genetic variation chip platforms, the X-chromosome has generally been excluded from the majority of genome-wide association studies analyses; this is most likely due to the lack of a standardized method in handling X-chromosomal genotype data. To analyze the X-linked genetic association for time-to-event outcomes with the actual process unknown, we propose a unified approach of maximizing the partial likelihood over all of the potential biological processes. The proposed method can be used to infer the true biological process and derive unbiased estimates of the genetic association parameters.
## Reference:
> "Xu, Wei, and Meiling Hao. "A unified partial likelihood approach for X‐chromosome association on time‐to‐event outcomes." Genetic epidemiology 42.1 (2018): 80-94." ([via](https://onlinelibrary.wiley.com/doi/abs/10.1002/gepi.22097))
> "Han, D., Hao, M., Qu, L., & Xu, W. (2019). ”A novel model for the X-chromosome inactivation association on survival data." Statistical Methods in Medical Research."
([via](https://www.ncbi.nlm.nih.gov/pubmed/31258049))
# 2. Installation
You can install **xlink** from [github]((https://github.com/qiuanzhu/xlink):
```{r eval=FALSE}
library("devtools")
install_github("qiuanzhu/xlink")
```
#3. Examples
In the following examples, we choose the **model** is "survival" model, which could also applied to "linear" model for continuous response and "binary" for fitting logistic regression model.
## 3.1 Select significant SNPs from XCI or XCI-E model type:
In the sample data with 10 SNPs and 4 clinic covariates,
```{r eval=FALSE}
library("xlink")
head(Rdata)
```
```{r, echo=FALSE, results='asis'}
library(xlink)
knitr::kable(head(Rdata))
```
If the Model type is chosen to be **XCI** and threshold for **MAF_v** is set to be 0.05, the output for snp_1 with coefficient, P value and loglikelihood information
```{r eval=FALSE}
Covars<-c("Age","Smoking","Treatment")
SNPs<-c("snp_1","snp_2")
output<-xlink_fit(os="OS",ostime="OS_time",snps=SNPs,gender="gender",covars=Covars, option =list(type="XCI",MAF_v=0.05),model="survival",data = Rdata)
```
```{r echo=FALSE, results='asis'}
Covars<-c("Age","Smoking","Treatment")
SNPs<-c("snp_1","snp_2")
output<-xlink_fit(os="OS",ostime="OS_time",snps=SNPs,gender="gender",covars=Covars, option =list(type="XCI",MAF_v=0.05),model="survival",data = Rdata)
```
```{r echo=FALSE, results='asis'}
knitr::kable(output[1]$snp_1$coefficients)
knitr::kable(output[1]$snp_1$loglik)
```
## 3.2 Select significant SNPs from all model type:
If the Model type is chosen to be **all** and threshold for **MAF_v** is set to be 0.1, the output for snp_1 with coefficient , P value and log-likelihood function information for **XCI-E**, **XCI** and **XCI-S** respectively,
```{r eval=FALSE}
Covars<-c("Age","Smoking","Treatment")
SNPs<-c("snp_1","snp_2")
output<-xlink_fit(os="OS",ostime="OS_time",snps=SNPs,gender="gender",covars=Covars, option =list(type="all",MAF_v=0.05),model="survival",data = Rdata)
```
For XCI-E model, snp_1 with coefficient, P value and log-likelihood function information
```{r echo=FALSE, results='asis'}
output<-xlink_fit(os="OS",ostime="OS_time",snps=SNPs,gender="gender",covars=Covars, option =list(MAF_v=0.1),model="survival",data = Rdata)
knitr::kable(output$snp_1$`XCI-E`$coefficients)
knitr::kable(output$snp_1$`XCI-E`$loglik)
```
For XCI model, snp_1 with coefficient, P value and log-likelihood function information
```{r echo=FALSE, results='asis'}
knitr::kable(output$snp_1$`XCI`$coefficients)
knitr::kable(output$snp_1$`XCI`$loglik)
```
For XCI-S model, snp_1 with coefficient , log-likelihood function information and **gamma** estimation
```{r echo=FALSE, results='asis'}
knitr::kable(output$snp_1$`XCI-S`$coefficients)
knitr::kable(output$snp_1$`XCI-S`$loglik)
knitr::kable(output$snp_1$`XCI-S`$Gamma , col.names ="Gamma")
```
The best model for snp_1 among model type XCI-E, XCI and XCI-S by using the AIC is
```{r echo=FALSE, results='asis'}
knitr::kable(output$snp_1$`Best model by AIC`, col.names = "Best model by AIC" )
```
## 3.3 Output for the significant SNPs by P value:
By setting the threshold for **pv_thold**, the select output become
```{r eval=FALSE}
Covars<-c("Age","Smoking","Treatment")
SNPs<-c("snp_1","snp_2","snp_3")
result<-xlink_fit(os="OS",ostime ="OS_time",snps=SNPs,gender ="gender",covars=Covars,
option =list(type="all",MAF_v=0.05), model="survival", data = Rdata)
select_output(input=result,pv_thold=10^-5)
```
```{r echo=FALSE, results='asis'}
Covars<-c("Age","Smoking","Treatment")
SNPs<-c("snp_1","snp_2","snp_3")
result<-xlink_fit(os="OS",ostime ="OS_time",snps=SNPs,gender ="gender",covars=Covars,
option =list(type="all",MAF_v=0.05), model="survival", data = Rdata)
knitr::kable( select_output(input=result,pv_thold=10^-5) )
```
| /scratch/gouwar.j/cran-all/cranData/xlink/vignettes/xlink.Rmd |
######################################################################
# Deal with Alignment
#' @export
#' @rdname Alignment
is.Alignment <- function(x) inherits(x, "Alignment")
######################################################################
# Create an Alignment.
#
#' Create an Alignment object.
#'
#' Create an Alignment object, useful when working with cell styles.
#'
#'
#' @param horizontal a character value specifying the horizontal alignment.
#' Valid values come from constant \code{HALIGN_STYLES_}.
#' @param vertical a character value specifying the vertical alignment. Valid
#' values come from constant \code{VALIGN_STYLES_}.
#' @param wrapText a logical indicating if the text should be wrapped.
#' @param rotation a numerical value indicating the degrees you want to rotate
#' the text in the cell.
#' @param indent a numerical value indicating the number of spaces you want to
#' indent the text in the cell.
#' @param x An Alignment object, as returned by \code{Alignment}.
#' @return \code{Alignment} returns a list with components from the input
#' argument, and a class attribute "Alignment". Alignment objects are used
#' when constructing cell styles.
#'
#' \code{is.Alignment} returns \code{TRUE} if the argument is of class
#' "Alignment" and \code{FALSE} otherwise.
#' @author Adrian Dragulescu
#' @seealso \code{\link{CellStyle}} for using the a \code{Alignment} object.
#' @examples
#'
#'
#' # you can just use h for horizontal, since R does the matching for you
#' a1 <- Alignment(h="ALIGN_CENTER", rotation=90) # centered and rotated!
#'
#' @export
Alignment <- function(horizontal=NULL, vertical=NULL, wrapText=FALSE,
rotation=0, indent=0)
{
if (!is.null(horizontal) && !(horizontal %in% names(HALIGN_STYLES_)))
stop("Not a valid horizontal value. See help page.")
if (!is.null(vertical) && !(vertical %in% names(VALIGN_STYLES_)))
stop("Not a valid vertical value. See help page.")
structure(list(horizontal=horizontal, vertical=vertical,
wrapText=wrapText, rotation=rotation, indent=0),
class="Alignment")
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/Alignment.R |
######################################################################
# Deal with Borders
#' @export
#' @rdname Border
is.Border <- function(x) inherits(x, "Border")
######################################################################
# Create a Border. It needs a workbook object!
# - color is an R color string.
#
#' Create an Border object.
#'
#' Create an Border object, useful when working with cell styles.
#'
#' The values for the color, position, or pen arguments are replicated to the
#' longest of them.
#'
#' @param color a character vector specifiying the font color. Any color names
#' as returned by \code{\link[grDevices]{colors}} can be used. Or, a hex
#' character, e.g. "#FF0000" for red. For Excel 95 workbooks, only a subset of
#' colors is available, see the constant \code{INDEXED_COLORS_}.
#' @param position a character vector specifying the border position. Valid
#' values are "BOTTOM", "LEFT", "TOP", "RIGHT".
#' @param pen a character vector specifying the pen style. Valid values come
#' from constant \code{BORDER_STYLES_}.
#' @param x An Border object, as returned by \code{Border}.
#' @return \code{Border} returns a list with components from the input
#' argument, and a class attribute "Border". Border objects are used when
#' constructing cell styles.
#'
#' \code{is.Border} returns \code{TRUE} if the argument is of class "Border"
#' and \code{FALSE} otherwise.
#' @author Adrian Dragulescu
#' @seealso \code{\link{CellStyle}} for using the a \code{Border} object.
#' @examples
#'
#'
#' border <- Border(color="red", position=c("TOP", "BOTTOM"),
#' pen=c("BORDER_THIN", "BORDER_THICK"))
#'
#' @export
Border <- function(color="black", position="BOTTOM", pen="BORDER_THIN")
{
if (any(!(position %in% c("BOTTOM", "LEFT", "TOP", "RIGHT"))))
stop("Not a valid postion value. See help page.")
if (any(!(pen %in% names(BORDER_STYLES_))))
stop("Not a valid pen value. See help page.")
len <- c(length(position), length(color), length(pen))
if (length(color) < max(len))
color <- rep(color, length.out=max(len))
if (length(position) < max(len))
position <- rep(position, length.out=max(len))
if (length(pen) < max(len))
pen <- rep(pen, length.out=max(len))
structure(list(color=color, position=position, pen=pen),
class="Border")
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/Border.R |
#' Functions to manipulate cells.
#'
#' Functions to manipulate cells.
#'
#' \code{setCellValue} writes the content of an R variable into the cell.
#' \code{Date} and \code{POSIXct} objects are passed in as numerical values.
#' To format them as dates in Excel see \code{\link{CellStyle}}.
#'
#' These functions are not vectorized and should be used only for small
#' spreadsheets. Use \code{CellBlock} functionality to efficiently read/write
#' parts of a spreadsheet.
#'
#' @param row a list of row objects. See \code{Row}.
#' @param colIndex a numeric vector specifying the index of columns.
#' @param simplify a logical value. If \code{TRUE}, the result will be
#' unlisted.
#' @param value an R variable of length one.
#' @param richTextString a logical value indicating if the value should be
#' inserted into the Excel cell as rich text.
#' @param showNA a logical value. If \code{TRUE} the cell will contain the
#' "#N/A" value, if \code{FALSE} they will be skipped. The default value was
#' chosen to remain compatible with previous versions of the function.
#' @param keepFormulas a logical value. If \code{TRUE} the formulas will be
#' returned as characters instead of being explicitly evaluated.
#' @param encoding A character value to set the encoding, for example "UTF-8".
#' @param cell a \code{Cell} object.
#' @return
#'
#' \code{createCell} creates a matrix of lists, each element of the list being
#' a java object reference to an object of type Cell representing an empty
#' cell. The dimnames of this matrix are taken from the names of the rows and
#' the \code{colIndex} variable.
#'
#' \code{getCells} returns a list of java object references for all the cells
#' in the row if \code{colIndex} is \code{NULL}. If you want to extract only a
#' specific columns, set \code{colIndex} to the column indices you are
#' interested.
#'
#' \code{getCellValue} returns the value in the cell as an R object. Type
#' conversions are done behind the scene. This function is not vectorized.
#' @author Adrian Dragulescu
#' @seealso To format cells, see \code{\link{CellStyle}}. For rows see
#' \code{\link{Row}}, for sheets see \code{\link{Sheet}}.
#' @examples
#'
#'
#' file <- system.file("tests", "test_import.xlsx", package = "xlsx")
#'
#' wb <- loadWorkbook(file)
#' sheets <- getSheets(wb)
#'
#' sheet <- sheets[['mixedTypes']] # get second sheet
#' rows <- getRows(sheet) # get all the rows
#'
#' cells <- getCells(rows) # returns all non empty cells
#'
#' values <- lapply(cells, getCellValue) # extract the values
#'
#' # write the months of the year in the first column of the spreadsheet
#' ind <- paste(2:13, ".2", sep="")
#' mapply(setCellValue, cells[ind], month.name)
#'
#' ####################################################################
#' # make a new workbook with one sheet and 5x5 cells
#' wb <- createWorkbook()
#' sheet <- createSheet(wb, "Sheet1")
#' rows <- createRow(sheet, rowIndex=1:5)
#' cells <- createCell(rows, colIndex=1:5)
#'
#' # populate the first column with Dates
#' days <- seq(as.Date("2013-01-01"), by="1 day", length.out=5)
#' mapply(setCellValue, cells[,1], days)
#'
#'
#'
#' @name Cell
NULL
######################################################################
# Create some cells in the row object. "cell" is the index of columns.
# You can pass in a list of rows.
# Return a matrix of lists. Each element is a cell object.
#' @export
#' @rdname Cell
createCell <- function(row, colIndex=1:5)
{
cells <- matrix(list(), nrow=length(row), ncol=length(colIndex),
dimnames=list(names(row), colIndex))
for (ir in seq_along(row))
for (ic in seq_along(colIndex))
cells[[ir,ic]] <- .jcall(row[[ir]], "Lorg/apache/poi/ss/usermodel/Cell;",
"createCell", as.integer(colIndex[ic]-1))
cells
}
######################################################################
# Get the cells for a list of rows. Users who want basic things only
# don't need to use this function.
#
#' @export
#' @rdname Cell
getCells <- function(row, colIndex=NULL, simplify=TRUE)
{
nC <- length(colIndex)
if (!is.null(colIndex))
colIx <- as.integer(colIndex-1) # ugly, have to do it here
res <- row
for (ir in seq_along(row)){
if (is.null(colIndex)){ # get all columns
minColIx <- .jcall(row[[ir]], "T", "getFirstCellNum") # 0-based
maxColIx <- .jcall(row[[ir]], "T", "getLastCellNum")-1 # 0-based
# actual col index; if the row is empty do nothing
colIx <- if (minColIx < 0) numeric(0) else seq.int(minColIx, maxColIx)
}
nC <- length(colIx)
rowCells <- vector("list", length=nC)
namesCells <- vector("character", length=nC)
for (ic in seq_along(rowCells)){
aux <- .jcall(row[[ir]], "Lorg/apache/poi/ss/usermodel/Cell;",
"getCell", colIx[ic])
if (!is.null(aux)){
rowCells[[ic]] <- aux
namesCells[ic] <- .jcall(aux, "I", "getColumnIndex")+1
}
}
names(rowCells) <- namesCells # need namesCells if spreadsheet is ragged
res[[ir]] <- rowCells
}
if (simplify)
res <- unlist(res)
res
}
######################################################################
# Only one cell and one value.
# You vectorize outside this function if you want.
#
# Date = .jnew("java/text/SimpleDateFormat",
# "yyyy-MM-dd")$parse(as.character(value)), # does not format it!
#
#' @export
#' @rdname Cell
setCellValue <- function(cell, value, richTextString=FALSE, showNA=TRUE)
{
if (is.na(value)) {
if (showNA) {
return(invisible(.jcall(cell, "V", "setCellErrorValue", .jbyte(42))))
} else { return(invisible()) }
}
value <- switch(class(value)[1],
integer = as.numeric(value),
numeric = value,
Date = as.numeric(value) + 25569, # add Excel origin
POSIXct = as.numeric(value)/86400 + 25569,
as.character(value)) # for factors and other types
if (richTextString)
value <- .jnew("org/apache/poi/sf/usermodel/RichTextString",
as.character(value)) # do I need to convert to as.character ?!!
invisible(.jcall(cell, "V", "setCellValue", value))
}
######################################################################
# get cell value. ONE cell only
# Not happy with the case when you have formulas. Still not general
# enough. We'll see how many things still not work.
#
#' @export
#' @rdname Cell
getCellValue <- function(cell, keepFormulas=FALSE, encoding="unknown")
{
cellType <- .jcall(cell, "I", "getCellType") + 1
value <- switch(cellType,
.jcall(cell, "D", "getNumericCellValue"), # 1 = numeric
{strVal <- .jcall(.jcall(cell, # 2 = string
"Lorg/apache/poi/ss/usermodel/RichTextString;",
"getRichStringCellValue"), "S", "toString");
if (encoding=="unknown") {strVal} else {Encoding(strVal) <- encoding; strVal}
},
ifelse(keepFormulas, .jcall(cell, "S", "getCellFormula"), # if a formula
tryCatch(.jcall(cell, "D", "getNumericCellValue"), # try to extract
error=function(e){ # contents
tryCatch(.jcall(cell, "S", "getStringCellValue"),
error=function(e){
tryCatch(.jcall(cell, "Z", "getBooleanCellValue"),
error=function(e)e,
finally=NA)
}, finally=NA)
}, finally=NA)
),
NA, # blank cell
.jcall(cell, "Z", "getBooleanCellValue"), # boolean
NA, #ifelse(keepErrors, .jcall(cell, "B", "getErrorCellValue"), NA), # error
"Error" # catch all
)
value
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/Cell.R |
# Cell Block functionality. This is to be used when writing to a spreadsheet.
#
#
#' Create and style a block of cells.
#'
#' Functions to create and style (not read) a block of cells. Use it to
#' set/update cell values and cell styles in an efficient manner.
#'
#'
#' Introduced in version 0.5.0 of the package, these functions speed up the
#' creation and styling of cells that are part of a "cell block" (a rectangular
#' shaped group of cells). Use the functions above if you want to create
#' efficiently a complex sheet with many styles. A simple by-column styling
#' can be done by directly using \code{\link{addDataFrame}}. With the
#' functionality provided here you can efficiently style individual cells, see
#' the example.
#'
#' It is difficult to treat \code{NA}'s consistently between R and Excel via
#' Java. Most likely, users of Excel will want to see \code{NA}'s as blank
#' cells. In R character \code{NA}'s are simply characters, which for Excel
#' means "NA".
#'
#' If you try to set more data to the block than you have cells in the block,
#' only the existing cells will be set.
#'
#' Note that when modifying the style of a group of cells, the changes are made
#' to the pairs defined by \code{(rowIndex, colIndex)}. This implies that the
#' length of \code{rowIndex} and \code{colIndex} are the same value. An
#' exception is made when either \code{rowIndex} or \code{colIndex} have length
#' one, when they will be expanded internally to match the length of the other
#' index.
#'
#' Function \code{CB.setMatrixData} works for numeric or character matrices.
#' If the matrix \code{x} is not of numeric type it will be converted to a
#' character matrix.
#'
#' @param sheet a \code{\link{Sheet}} object.
#' @param startRow a numeric value for the starting row.
#' @param startColumn a numeric value for the starting column.
#' @param rowOffset a numeric value for the starting row.
#' @param colOffset a numeric value for the starting column.
#' @param showNA a logical value. If set to \code{FALSE}, NA values will be
#' left as empty cells.
#' @param noRows a numeric value to specify the number of rows for the block.
#' @param noColumns a numeric value to specify the number of columns for the
#' block.
#' @param create If \code{TRUE} cells will be created if they don't exist, if
#' \code{FALSE} only existing cells will be used. If cells don't exist (on a
#' new sheet for example), you have to use \code{TRUE}. On an existing sheet
#' with data, use \code{TRUE} if you want to blank out an existing cell block.
#' Use \code{FALSE} if you want to keep the styling of existing cells, but just
#' modify the value of the cell.
#' @param cellBlock a cell block object as returned by \code{\link{CellBlock}}.
#' @param rowStyle a \code{\link{CellStyle}} object used to style the row.
#' @param colStyle a \code{\link{CellStyle}} object used to style the column.
#' @param cellStyle a \code{\link{CellStyle}} object.
#' @param border a Border object, as returned by \code{\link{Border}}.
#' @param fill a Fill object, as returned by \code{\link{Fill}}.
#' @param font a Font object, as returned by \code{\link{Font}}.
#' @param colIndex a numeric vector specifiying the columns you want relative
#' to the \code{startColumn}.
#' @param rowIndex a numeric vector specifiying the rows you want relative to
#' the \code{startRow}.
#' @param x the data you want to add to the cell block, a vector or a matrix
#' depending on the function.
#' @return For \code{CellBlock} a cell block object.
#'
#' For \code{CB.setColData}, \code{CB.setRowData}, \code{CB.setMatrixData},
#' \code{CB.setFill}, \code{CB.setFont}, \code{CB.setBorder} nothing as he
#' modification to the workbook is done in place.
#' @author Adrian Dragulescu
#' @examples
#'
#' \donttest{
#' wb <- createWorkbook()
#' sheet <- createSheet(wb, sheetName="CellBlock")
#'
#' cb <- CellBlock(sheet, 7, 3, 1000, 60)
#' CB.setColData(cb, 1:100, 1) # set a column
#' CB.setRowData(cb, 1:50, 1) # set a row
#'
#' # add a matrix, and style it
#' cs <- CellStyle(wb) + DataFormat("#,##0.00")
#' x <- matrix(rnorm(900*45), nrow=900)
#' CB.setMatrixData(cb, x, 10, 4, cellStyle=cs)
#'
#' # highlight the negative numbers in red
#' fill <- Fill(foregroundColor = "red", backgroundColor="red")
#' ind <- which(x < 0, arr.ind=TRUE)
#' CB.setFill(cb, fill, ind[,1]+9, ind[,2]+3) # note the indices offset
#'
#' # set the border on the top row of the Cell Block
#' border <- Border(color="blue", position=c("TOP", "BOTTOM"),
#' pen=c("BORDER_THIN", "BORDER_THICK"))
#' CB.setBorder(cb, border, 1, 1:1000)
#'
#'
#' # Don't forget to save the workbook ...
#' # saveWorkbook(wb, file)
#' }
#'
#' @export
CellBlock <- function(sheet, startRow, startColumn, noRows, noColumns,
create=TRUE) UseMethod("CellBlock")
#' @export
#' @rdname CellBlock
is.CellBlock <- function(cellBlock) {inherits(cellBlock, "CellBlock")}
#########################################################################
# Create a cell block
#
#' @export
#' @rdname CellBlock
CellBlock.default <- function(sheet, startRow, startColumn, noRows, noColumns,
create=TRUE)
{
cb <- new(J("org/cran/rexcel/RCellBlock"), sheet, as.integer(startRow-1),
as.integer(startColumn-1), as.integer(noRows), as.integer(noColumns),
create)
structure(list(ref=cb), class="CellBlock")
}
#########################################################################
# set the column data for a Cell Block
#
#' @export
#' @rdname CellBlock
CB.setColData <- function(cellBlock, x, colIndex, rowOffset=0, showNA=TRUE,
colStyle=NULL)
{
.jcall( cellBlock$ref, "V", "setColData", as.integer(colIndex-1),
as.integer(rowOffset), .jarray(x), showNA,
if ( !is.null(colStyle) ) colStyle$ref else
.jnull('org/apache/poi/ss/usermodel/CellStyle') )
}
#########################################################################
# set the row data for a Cell Block
#
#' @export
#' @rdname CellBlock
CB.setRowData <- function(cellBlock, x, rowIndex, colOffset=0, showNA=TRUE,
rowStyle=NULL)
{
.jcall( cellBlock$ref, "V", "setRowData", as.integer(rowIndex-1),
as.integer(colOffset), .jarray(as.character(x)), showNA,
if ( !is.null(rowStyle) ) rowStyle$ref else
.jnull('org/apache/poi/ss/usermodel/CellStyle') )
}
#########################################################################
# set a matrix of data for a Cell Block.
# if x is not a numeric matrix, coerce it a character matrix
#
#' @export
#' @rdname CellBlock
CB.setMatrixData <- function(cellBlock, x, startRow, startColumn,
showNA=TRUE, cellStyle=NULL)
{
endRow <- startRow + dim(x)[1] - 1
endColumn <- startColumn + dim(x)[2] - 1
if ( (endRow-startRow+1) > .jfield(cellBlock$ref, "I", "noRows") )
stop("The rows of x don't fit in the cellBlock!")
if ( (endColumn-startColumn+1) > .jfield(cellBlock$ref, "I", "noCols") )
stop("The columns of x don't fit in the cellBlock!")
if (class(x[1,1])[1] == "numeric") {
.jcall( cellBlock$ref, "V", "setMatrixData", as.integer(startRow-1),
as.integer(endRow-1), as.integer(startColumn-1), as.integer(endColumn-1),
.jarray(x), showNA,
if ( !is.null(cellStyle) ) cellStyle$ref else
.jnull('org/apache/poi/ss/usermodel/CellStyle') )
} else {
.jcall( cellBlock$ref, "V", "setMatrixData", as.integer(startRow-1),
as.integer(endRow-1), as.integer(startColumn-1), as.integer(endColumn-1),
.jarray(as.character(x)), showNA,
if ( !is.null(cellStyle) ) cellStyle$ref else
.jnull('org/apache/poi/ss/usermodel/CellStyle') )
}
}
#########################################################################
# set the Fill for an array of indices of a Cell Block
#
#' @export
#' @rdname CellBlock
CB.setFill <- function( cellBlock, fill, rowIndex, colIndex)
{
if (length(colIndex)==1 & length(rowIndex) > 1)
colIndex <- rep(colIndex, length(rowIndex))
if (length(rowIndex)==1 & length(colIndex) > 1)
rowIndex <- rep(rowIndex, length(colIndex))
if (length(rowIndex) != length(colIndex))
stop("rowIndex and colIndex arguments don't have the same length!")
if ( cellBlock$ref$isXSSF() ) {
.jcall( cellBlock$ref, 'V', 'setFill',
.xssfcolor( fill$foregroundColor ),
.xssfcolor( fill$backgroundColor ),
.jshort(FILL_STYLES_[[fill$pattern]]),
.jarray( as.integer( rowIndex-1 ) ),
.jarray( as.integer( colIndex-1 ) ) )
} else {
.jcall( cellBlock$ref, 'V', 'setFill',
.hssfcolor( fill$foregroundColor ),
.hssfcolor( fill$backgroundColor ),
.jshort(FILL_STYLES_[[fill$pattern]]),
.jarray( as.integer( rowIndex-1 ) ),
.jarray( as.integer( colIndex-1 ) ) )
}
invisible()
}
#########################################################################
# set the Font for an array of indices of a Cell Block
#
#' @export
#' @rdname CellBlock
CB.setFont <- function( cellBlock, font, rowIndex, colIndex )
{
if (length(colIndex)==1 & length(rowIndex) > 1)
colIndex <- rep(colIndex, length(rowIndex))
if (length(rowIndex)==1 & length(colIndex) > 1)
rowIndex <- rep(rowIndex, length(colIndex))
if (length(rowIndex) != length(colIndex))
stop("rowIndex and colIndex arguments don't have the same length!")
.jcall( cellBlock$ref, 'V', 'setFont', font$ref,
.jarray( as.integer( rowIndex-1 ) ),
.jarray( as.integer( colIndex-1 ) ) )
invisible()
}
#########################################################################
# set the Border for an array of indices of a Cell Block
#
#' @export
#' @rdname CellBlock
CB.setBorder <- function( cellBlock, border, rowIndex, colIndex)
{
if (length(colIndex)==1 & length(rowIndex) > 1)
colIndex <- rep(colIndex, length(rowIndex))
if (length(rowIndex)==1 & length(colIndex) > 1)
rowIndex <- rep(rowIndex, length(colIndex))
if (length(rowIndex) != length(colIndex))
stop("rowIndex and colIndex arguments don't have the same length!")
isXSSF <- .jcall( cellBlock$ref, 'Z', 'isXSSF' )
border_none <- BORDER_STYLES_[['BORDER_NONE']]
borders <- c( TOP = border_none,
BOTTOM = border_none,
LEFT = border_none,
RIGHT = border_none )
borders[ border$position ] <- sapply( border$pen,
function( pen ) BORDER_STYLES_[pen] )
null_color <- if (isXSSF) {
.jnull('org/apache/poi/xssf/usermodel/XSSFColor')
} else {
0
}
border_colors <- c( TOP = null_color,
BOTTOM = null_color,
LEFT = null_color,
RIGHT = null_color )
border_colors[ border$position ] <- .Rcolor2XLcolor( border$color, isXSSF)
if ( isXSSF ) {
.jcall( cellBlock$ref, "V", "putBorder",
.jshort(borders[['TOP']]), border_colors[['TOP']],
.jshort(borders[['BOTTOM']]), border_colors[['BOTTOM']],
.jshort(borders[['LEFT']]), border_colors[['LEFT']],
.jshort(borders[['RIGHT']]), border_colors[['RIGHT']],
.jarray( as.integer( rowIndex-1L ) ),
.jarray( as.integer( colIndex-1L ) ) )
} else {
.jcall( cellBlock$ref, "V", "putBorder",
.jshort(borders[['TOP']]), .jshort(border_colors[['TOP']]),
.jshort(borders[['BOTTOM']]), .jshort(border_colors[['BOTTOM']]),
.jshort(borders[['LEFT']]), .jshort(border_colors[['LEFT']]),
.jshort(borders[['RIGHT']]), .jshort(border_colors[['RIGHT']]),
.jarray( as.integer( rowIndex-1L ) ),
.jarray( as.integer( colIndex-1L ) ) )
}
invisible()
}
############################################################################
# get reference to java cell object by its CellBlock row and column indices
# DON'T NEED TO EXPOSE THIS it's just: cb$ref$getCell(1L, 1L)
## CB.getCell <- function( cellBlock, rowIndex, colIndex )
## {
## invisible(
## .jcall( cellBlock$ref, 'Lorg/apache/poi/ss/usermodel/Cell;', 'getCell',
## rowIndex - 1L, colIndex - 1L ) )
## }
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/CellBlock.R |
######################################################################
# Deal with CellProtection
#' @rdname CellProtection
#' @export
is.CellProtection <- function(x) inherits(x, "CellProtection")
######################################################################
# Create an CellProtection
#
#' Create a CellProtection object.
#'
#' Create a CellProtection object used for cell styles.
#'
#' @param locked a logical indicating the cell is locked.
#' @param hidden a logical indicating the cell is hidden.
#' @param x A CellProtection object, as returned by \code{CellProtection}.
#' @return
#'
#' \code{CellProtection} returns a list with components from the input
#' argument, and a class attribute "CellProtection". CellProtection objects
#' are used when constructing cell styles.
#'
#' \code{is.CellProtection} returns \code{TRUE} if the argument is of class
#' "CellProtection" and \code{FALSE} otherwise.
#' @author Adrian Dragulescu
#' @seealso \code{\link{CellStyle}} for using the a \code{CellProtection}
#' object.
#' @examples
#'
#'
#' font <- CellProtection(locked=TRUE)
#'
#' @export
CellProtection <- function(locked=TRUE, hidden=FALSE)
{
structure(list(locked=locked, hidden=hidden),
class="CellProtection")
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/CellProtection.R |
######################################################################
# Create a cell style. It needs a workbook object!
#
#' Functions to manipulate cells.
#'
#' Create and set cell styles.
#'
#' \code{setCellStyle} sets the \code{CellStyle} to one \code{Cell} object.
#'
#' You need to have a \code{Workbook} object to attach a \code{CellStyle}
#' object to it.
#'
#' Since OS X 10.5 Apple dropped support for AWT on the main thread, so
#' essentially you cannot use any graphics classes in R on OS X 10.5 since R is
#' single-threaded. (verbatim from Simon Urbanek). This implies that setting
#' colors on Mac will not work as is! A set of about 50 basic colors are still
#' available please see the javadocs.
#'
#' For Excel 95/2000/XP/2003 the choice of colors is limited. See
#' \code{INDEXED_COLORS_} for the list of available colors.
#'
#' Unspecified values for arguments are taken from the system locale.
#'
#' @param wb a workbook object as returned by \code{\link{createWorkbook}} or
#' \code{\link{loadWorkbook}}.
#' @param dataFormat a \code{\link{DataFormat}} object.
#' @param alignment a \code{\link{Alignment}} object.
#' @param border a \code{\link{Border}} object.
#' @param fill a \code{\link{Fill}} object.
#' @param font a \code{\link{Font}} object.
#' @param cellProtection a \code{\link{CellProtection}} object.
#' @param x a \code{CellStyle} object.
#' @param cell a \code{\link{Cell}} object.
#' @param cellStyle a \code{CellStyle} object.
#' @return
#'
#' \code{createCellStyle} creates a CellStyle object.
#'
#' \code{is.CellStyle} returns \code{TRUE} if the argument is of class
#' "CellStyle" and \code{FALSE} otherwise.
#' @author Adrian Dragulescu
#' @examples
#'
#' \dontrun{
#' wb <- createWorkbook()
#' sheet <- createSheet(wb, "Sheet1")
#'
#' rows <- createRow(sheet, rowIndex=1)
#'
#' cell.1 <- createCell(rows, colIndex=1)[[1,1]]
#' setCellValue(cell.1, "Hello R!")
#'
#' cs <- CellStyle(wb) +
#' Font(wb, heightInPoints=20, isBold=TRUE, isItalic=TRUE,
#' name="Courier New", color="orange") +
#' Fill(backgroundColor="lavender", foregroundColor="lavender",
#' pattern="SOLID_FOREGROUND") +
#' Alignment(h="ALIGN_RIGHT")
#'
#' setCellStyle(cell.1, cellStyle1)
#'
#' # you need to save the workbook now if you want to see this art
#' }
#' @export
#' @name CellStyle
CellStyle <- function(wb, dataFormat=NULL, alignment=NULL,
border=NULL, fill=NULL, font=NULL, cellProtection=NULL) UseMethod("CellStyle")
#' @export
#' @rdname CellStyle
is.CellStyle <- function(x) {inherits(x, "CellStyle")}
######################################################################
# Create a cell style. It needs a workbook object!
#
#' @export
#' @rdname CellStyle
CellStyle.default <- function(wb, dataFormat=NULL, alignment=NULL,
border=NULL, fill=NULL, font=NULL, cellProtection=NULL)
{
if ((!is.null(dataFormat)) & (!inherits(dataFormat, "DataFormat")))
stop("Argument dataFormat needs to be of class DataFormat.")
if ((!is.null(alignment)) & (!inherits(alignment, "Alignment")))
stop("Argument alignment needs to be of class Alignment.")
if ((!is.null(border)) & (!inherits(border, "Border")))
stop("Argument border needs to be of class Border.")
if ((!is.null(fill)) & (!inherits(fill, "Fill")))
stop("Argument fill needs to be of class Fill.")
if ((!is.null(font)) & (!inherits(font, "Font")))
stop("Argument font needs to be of class Font.")
cellStyle <- .jcall(wb, "Lorg/apache/poi/ss/usermodel/CellStyle;",
"createCellStyle")
CS <- CELL_STYLES_
if (!is.null(dataFormat)){
fmt <- .jcall(wb, "Lorg/apache/poi/ss/usermodel/DataFormat;",
"createDataFormat")
.jcall(cellStyle, "V", "setDataFormat",
.jshort(fmt$getFormat(dataFormat$dataFormat)))
}
# the alignment
if (!is.null(alignment)) {
if (!is.null(alignment$horizontal))
.jcall(cellStyle, "V", "setAlignment", .jshort(CS[alignment$horizontal]))
if (!is.null(alignment$vertical))
.jcall(cellStyle, "V", "setVerticalAlignment", .jshort(CS[alignment$vertical]))
if (alignment$wrapText)
.jcall(cellStyle, "V", "setWrapText", TRUE)
if (alignment$rotation != 0)
.jcall(cellStyle, "V", "setRotation", .jshort(alignment$rotation))
if (alignment$indent != 0)
.jcall(cellStyle, "V", "setIndention", .jshort(alignment$indent))
}
# the border
if (!is.null(border)) {
for (i in 1:length(border$position)) {
bcolor <- if (grepl("XSSF", wb$getClass()$getName())) {
.xssfcolor(border$color[i])
} else {
idcol <- INDEXED_COLORS_[toupper(border$color[i])]
.jshort(idcol)
}
switch(border$position[i],
BOTTOM = {
.jcall(cellStyle, "V", "setBorderBottom",.jshort(CS[border$pen[i]]))
.jcall(cellStyle, "V", "setBottomBorderColor", bcolor)
},
LEFT = {
.jcall(cellStyle, "V", "setBorderLeft", .jshort(CS[border$pen[i]]))
.jcall(cellStyle, "V", "setLeftBorderColor", bcolor)
},
TOP = {
.jcall(cellStyle, "V", "setBorderTop", .jshort(CS[border$pen[i]]))
.jcall(cellStyle, "V", "setTopBorderColor", bcolor)
},
RIGHT = {
.jcall(cellStyle, "V", "setBorderRight",.jshort(CS[border$pen[i]]))
.jcall(cellStyle, "V", "setRightBorderColor", bcolor)
}
)
}
}
# the fill
if (!is.null(fill)) {
isXSSF <-grepl("XSSF", wb$getClass()$getName())
if (isXSSF) {
.jcall(cellStyle, "V", "setFillForegroundColor",
.xssfcolor(fill$foregroundColor))
.jcall(cellStyle, "V", "setFillBackgroundColor",
.xssfcolor(fill$backgroundColor))
} else {
.jcall(cellStyle, "V", "setFillForegroundColor",
.jshort(INDEXED_COLORS_[toupper(fill$foregroundColor)]))
.jcall(cellStyle, "V", "setFillBackgroundColor",
.jshort(INDEXED_COLORS_[toupper(fill$backgroundColor)]))
}
.jcall(cellStyle, "V", "setFillPattern", .jshort(CS[fill$pattern]))
}
if (!is.null(font))
.jcall(cellStyle, "V", "setFont", font$ref)
if (!is.null(cellProtection)) {
.jcall(cellStyle, "V", "setHidden", cellProtection$hidden)
.jcall(cellStyle, "V", "setLocked", cellProtection$locked)
}
structure(list(ref=cellStyle, wb=wb, dataFormat=dataFormat,
alignment=alignment, border=border, fill=fill, font=font,
cellProtection=cellProtection),
class="CellStyle")
}
######################################################################
#
#' CellStyle construction.
#'
#' Create cell styles.
#'
#' The style of the argument object takes precedence over the style of argument
#' cs1.
#'
#' @param cs1 a \code{\link{CellStyle}} object.
#' @param object an object to add. The object can be another
#' \code{\link{CellStyle}}, a \code{\link{DataFormat}}, a
#' \code{\link{Alignment}}, a \code{\link{Border}}, a \code{\link{Fill}}, a
#' \code{\link{Font}}, or a \code{\link{CellProtection}} object.
#' @return A CellStyle object.
#' @author Adrian Dragulescu
#' @examples
#'
#' \dontrun{
#' cs <- CellStyle(wb) +
#' Font(wb, heightInPoints=20, isBold=TRUE, isItalic=TRUE,
#' name="Courier New", color="orange") +
#' Fill(backgroundColor="lavender", foregroundColor="lavender",
#' pattern="SOLID_FOREGROUND") +
#' Alignment(h="ALIGN_RIGHT")
#'
#' setCellStyle(cell.1, cellStyle1)
#'
#' # you need to save the workbook now if you want to see this art
#' }
#'
#' @export
#' @name CellStyle-plus
"+.CellStyle" <- function(cs1, object)
{
if (is.null(object)) return(cs1)
cs <- if (is.CellStyle(object)) {
dataFormat <- if (is.null(object$dataFormat)){cs1$dataFormat}
alignment <- if (is.null(object$alignment)){cs1$aligment}
border <- if (is.null(object$border)){cs1$border}
fill <- if (is.null(object$fill)){cs1$fill}
font <- if (is.null(object$font)){cs1$font}
cellProtection <- if (is.null(object$cellProtection)){cs1$cellProtection}
CellStyle.default(object$wb, dataFormat=dataFormat,
alignment=alignment, border=border, fill=fill,
font=font, cellProtection=cellProtection)
} else if (is.DataFormat(object)) {
CellStyle.default(cs1$wb, dataFormat=object,
alignment=cs1$alignment, border=cs1$border, fill=cs1$fill,
font=cs1$font, cellProtection=cs1$cellProtection)
} else if (is.Alignment(object)) {
CellStyle.default(cs1$wb, dataFormat=cs1$dataFormat,
alignment=object, border=cs1$border, fill=cs1$fill,
font=cs1$font, cellProtection=cs1$cellProtection)
} else if (is.Border(object)) {
CellStyle.default(cs1$wb, dataFormat=cs1$dataFormat,
alignment=cs1$alignment, border=object, fill=cs1$fill,
font=cs1$font, cellProtection=cs1$cellProtection)
} else if (is.Fill(object)) {
CellStyle.default(cs1$wb, dataFormat=cs1$dataFormat,
alignment=cs1$alignment, border=cs1$border, fill=object,
font=cs1$font, cellProtection=cs1$cellProtection)
} else if (is.Font(object)) {
CellStyle.default(cs1$wb, dataFormat=cs1$dataFormat,
alignment=cs1$alignment, border=cs1$border, fill=cs1$fill,
font=object, cellProtection=cs1$cellProtection)
} else if (is.CellProtection(object)) {
CellStyle.default(cs1$wb, dataFormat=cs1$dataFormat,
alignment=cs1$alignment, border=cs1$border, fill=cs1$fill,
font=cs1$font, cellProtection=object)
} else {
stop("Don't know how to add ", deparse(substitute(object)), " to a plot",
call. = FALSE)
}
cs
}
## ######################################################################
## # Set the cell style for one cell.
## # Only one cell and one value.
## #
## setCellStyle <- function(x, cellStyle, ...)
## UseMethod("setCellStyle", x)
######################################################################
# Set the cell style for one cell.
# Only one cell and one value.
#
#' @export
#' @rdname CellStyle
setCellStyle <- function(cell, cellStyle)
{
.jcall(cell, "V", "setCellStyle", cellStyle$ref)
invisible(NULL)
}
## # for a CellBlock - NOT USED FOR NOW
## setCellStyle.CellBlock <- function(cellBlock, cellStyle, rowIndex=NULL,
## colIndex=NULL)
## {
## if (is.null(rowIndex) & is.null(colIndex)) {
## cellBlock$setCellStyle( style ) # apply it to all the cells
## } else {
## cellBlock$setCellStyle( style, .jarray( as.integer( rowIndex-1L ) ),
## .jarray( as.integer( colIndex-1L ) ) )
## }
## invisible()
## }
######################################################################
# Get the cell style for one cell.
# Only one cell and one value.
#
#' @export
#' @rdname CellStyle
getCellStyle <- function(cell)
{
.jcall(cell, "Lorg/apache/poi/ss/usermodel/CellStyle;", "getCellStyle")
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/CellStyle.R |
######################################################################
# Deal with Format properties for cells, needed for CellStyle
#' @export
#' @rdname DataFormat
is.DataFormat <- function(df) inherits(df, "DataFormat")
######################################################################
# Create a DataFormat
# maybe allow to change the Locale
# .jfield("java/util/Locale", "Ljava/util/Locale;","FRENCH")
# https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html
#' Create an DataFormat object.
#'
#' Create an DataFormat object, useful when working with cell styles.
#'
#' Specifying the \code{dataFormat} argument allows you to format the cell.
#' For example, "#,##0.00" corresponds to using a comma separator for powers of
#' 1000 with two decimal places, "m/d/yyyy" can be used to format dates and is
#' the equivalent of 's MM/DD/YYYY format. To format datetimes use "m/d/yyyy
#' h:mm:ss;@". To show negative values in red within parantheses with two
#' decimals and commas after power of 1000 use "#,##0.00_);[Red](#,##0.00)". I
#' am not aware of an official way to discover these strings. I find them out
#' by recording a macro that formats a specific cell and then checking out the
#' resulting VBA code. From there you can read the \code{dataFormat} code.
#'
#' @param x a character value specifying the data format.
#' @param df An DataFormat object, as returned by \code{DataFormat}.
#' @return \code{DataFormat} returns a list one component dataFormat, and a
#' class attribute "DataFormat". DataFormat objects are used when constructing
#' cell styles.
#'
#' \code{is.DataFormat} returns \code{TRUE} if the argument is of class
#' "DataFormat" and \code{FALSE} otherwise.
#' @author Adrian Dragulescu
#' @seealso \code{\link{CellStyle}} for using the a \code{DataFormat} object.
#' @examples
#'
#' df <- DataFormat("#,##0.00")
#'
#' @export
DataFormat <- function(x)
{
structure(list(dataFormat=as.character(x)),
class="DataFormat")
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/DataFormat.R |
# This file defines Excel specific constants
.EXCEL_LIMIT_MAX_CHARS_IN_CELL <- 32767
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/ExcelConstants.R |
######################################################################
# Deal with Fill properties for cells
#' @export
#' @rdname Fill
is.Fill <- function(x) inherits(x, "Fill")
######################################################################
# Create a Fill.
# - colors is an R color string.
#
#' Create an Fill object.
#'
#' Create an Fill object, useful when working with cell styles.
#'
#' @param foregroundColor a character vector specifiying the foreground color.
#' Any color names as returned by \code{\link[grDevices]{colors}} can be used.
#' Or, a hex character, e.g. "#FF0000" for red. For Excel 95 workbooks, only a
#' subset of colors is available, see the constant \code{INDEXED_COLORS_}.
#' @param backgroundColor a character vector specifiying the foreground color.
#' Any color names as returned by \code{\link[grDevices]{colors}} can be used.
#' Or, a hex character, e.g. "#FF0000" for red. For Excel 95 workbooks, only a
#' subset of colors is available, see the constant \code{INDEXED_COLORS_}.
#' @param pattern a character vector specifying the fill pattern style. Valid
#' values come from constant \code{FILL_STYLES_}.
#' @param x a Fill object, as returned by \code{Fill}.
#' @return \code{Fill} returns a list with components from the input argument,
#' and a class attribute "Fill". Fill objects are used when constructing cell
#' styles.
#'
#' \code{is.Fill} returns \code{TRUE} if the argument is of class "Fill" and
#' \code{FALSE} otherwise.
#' @author Adrian Dragulescu
#' @seealso \code{\link{CellStyle}} for using the a \code{Fill} object.
#' @examples
#'
#' fill <- Fill()
#'
#' @export
Fill <- function(foregroundColor="lightblue", backgroundColor="lightblue",
pattern="SOLID_FOREGROUND")
{
if (!(pattern %in% names(FILL_STYLES_)))
stop("Not a valid pattern value. See help page.")
structure(list(foregroundColor=foregroundColor,
backgroundColor=backgroundColor, pattern=pattern),
class="Fill")
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/Fill.R |
######################################################################
# Deal with Fonts
#' @export
#' @rdname Font
is.Font <- function(x) inherits(x, "Font")
######################################################################
# Create a Font. It needs a workbook object!
# - color is an R color string.
#
#' Create a Font object.
#'
#' Create a Font object.
#'
#' Default values for \code{NULL} parameters are taken from Excel. So the
#' default font color is black, the default font name is "Calibri", and the
#' font height in points is 11.
#'
#' For Excel 95/2000/XP/2003, it is impossible to set the font to bold. This
#' limitation may be removed in the future.
#'
#' NOTE: You need to have a \code{Workbook} object to attach a \code{Font}
#' object to it.
#'
#' @aliases Font is.Font
#' @param wb a workbook object as returned by \code{\link{createWorkbook}} or
#' \code{\link{loadWorkbook}}.
#' @param color a character specifiying the font color. Any color names as
#' returned by \code{\link[grDevices]{colors}} can be used. Or, a hex
#' character, e.g. "#FF0000" for red. For Excel 95 workbooks, only a subset of
#' colors is available, see the constant \code{INDEXED_COLORS_}.
#' @param heightInPoints a numeric value specifying the font height. Usual
#' values are 10, 12, 14, etc.
#' @param name a character value for the font to use. All values that you see
#' in Excel should be available, e.g. "Courier New".
#' @param isItalic a logical indicating the font should be italic.
#' @param isStrikeout a logical indicating the font should be stiked out.
#' @param isBold a logical indicating the font should be bold.
#' @param underline a numeric value specifying the thickness of the underline.
#' Allowed values are 0, 1, 2.
#' @param boldweight a numeric value indicating bold weight. Normal is 400,
#' regular bold is 700.
#' @param x A Font object, as returned by \code{Font}.
#' @return \code{Font} returns a list with a java reference to a \code{Font}
#' object, and a class attribute "Font".
#'
#' \code{is.Font} returns \code{TRUE} if the argument is of class "Font" and
#' \code{FALSE} otherwise.
#' @author Adrian Dragulescu
#' @seealso \code{\link{CellStyle}} for using the a \code{Font} object.
#' @examples
#'
#' \dontrun{
#' font <- Font(wb, color="blue", isItalic=TRUE)
#' }
#'
#' @export
Font <- function(wb, color=NULL, heightInPoints=NULL, name=NULL,
isItalic=FALSE, isStrikeout=FALSE, isBold=FALSE, underline=NULL,
boldweight=NULL) # , setFamily=NULL
{
font <- .jcall(wb, "Lorg/apache/poi/ss/usermodel/Font;",
"createFont")
if (!is.null(color))
if (grepl("XSSF", wb$getClass()$getName())){
.jcall(font, "V", "setColor", .xssfcolor(color))
} else {
.jcall(font, "V", "setColor",
.jshort(INDEXED_COLORS_[toupper(color)]))
}
if (!is.null(heightInPoints))
.jcall(font, "V", "setFontHeightInPoints", .jshort(heightInPoints))
if (!is.null(name))
.jcall(font, "V", "setFontName", name)
if (isItalic)
.jcall(font, "V", "setItalic", TRUE)
if (isStrikeout)
.jcall(font, "V", "setStrikeout", TRUE)
if (isBold & grepl("XSSF", wb$getClass()$getName()))
.jcall(font, "V", "setBold", TRUE)
if (!is.null(underline))
.jcall(font, "V", "setUnderline", .jbyte(underline))
if (!is.null(boldweight))
.jcall(font, "V", "setBoldweight", .jshort(boldweight))
structure(list(ref=font), class="Font")
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/Font.R |
# Functions to deal with ranges.
#
# createRange
# getRanges
# readRange
#
#############################################################################
# Set an area of a sheet to a contiguous range
#
#' Functions to manipulate (contiguous) named ranges.
#'
#' These functions are provided for convenience only. Use directly the Java
#' API to access additional functionality.
#'
#' @param wb a workbook object as returned by \code{createWorksheet} or
#' \code{loadWorksheet}.
#' @param range a range object as returned by \code{getRanges}.
#' @param sheet a sheet object as returned by \code{getSheets}.
#' @param rangeName a character specifying the name of the name to create.
#' @param colClasses the type of the columns supported. Only \code{numeric}
#' and \code{character} are supported. See \code{\link{read.xlsx2}} for more
#' details.
#' @param firstCell a cell object corresponding to the top left cell in the
#' range.
#' @param lastCell a cell object corresponding to the bottom right cell in the
#' range.
#' @return \code{getRanges} returns the existing ranges as a list.
#'
#' \code{readRange} reads the range into a data.frame.
#'
#' \code{createRange} returns the created range object.
#' @author Adrian Dragulescu
#' @examples
#'
#'
#' file <- system.file("tests", "test_import.xlsx", package = "xlsx")
#'
#' wb <- loadWorkbook(file)
#' sheet <- getSheets(wb)[["deletedFields"]]
#' ranges <- getRanges(wb)
#'
#' # the call below fails on cran tests for MacOS. You should see the
#' # FAQ: https://code.google.com/p/rexcel/wiki/FAQ
#' #res <- readRange(ranges[[1]], sheet, colClasses="numeric") # read it
#'
#' ranges[[1]]$getNameName() # get its name
#'
#' # see all the available java methods that you can call
#' rJava::.jmethods(ranges[[1]])
#'
#' # create a new named range
#' firstCell <- sheet$getRow(14L)$getCell(4L)
#' lastCell <- sheet$getRow(20L)$getCell(7L)
#' rangeName <- "Test2"
#' # same issue on MacOS
#' #createRange(rangeName, firstCell, lastCell)
#'
#'
#' @export
#' @name NamedRanges
createRange <- function(rangeName, firstCell, lastCell)
{
sheet <- firstCell$getSheet()
sheetName <- sheet$getSheetName()
firstCellRef <- .jnew("org/apache/poi/ss/util/CellReference",
as.integer(firstCell$getRowIndex()), as.integer(firstCell$getColumnIndex()))
lastCellRef <- .jnew("org/apache/poi/ss/util/CellReference",
as.integer(lastCell$getRowIndex()), as.integer(lastCell$getColumnIndex()))
nameFormula <- paste(sheetName, "!", firstCellRef$formatAsString(), ":",
lastCellRef$formatAsString(), sep="")
wb <- sheet$getWorkbook()
range <- wb$createName()
range$setNameName(rangeName)
range$setRefersToFormula( nameFormula )
range
}
#############################################################################
# get info about ranges in the spreadsheet, similar to getSheets
#
#' @export
#' @rdname NamedRanges
getRanges <- function(wb)
{
noRanges <- .jcall(wb, "I", "getNumberOfNames")
if (noRanges == 0){
cat("Workbook has no ranges!\n")
return()
}
res <- list()
for (i in 1:noRanges) {
aRange <- .jcall(wb, "Lorg/apache/poi/ss/usermodel/Name;", "getNameAt",
as.integer(i-1))
if (.jcall(aRange, "Z", "isDeleted")) {
aRangeRef <- "No cell reference"
} else {
aRangeRef <- tryCatch(.jcall(aRange, "S", "getRefersToFormula"),
error = function(e) "Invalid reference")
# one <- list(ref=aRange, name=aRange$getNameName())
res[[i]] <- aRange
# names(res)[i] <- aRangeRef
}
}
res
}
#############################################################################
# Read one range.
# range is a Java Object reference as returned by getRanges
#
#' @export
#' @rdname NamedRanges
readRange <- function(range, sheet, colClasses = "character")
{
## getRefersToFormula throws an error if external reference is broken
aRangeRef <- tryCatch(.jcall(range, "S", "getRefersToFormula"),
error = function(e) stop("Invalid range address", call. = FALSE))
## A broken reference starts with #REF!
if (grepl("#REF!", aRangeRef, fixed=TRUE) > 0)
stop(paste(range, aRangeRef, "is broken"), call. = FALSE)
## A linked range looks like '[path\path\file.xls]Sheet'!A1:B1
if (grepl("[", aRangeRef, fixed=TRUE) > 0)
stop(paste(range, aRangeRef, "linked range can't be read"), call. = FALSE)
areaRef <- .jnew("org/apache/poi/ss/util/AreaReference", aRangeRef)
if (!areaRef$isContiguous(aRangeRef))
stop(paste(range, "is not contiguous. Not supported yet!"), call. = FALSE)
firstCell <- areaRef$getFirstCell()
startRow <- firstCell$getRow()+1
startColumn <- firstCell$getCol()+1
lastCell <- areaRef$getLastCell()
endRow <- lastCell$getRow()+1
endColumn <- lastCell$getCol()+1
noRows <- endRow - startRow + 1
noColumns <- endColumn - startColumn + 1
if (length(colClasses) < noColumns)
colClasses <- rep(colClasses, noColumns)
Rintf <- .jnew("org/cran/rexcel/RInterface") # create an interface object
res <- vector("list", length=noColumns)
for (i in seq_len(noColumns)){
res[[i]] <- switch(colClasses[i],
numeric = .jcall(Rintf, "[D", "readColDoubles",
.jcast(sheet, "org/apache/poi/ss/usermodel/Sheet"),
as.integer(startRow-1), as.integer(startRow-1+noRows-1),
as.integer(startColumn-1+i-1)),
character = .jcall(Rintf, "[S", "readColStrings",
.jcast(sheet, "org/apache/poi/ss/usermodel/Sheet"),
as.integer(startRow-1), as.integer(startRow-1+noRows-1),
as.integer(startColumn-1+i-1))
)
}
names(res) <- paste("C", startColumn:endColumn, sep="")
data.frame(res)
}
## firstCellRef <- .jnew("org/apache/poi/hssf/util/CellReference", firstCell)
## endCellRef <- .jnew("org/apache/poi/hssf/util/CellReference", endCell)
## areaRef <- .jnew("org/apache/poi/ss/util/AreaReference", firstCellRef, endCellRef)
## nameFormula <- areaRef$formatAsString()
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/NamedRanges.R |
# functions to work with binary plots
#
#' Functions to manipulate images in a spreadsheet.
#'
#' For now, the following image types are supported: dib, emf, jpeg, pict, png,
#' wmf. Please note, that scaling works correctly only for workbooks with the
#' default font size (Calibri 11pt for .xlsx). If the default font is changed
#' the resized image can be streched vertically or horizontally.
#'
#' Don't know how to remove an existing image yet.
#'
#' @param file the absolute path to the image file.
#' @param sheet a worksheet object as returned by \code{createSheet} or by
#' subsetting \code{getSheets}. The picture will be added on this sheet at
#' position \code{startRow}, \code{startColumn}.
#' @param scale a numeric specifying the scale factor for the image.
#' @param startRow a numeric specifying the row of the upper left corner of the
#' image.
#' @param startColumn a numeric specifying the column of the upper left corner
#' of the image.
#' @return \code{addPicture} a java object references pointing to the picture.
#' @author Adrian Dragulescu
#' @examples
#'
#'
#' file <- system.file("tests", "log_plot.jpeg", package = "xlsx")
#'
#' wb <- createWorkbook()
#' sheet <- createSheet(wb, "Sheet1")
#'
#' addPicture(file, sheet)
#'
#' # don't forget to save the workbook!
#'
#'
#' @export
#' @name Picture
addPicture <- function(file, sheet, scale=1, startRow=1, startColumn=1)
{
# get the picture extension
pic_ext <- paste("PICTURE_TYPE_",
toupper(gsub(".*\\.(.*)$", "\\1", file)), sep="")
iStream <- .jnew("java/io/FileInputStream", file)
ioutils <- .jnew("org/apache/poi/util/IOUtils")
bytes <- .jcall(ioutils, "[B", "toByteArray",
.jcast(iStream, "java/io/InputStream"))
.jcall(iStream, "V", "close")
wb <- .jcall(sheet,
"Lorg/apache/poi/ss/usermodel/Workbook;", "getWorkbook")
extId <- .jfield(wb, "I", pic_ext)
picId <- .jcall(wb, "I", "addPicture", bytes, as.integer(extId))
drawing <- .jcall(sheet,
"Lorg/apache/poi/ss/usermodel/Drawing;", "createDrawingPatriarch")
factory <- .jcall(wb,
"Lorg/apache/poi/ss/usermodel/CreationHelper;", "getCreationHelper")
anchor <- .jcall(factory,
"Lorg/apache/poi/ss/usermodel/ClientAnchor;", "createClientAnchor")
.jcall(anchor, "V", "setCol1", as.integer(startColumn-1))
.jcall(anchor, "V", "setRow1", as.integer(startRow-1))
# create the picture
pict <- .jcall(drawing, "Lorg/apache/poi/ss/usermodel/Picture;",
"createPicture", anchor, as.integer(picId))
.jcall(pict, "V", "resize", scale)
invisible(pict)
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/Picture.R |
######################################################################
# work with print setup
#
#' Function to manipulate print setup.
#'
#' Other settings are available but not exposed. Please see the java docs.
#'
#' @aliases printSetup PrintSetup
#' @param sheet a worksheet object \code{\link{Worksheet}}.
#' @param fitHeight numeric value to set the number of pages high to fit the
#' sheet in.
#' @param fitWidth numeric value to set the number of pages wide to fit the
#' sheet in.
#' @param copies numeric value to set the number of copies.
#' @param draft logical indicating if it's a draft or not.
#' @param footerMargin numeric value to set the footer margin.
#' @param headerMargin numeric value to set the header margin.
#' @param landscape logical value to specify the paper orientation.
#' @param pageStart numeric value from where to start the page numbering.
#' @param paperSize character to set the paper size. Valid values are
#' "A4_PAPERSIZE", "A5_PAPERSIZE", "ENVELOPE_10_PAPERSIZE",
#' "ENVELOPE_CS_PAPERSIZE", "ENVELOPE_DL_PAPERSIZE",
#' "ENVELOPE_MONARCH_PAPERSIZE", "EXECUTIVE_PAPERSIZE", "LEGAL_PAPERSIZE",
#' "LETTER_PAPERSIZE".
#' @param noColor logical value to indicate if the prints should be color or
#' not.
#' @return A reference to a java PrintSetup object.
#' @author Adrian Dragulescu
#' @examples
#'
#'
#' wb <- createWorkbook()
#' sheet <- createSheet(wb, "Sheet1")
#' ps <- printSetup(sheet, landscape=TRUE, copies=3)
#'
#'
#' @export
#' @name PrintSetup
printSetup <- function(sheet, fitHeight=NULL,
fitWidth=NULL, copies=NULL, draft=NULL, footerMargin=NULL,
headerMargin=NULL, landscape=FALSE, pageStart=NULL, paperSize=NULL,
noColor=NULL)
{
ps <- .jcall(sheet, "Lorg/apache/poi/ss/usermodel/PrintSetup;",
"getPrintSetup")
if (!is.null(fitHeight))
.jcall(ps, "V", "setFitHeight", .jshort(fitHeight))
if (!is.null(fitWidth))
.jcall(ps, "V", "setFitWidth", .jshort(fitWidth))
if (!is.null(copies))
.jcall(ps, "V", "setCopies", .jshort(copies))
if (!is.null(draft))
.jcall(ps, "V", "setDraft", draft)
if (!is.null(footerMargin))
.jcall(ps, "V", "setFooterMargin", footerMargin)
if (!is.null(headerMargin))
.jcall(ps, "V", "setHeaderMargin", headerMargin)
if (!is.null(landscape))
.jcall(ps, "V", "setLandscape", as.logical(landscape))
if (!is.null(pageStart))
.jcall(ps, "V", "setPageStart", .jshort(pageStart))
if (!is.null(paperSize)){
pagesizeInd <- .jfield(ps, NULL, paperSize)
.jcall(ps, "V", "setPaperSize", .jshort(pagesizeInd))
}
if (!is.null(noColor))
.jcall(ps, "V", "setNoColor", noColor)
ps
}
## if (setAutobreaks)
## .jcall(sheet, "V", "setAutobreaks", )
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/PrintSetup.R |
#
#' Functions to manipulate rows of a worksheet.
#'
#' \code{removeRow} is just a convenience wrapper to remove the rows from the
#' sheet (before saving). Internally it calls \code{lapply}.
#'
#' @param sheet a worksheet object as returned by \code{createSheet} or by
#' subsetting \code{getSheets}.
#' @param rowIndex a numeric vector specifying the index of rows to create.
#' For \code{getRows}, a \code{NULL} value will return all non empty rows.
#' @param rows a list of \code{Row} objects.
#' @param inPoints a numeric value to specify the height of the row in points.
#' @param multiplier a numeric value to specify the multiple of default row
#' height in points. If this value is set, it takes precedence over the
#' \code{inPoints} argument.
#' @return For \code{getRows} a list of java object references each pointing to
#' a row. The list is named with the row number.
#' @author Adrian Dragulescu
#' @seealso To extract the cells from a given row, see \code{\link{Cell}}.
#' @examples
#'
#'
#' file <- system.file("tests", "test_import.xlsx", package = "xlsx")
#'
#' wb <- loadWorkbook(file)
#' sheets <- getSheets(wb)
#'
#' sheet <- sheets[[2]]
#' rows <- getRows(sheet) # get all the rows
#'
#' # see all the available java methods that you can call
#' rJava::.jmethods(rows[[1]])
#'
#' # for example
#' rows[[1]]$getRowNum() # zero based index in Java
#'
#' removeRow(sheet, rows) # remove them all
#'
#' # create some row
#' rows <- createRow(sheet, rowIndex=1:5)
#' setRowHeight( rows, multiplier=3) # 3 times bigger rows than the default
#'
#'
#'
#' @name Row
NULL
######################################################################
# Return a list of row objects.
#
#' @export
#' @rdname Row
createRow <- function(sheet, rowIndex=1:5)
{
rows <- vector("list", length(rowIndex))
names(rows) <- rowIndex
for (ir in seq_along(rowIndex))
rows[[ir]] <- .jcall(sheet, "Lorg/apache/poi/ss/usermodel/Row;",
"createRow", as.integer(rowIndex[ir]-1)) # in java the index starts from 0!
rows
}
######################################################################
# Return a list of all row objects in a sheet.
# You can specify which rows you want to return by provinding a vector of
# rowIndices with rowInd.
#
#' @export
#' @rdname Row
getRows <- function(sheet, rowIndex=NULL)
{
noRows <- sheet$getLastRowNum()+1
keep <- as.integer(seq_len(noRows)-1)
if (!is.null(rowIndex))
keep <- keep[rowIndex]
rows <- vector("list", length(keep))
namesRow <- rep(NA, length(keep))
for (ir in seq_along(keep)){
aux <- .jcall(sheet, "Lorg/apache/poi/ss/usermodel/Row;",
"getRow", keep[ir])
if (!is.null(aux)){
rows[[ir]] <- aux
namesRow[ir] <- .jcall(aux, "I", "getRowNum") + 1
}
}
names(rows) <- namesRow # need this if rows are ragged
rows <- rows[!is.na(namesRow)] # skip the empty rows
rows
}
######################################################################
# remove rows
#
#' @export
#' @rdname Row
removeRow <- function(sheet, rows=NULL)
{
if (is.null(rows))
rows <- getRows(sheet) # delete them all
lapply(rows, function(x){.jcall(sheet, "V", "removeRow", x)})
invisible()
}
######################################################################
# set the Row height
#
#' @export
#' @rdname Row
setRowHeight <- function(rows, inPoints, multiplier=NULL)
{
if ( !is.null(multiplier) ) {
sheet <- rows[[1]]$getSheet() # get the sheet
inPoints <- multiplier * sheet$getDefaultRowHeightInPoints()
}
lapply(rows, function(row) {
row$setHeightInPoints( .jfloat(inPoints) )
})
invisible()
}
## setClass("Workbook",
## representation(
## INITIAL_CAPACITY = "integer",
## sheetName = "character", # a vector
## ref = "jobjRef"), # the java reference
## prototype = prototype(
## INITIAL_CAPACITY = as.integer(3),
## ref = .jnull()
## )
## )
## setMethod("initialize", "Workbook",
## function(.Object, sheetName, ...)
## callNextMethod(.Object, sheetName, ...))
## setMethod("show", "WorksheetEntry",
## function(object){
## callNextMethod(object)
## cat("\n@nrow =", object@nrow,
## "\n@ncol =", object@ncol)
## })
## ##########################################################################
## #
## #setMethod("getWorksheets", "SpreadsheetEntry",
## # function(xls, ...) .getWorksheetEntries(xls, ...))
## getWorksheets <- function(xls, ...)
## {
## id <- .getUniqueId(xls@id)[[1]]
## worksheetId <- paste("https://spreadsheets.google.com/feeds/spreadsheets/",
## id, sep="")
## msg <- xls@con@ref$getWorksheetEntries(worksheetId)
## msg <- strsplit(msg, "\n")[[1]] # split by worksheets
## if (length(msg)==1){
## cat("No worksheets found in the spreadheet.\n")
## return
## }
## msg <- strsplit(msg, "\t") # split by fields
## slotNames <- msg[[1]]
## msg <- msg[-1]
## msg <- lapply(msg, as.list)
## msg <- lapply(msg, function(x, slotNames){names(x) <- slotNames; x},
## slotNames)
## msg <- lapply(msg,
## function(x, slotNames){
## x$canEdit <- as.logical(toupper(x$canEdit))
## x$nrow <- as.integer(x$nrow)
## x$ncol <- as.integer(x$ncol)
## x$published <- as.POSIXct(x$published, "%Y-%m-%dT%H:%M:%OSZ", tz="")
## x
## }, slotNames)
## wks <- vector("list", length(msg))
## for (w in 1:length(wks)){
## listFields <- msg[[w]]
## listFields$con <- xls@con
## wks[[w]] <- new("WorksheetEntry", listFields) # call the constructor
## }
## wks
## }
## ##########################################################################
## # convert to data.frame
## setAs("WorksheetEntry", "data.frame",
## function(from){
## res <- data.frame(
## title = from@title,
## nrow = from@nrow,
## ncol = from@ncol,
## authors = from@authors,
## canEdit = from@canEdit,
## # id = from@id,
## # etag = from@etag,
## published = from@published,
## # content = from@content,
## # con = from@con,
## stringsAsFactors = FALSE)
## res
## })
## ##########################################################################
## #
## #setMethod("getListEntries", "WorksheetEntry",
## # function(wks, ...) .getListEntries(wks, ...))
## getListEntries <- function(wks, ...)
## {
## id <- gsub("worksheets", "list", wks@id)
## worksheetId <- paste(id, "/private/full", sep="")
## msg <- wks@con@ref$getListEntries(worksheetId)
## if (wks@con@ref$getMsg() != "")
## stop(wks@con@ref$getMsg())
## msg <- strsplit(msg, "\n")[[1]] # split by list entries
## if (length(msg)==0){
## cat("No list entries found in the worksheet.\n")
## return
## }
## msg <- strsplit(msg, "\t") # split by fields
## slotNames <- msg[[1]]
## msg <- msg[-1]
## msg <- lapply(msg, as.list)
## msg <- lapply(msg, function(x, slotNames){names(x) <- slotNames; x},
## slotNames)
## msg <- lapply(msg,
## function(x, slotNames){
## x$canEdit <- as.logical(toupper(x$canEdit))
## x$published <- as.POSIXct(x$published, "%Y-%m-%dT%H:%M:%OSZ", tz="")
## x
## }, slotNames)
## entries <- vector("list", length(msg))
## for (e in 1:length(entries)){
## listFields <- msg[[e]]
## listFields$rowId <- sub(".*/(.*)$", "\\1", listFields$id)
## listFields$con <- wks@con
## entries[[e]] <- new("ListEntry", listFields) # call the constructor
## }
## names(entries) <- sapply(entries, slot, "rowId")
## entries
## }
## ##########################################################################
## # getContent for a ListEntry
## # Returns a data.frame with one row
## #
## setMethod("getContent", "ListEntry",
## function(obj, ...){
## id <- obj@id
## ind <- gregexpr("/", id)[[1]]
## id <- paste(substr(id, 1, ind[length(ind)]), "private/full/",
## substr(id, ind[length(ind)]+1, nchar(id)), sep="")
## msg <- obj@con@ref$getContentListEntry(id)
## if (is.null(msg)) return(NULL)
## msg <- strsplit(msg, "\t")[[1]] # split by fields
## N <- length(msg)
## values <- matrix(msg[seq.int(2,N,2)], ncol=N/2, byrow=TRUE)
## colnames(values) <- msg[seq.int(1,N,2)]
## rownames(values) <- obj@rowId
## values
## }
## )
## ##########################################################################
## # add ListEntries to a worksheetEntry (wks)
## #
## addListEntry <- function(wks, contentList)
## {
## id <- wks@id
## ind <- gregexpr("/", id)[[1]]
## id <- paste(substr(id, 1, ind[length(ind)]), "private/full/",
## substr(id, ind[length(ind)]+1, nchar(id)), sep="")
## # make content string. tag,values separated by \t, listEntries
## # separated by \t.
## content <- sapply(contentList, function(x){
## paste(names(x), x, sep="\t", collapse="\t")})
## content <- paste(content, sep="", collapse="\n")
## wks@con@ref$addListEntry(id, content)
## invisible(as.logical(wks@con@ref$getMsg()))
## }
## ##########################################################################
## # add ListEntries to a worksheetEntry (wks)
## #
## updateListEntry <- function(listEntries, contentList)
## {
## if (length(contentList)==1 & !is.list(contentList[1]))
## contentList <- list(contentList) # give the user a break
## if (length(listEntries) != length(contentList))
## stop("Non-equal length for the two arguments!")
## # construct the correct list entries id
## id <- sapply(listEntries, slot, "id")
## ind <- gregexpr("/", id)
## id <- mapply(function(id, ind){
## paste(substr(id, 1, ind[length(ind)]), "private/full/",
## substr(id, ind[length(ind)]+1, nchar(id)), sep="")}, id, ind)
## ids <- paste(id, sep="", collapse="\n")
## # make content string. tag,values separated by \t, listEntries
## # separated by \t.
## content <- sapply(contentList, function(x){
## paste(names(x), x, sep="\t", collapse="\t")})
## content <- paste(content, sep="", collapse="\n")
## listEntries[[1]]@con@ref$updateListEntry(ids, content)
## invisible(as.logical(listEntries[[1]]@con@ref$getMsg()))
## }
## ##########################################################################
## # delete ListEntries to a worksheetEntry (wks)
## #
## deleteListEntry <- function(listEntries)
## {
## # construct the correct list entries id
## id <- sapply(listEntries, slot, "id")
## ind <- gregexpr("/", id)
## id <- mapply(function(id, ind){
## paste(substr(id, 1, ind[length(ind)]), "private/full/",
## substr(id, ind[length(ind)]+1, nchar(id)), sep="")}, id, ind)
## ids <- paste(id, sep="", collapse="\n")
## listEntries[[1]]@con@ref$deleteListEntry(ids)
## invisible(as.logical(listEntries[[1]]@con@ref$getMsg()))
## }
## ##########################################################################
## # create an empty worksheet. Call it new instead of add for consistency
## # with other objects.
## addWorksheet <- function(xls, title, nrow=100, ncol=20)
## {
## key <- gsub("spreadsheet%3A(.*)", "\\1", xls@key)
## id <- paste("https://spreadsheets.google.com/feeds/spreadsheets/", key,
## sep="")
## xls@con@ref$addWorksheet(title, as.integer(nrow), as.integer(ncol), id)
## invisible(as.logical(xls@con@ref$getMsg()))
## }
## ##########################################################################
## # delete an existing worksheet
## deleteWorksheet <- function(wks)
## {
## id <- wks@id
## ind <- gregexpr("/", id)[[1]]
## id <- paste(substr(id, 1, ind[length(ind)]), "private/full/",
## substr(id, ind[length(ind)]+1, nchar(id)), sep="")
## wks@con@ref$deleteWorksheet(id)
## invisible(as.logical(wks@con@ref$getMsg()))
## }
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/Row.R |
# createWorkbook
# loadWorkbook
# saveWorkbook
# getSheets
# createSheet
# removeSheet
#' Functions to manipulate Excel 2007 workbooks.
#'
#' \code{createWorkbook} creates an empty workbook object.
#'
#' \code{loadWorkbook} loads a workbook from a file.
#'
#' \code{saveWorkbook} saves an existing workook to an Excel 2007 file.
#'
#' Reading or writing of password protected workbooks is supported for Excel
#' 2007 OOXML format only. Note that in Linux, LibreOffice is not able to read
#' password protected spreadsheets.
#'
#' @param type a String, either \code{xlsx} for Excel 2007 OOXML format, or
#' \code{xls} for Excel 95 binary format.
#' @param file the path to the file you intend to read or write. Can be an xls
#' or xlsx format.
#' @param wb a workbook object as returned by \code{createWorkbook} or
#' \code{loadWorkbook}.
#' @param password a String with the password.
#' @return \code{createWorkbook} returns a java object reference pointing to an
#' empty workbook object.
#'
#' \code{loadWorkbook} creates a java object reference corresponding to the
#' file to load.
#' @author Adrian Dragulescu
#' @seealso \code{\link{write.xlsx}} for writing a \code{data.frame} to an
#' \code{xlsx} file. \code{\link{read.xlsx}} for reading the content of a
#' \code{xlsx} worksheet into a \code{data.frame}. To extract worksheets and
#' manipulate them, see \code{\link{Worksheet}}.
#' @examples
#'
#'
#' wb <- createWorkbook()
#'
#' # see all the available java methods that you can call
#' rJava::.jmethods(wb)
#'
#' # for example
#' wb$getNumberOfSheets() # no sheet yet!
#'
#' # loadWorkbook("C:/Temp/myFile.xls")
#'
#' @name Workbook
NULL
######################################################################
#
#' @export
#' @rdname Workbook
createWorkbook <- function(type="xlsx")
{
if (type=="xls") {
wb <- .jnew("org/apache/poi/hssf/usermodel/HSSFWorkbook")
} else if (type == "xlsx") {
wb <- .jnew("org/apache/poi/xssf/usermodel/XSSFWorkbook")
} else {
stop(paste("Unknown format", type))
}
return(wb)
}
######################################################################
#
#' @export
#' @rdname Workbook
loadWorkbook <- function(file, password=NULL)
{
if (!file.exists(path.expand(file)))
stop("Cannot find ", path.expand(file))
if (is.null(password)) {
inputStream <- .jnew("java/io/FileInputStream", path.expand(file))
wbFactory <- .jnew("org/apache/poi/ss/usermodel/WorkbookFactory")
wb <- wbFactory$create(inputStream)
} else {
file <- .jnew("java/io/File", path.expand(file))
fileSystem <-new(J("org/apache/poi/poifs/filesystem/NPOIFSFileSystem"),
file)
info <- new(J("org/apache/poi/poifs/crypt/EncryptionInfo"),
fileSystem)
decryptor <- J(info, "getDecryptor")
verification <- J(decryptor, "verifyPassword", password)
if (!verification) stop("password does not verify")
dataStream <- J(decryptor, "getDataStream", fileSystem)
wb <- new(J("org/apache/poi/xssf/usermodel/XSSFWorkbook"),
dataStream)
}
return(wb)
}
######################################################################
#
#' @export
#' @rdname Workbook
saveWorkbook <- function(wb, file, password=NULL)
{
nfile <- normalizePath(file, mustWork = FALSE)
jFile <- .jnew("java/io/File", nfile)
fh <- .jnew("java/io/FileOutputStream", jFile)
# write the workbook to the file
wb$write(fh)
# close the filehandle
.jcall(fh, "V", "close")
if ( !is.null(password) ) {
fs <- .jnew("org/apache/poi/poifs/filesystem/POIFSFileSystem")
encMode <- J("org/apache/poi/poifs/crypt/EncryptionMode", "valueOf", "agile")
info <- .jnew("org/apache/poi/poifs/crypt/EncryptionInfo", fs, encMode)
enc <- info$getEncryptor()
enc$confirmPassword(password)
access <- J("org.apache.poi.openxml4j.opc.PackageAccess", "valueOf", "READ_WRITE")
opc <- J("org.apache.poi.openxml4j.opc.OPCPackage", "open", jFile, access)
outputStream <- enc$getDataStream(fs)
opc$save(outputStream)
opc$close()
fos <- .jnew("java/io/FileOutputStream", nfile)
fs$writeFilesystem(fos)
fos$close()
}
invisible()
}
## # make a file handle and write the xlsx to file
## filename <- "C:/Temp/junk.xlsx"
## fh <- .jnew("java/io/FileOutputStream", filename)
## .jcall(wb, "V", "write", .jcast(fh, "java/io/OutputStream"))
#' Functions to manipulate worksheets.
#'
#' @aliases Worksheet
#'
#' @param wb a workbook object as returned by \code{createWorksheet} or
#' \code{loadWorksheet}.
#' @param sheetName a character specifying the name of the worksheet to create,
#' or remove.
#' @return \code{createSheet} returns the created \code{Sheet} object.
#'
#' \code{getSheets} returns a list of java object references each pointing to
#' an worksheet. The list is named with the sheet names.
#' @author Adrian Dragulescu
#' @seealso To extract rows from a given sheet, see \code{\link{Row}}.
#' @examples
#'
#'
#' file <- system.file("tests", "test_import.xlsx", package = "xlsx")
#'
#' wb <- loadWorkbook(file)
#' sheets <- getSheets(wb)
#'
#' sheet <- sheets[[2]] # extract the second sheet
#'
#' # see all the available java methods that you can call
#' rJava::.jmethods(sheet)
#'
#' # for example
#' sheet$getLastRowNum()
#'
#' @name Sheet
NULL
######################################################################
# return the sheets
#
#' @export
#' @rdname Sheet
getSheets <- function(wb)
{
noSheets <- wb$getNumberOfSheets()
if (noSheets==0){
cat("Workbook has no sheets!\n")
return()
}
res <- vector("list", length=noSheets)
for (sh in 1:noSheets){
names(res)[sh] <- wb$getSheetName(as.integer(sh-1))
res[[sh]] <- wb$getSheetAt(as.integer(sh-1))
}
res
}
######################################################################
#
#' @export
#' @rdname Sheet
createSheet <- function(wb, sheetName="Sheet1")
{
sheet <- .jcall(wb, "Lorg/apache/poi/ss/usermodel/Sheet;",
"createSheet", sheetName)
return(sheet)
}
######################################################################
#
#' @export
#' @rdname Sheet
removeSheet <- function(wb, sheetName="Sheet1")
{
sheetInd <- wb$getSheetIndex(sheetName)
.jcall(wb, "V", "removeSheetAt", as.integer(sheetInd))
return(invisible())
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/Workbook.R |
#' Add a \code{data.frame} to a sheet.
#'
#' Add a \code{data.frame} to a sheet, allowing for different column styles.
#' Useful when constructing the spreadsheet from scratch.
#'
#' Starting with version 0.5.0 this function uses the functionality provided by
#' \code{CellBlock} which results in a significant improvement in performance
#' compared with a cell by cell application of \code{\link{setCellValue}} and
#' with other previous atempts.
#'
#' It is difficult to treat \code{NA}'s consistently between R and Excel via
#' Java. Most likely, users of Excel will want to see \code{NA}'s as blank
#' cells. In R character \code{NA}'s are simply characters, which for Excel
#' means "NA".
#'
#' The default formats for Date and DateTime columns can be changed via the two
#' package options \code{xlsx.date.format} and \code{xlsx.datetime.format}.
#' They need to be specified in Java date format
#' \url{https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html}.
#'
#' @param x a \code{data.frame}.
#' @param sheet a \code{\link{Sheet}} object.
#' @param col.names a logical value indicating if the column names of \code{x}
#' are to be written along with \code{x} to the file.
#' @param row.names a logical value indicating whether the row names of
#' \code{x} are to be written along with \code{x} to the file.
#' @param startRow a numeric value for the starting row.
#' @param startColumn a numeric value for the starting column.
#' @param colStyle a list of \code{\link{CellStyle}}. If the name of the list
#' element is the column number, it will be used to set the style of the
#' column. Columns of type \code{Date} and \code{POSIXct} are styled
#' automatically even if \code{colSyle=NULL}.
#' @param colnamesStyle a \code{\link{CellStyle}} object to customize the table
#' header.
#' @param rownamesStyle a \code{\link{CellStyle}} object to customize the row
#' names (if \code{row.names=TRUE}).
#' @param showNA a boolean value to control how NA's are displayed on the
#' sheet. If \code{FALSE}, NA values will be represented as blank cells.
#' @param characterNA a string value to control how character NA will be shown
#' in the spreadsheet.
#' @param byrow a logical value indicating if the data.frame should be added to
#' the sheet in row wise fashion.
#' @return None. The modification to the workbook is done in place.
#' @author Adrian Dragulescu
#' @examples
#'
#'
#' wb <- createWorkbook()
#' sheet <- createSheet(wb, sheetName="addDataFrame1")
#' data <- data.frame(mon=month.abb[1:10], day=1:10, year=2000:2009,
#' date=seq(as.Date("1999-01-01"), by="1 year", length.out=10),
#' bool=c(TRUE, FALSE), log=log(1:10),
#' rnorm=10000*rnorm(10),
#' datetime=seq(as.POSIXct("2011-11-06 00:00:00", tz="GMT"), by="1 hour",
#' length.out=10))
#' cs1 <- CellStyle(wb) + Font(wb, isItalic=TRUE) # rowcolumns
#' cs2 <- CellStyle(wb) + Font(wb, color="blue")
#' cs3 <- CellStyle(wb) + Font(wb, isBold=TRUE) + Border() # header
#' addDataFrame(data, sheet, startRow=3, startColumn=2, colnamesStyle=cs3,
#' rownamesStyle=cs1, colStyle=list(`2`=cs2, `3`=cs2))
#'
#' # to change the default date format use something like this
#' # options(xlsx.date.format="dd MMM, yyyy")
#'
#'
#' # Don't forget to save the workbook ...
#' # saveWorkbook(wb, file)
#'
#' @export
addDataFrame <- function(x, sheet, col.names=TRUE, row.names=TRUE,
startRow=1, startColumn=1, colStyle=NULL, colnamesStyle=NULL,
rownamesStyle=NULL, showNA=FALSE, characterNA="", byrow=FALSE)
{
if (!is.data.frame(x))
x <- data.frame(x) # just because the error message is too ugly
if (row.names) { # add rownames to data x as the first column
x <- cbind(rownames=rownames(x), x)
if (!is.null(colStyle))
names(colStyle) <- as.numeric(names(colStyle)) + 1
}
wb <- sheet$getWorkbook()
classes <- unlist(sapply(x, class))
if ("Date" %in% classes)
csDate <- CellStyle(wb) + DataFormat(getOption("xlsx.date.format"))
if ("POSIXct" %in% classes)
csDateTime <- CellStyle(wb) + DataFormat(getOption("xlsx.datetime.format"))
# offset required to give space for column names
# (either excel columns if byrow=TRUE or rows if byrow=FALSE)
iOffset <- if (col.names) 1L else 0L
# offset required to give space for row names
# (either excel rows if byrow=TRUE or columns if byrow=FALSE)
jOffset <- if (row.names) 1L else 0L
if ( byrow ) {
# write data.frame columns data row-wise
setDataMethod <- "setRowData"
setHeaderMethod <- "setColData"
blockRows <- ncol(x)
blockCols <- nrow(x) + iOffset # row-wise data + column names
} else {
# write data.frame columns data column-wise, DEFAULT
setDataMethod <- "setColData"
setHeaderMethod <- "setRowData"
blockRows <- nrow(x) + iOffset # column-wise data + column names
blockCols <- ncol(x)
}
# create a CellBlock, not sure why the usual .jnew doesn't work
cellBlock <- CellBlock( sheet,
as.integer(startRow), as.integer(startColumn),
as.integer(blockRows), as.integer(blockCols),
TRUE)
# insert colnames
if (col.names) {
if (!(ncol(x) == 1 && colnames(x)=="rownames"))
.jcall( cellBlock$ref, "V", setHeaderMethod, 0L, jOffset,
.jarray(colnames(x)[(1+jOffset):ncol(x)]), showNA,
if ( !is.null(colnamesStyle) ) colnamesStyle$ref else
.jnull('org/apache/poi/ss/usermodel/CellStyle') )
}
# write one data.frame column at a time, and style it if it has style
# Dates and POSIXct columns get styled if not overridden.
for (j in seq_along(x)) {
thisColStyle <-
if ((j==1) && (row.names) && (!is.null(rownamesStyle))) {
rownamesStyle
} else if (as.character(j) %in% names(colStyle)) {
colStyle[[as.character(j)]]
} else if ("Date" %in% class(x[,j])) {
csDate
} else if ("POSIXt" %in% class(x[,j])) {
csDateTime
} else {
NULL
}
xj <- x[,j]
if ("integer" %in% class(xj)) {
aux <- xj
} else if (any(c("numeric", "Date", "POSIXt") %in% class(xj))) {
aux <- if ("Date" %in% class(xj)) {
as.numeric(xj)+25569
} else if ("POSIXt" %in% class(x[,j])) {
as.numeric(xj)/86400 + 25569
} else {
xj
}
haveNA <- is.na(aux)
if (any(haveNA))
aux[haveNA] <- NaN # encode the numeric NAs as NaN for java
} else {
aux <- as.character(x[,j])
haveNA <- is.na(aux)
if (any(haveNA))
aux[haveNA] <- characterNA
# Excel max cell size limit
if (!all(is.na(aux)) && max(nchar(aux), na.rm = TRUE) > .EXCEL_LIMIT_MAX_CHARS_IN_CELL) {
warning(sprintf("Some cells exceed Excel's limit of %d characters and they will be truncated",
.EXCEL_LIMIT_MAX_CHARS_IN_CELL))
aux <- strtrim(aux, .EXCEL_LIMIT_MAX_CHARS_IN_CELL)
}
}
.jcall( cellBlock$ref, "V", setDataMethod,
as.integer(j-1L), # -1L for Java index
iOffset, # does not need -1L
.jarray(aux), showNA,
if ( !is.null(thisColStyle) ) thisColStyle$ref else
.jnull('org/apache/poi/ss/usermodel/CellStyle') )
}
# return the cellBlock occupied by the generated data frame
invisible(cellBlock)
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/addDataFrame.R |
# This file contains other utilities to make this a more useful package
# If you have an Excel file template and use xlsx to fill in some data and write
# it back to a file (which is a general technique to produce Excel-based reports),
# then it works beautifully except that Excel will not refresh formulae and pivot
# tables when you open the file.
#
# The first problem of forcing formula calculation is easy to solve but the pivot
# table issue is not fixable by Apache POI library. It turns out that
# Excel can refresh pivot tables when you open the file if the pivot cache definition
# XML file has the refreshOnLoad flag set to 1.
# See https://stackoverflow.com/questions/11670816/how-to-refresh-pivot-cache-of-excel-2010-using-open-xml#16624292
#
# This method automates the hack. Basically, unzip the excel file, update
# the pivot cache definition files and writes it back. It's really a hack.
# This hack should be temporary when apache-poi eventually allows adding the
# refreshOnLoad attribute for existing pivot tables in the workbook.
# Make Excel refresh all formula when the file is open
# If output is NULL then overwrite the original file
#' @title Force Refresh Pivot Tables and Formulae
#'
#' @description Functions to force formula calculation or refresh of pivot
#' tables when the Excel file is opened.
#'
#' @details
#' \code{forcePivotTableRefresh} forces pivot tables to be refreshed when the Excel file is opened.
#' \code{forceFormulaRefresh} forces formulae to be recalculated when the Excel file is opened.
#'
#' @param file the path of the source file where formulae/pivot table needs to be refreshed
#' @param output the path of the output file. If it is \code{NULL} then the source file will be overwritten
#' @param verbose Whether to make logging more verbose
#'
#' @return Does not return any results
#'
#' @examples
#' # Patch a file where its pivot tables are not recalculated when the file is opened
#' \dontrun{
#' forcePivotTableRefresh("/tmp/file.xlsx")
#' forcePivotTableRefresh("/tmp/file.xlsx", "/tmp/fixed_file.xlsx")
#' }
#' # Patch a file where its formulae are not recalculated when the file is opened
#' \dontrun{
#' forceFormulaRefresh("/tmp/file.xlsx")
#' forceFormulaRefresh("/tmp/file.xlsx", "/tmp/fixed_file.xlsx")
#' }
#'
#'
#' @author Tom Kwong
#'
#' @export
#' @rdname autoRefresh
forceFormulaRefresh <- function(file, output=NULL, verbose=FALSE) {
# redirect output to source location?
if (is.null(output)) {
output <- file
if (verbose) {
cat(sprintf("Overwriting source file at %s\n", file))
}
}
wb <- loadWorkbook(file)
wb$setForceFormulaRecalculation(TRUE)
saveWorkbook(wb, output)
if (verbose) {
cat(sprintf("Successfully patched file to auto calculate formulae. File saved at %s\n", output))
}
}
#' @export
#' @rdname autoRefresh
forcePivotTableRefresh <- function(file, output=NULL, verbose=FALSE) {
if (!file.exists(file)) {
stop("File does not exist ", file)
}
# redirect output to source location?
if (is.null(output)) {
output <- file
if (verbose) {
cat(sprintf("Overwriting source file at %s\n", file))
}
}
# create a temp directory to hold the unzip'ed Excel content
tmpDir <- tempfile()
dir.create(tmpDir)
#cat(sprintf("Temp directory: %s", tmpDir))
# unzip the excel file
unzip(file, exdir = tmpDir)
# find pivot cache definition files & patch them
pivotTablesPatched <- 0
pivotCacheDir <- file.path(tmpDir, "xl", "pivotCache")
if (dir.exists(pivotCacheDir)) {
pivotCacheFiles <- list.files(path = pivotCacheDir)
pivotCacheDefFiles <- pivotCacheFiles[grepl("pivotCacheDefinition", pivotCacheFiles)]
result <- lapply(pivotCacheDefFiles,
function(defFile) {
# Read pivot cache definition file
workingFile <- file.path(pivotCacheDir, defFile)
text <- readLines(workingFile, warn = FALSE)
# Add refreshOnLoad attribute
text <- gsub('refreshedBy=', 'refreshOnLoad="1" refreshedBy=', text)
# Write back to the file now.
# Excel is particular about the file format... cannot use writeLines
# or else it will be a unix-style (newline, has EOL at last line)
text <- paste(text, collapse = '\r\n')
cat(text, file = workingFile)
})
pivotTablesPatched <- length(result)
}
if (pivotTablesPatched > 0) {
oldwd <- getwd()
setwd(tmpDir)
tmpOutputFile <- paste0(tempfile(), ".xlsx")
status <- zip(tmpOutputFile,
files = list.files(tmpDir, recursive = TRUE, all.files = TRUE),
flags = "-r9q")
setwd(oldwd)
if (status != 0) {
stop(sprintf("Unable to create zip file at %s", tmpOutputFile))
}
if (!file.copy(tmpOutputFile, output, overwrite = TRUE)) {
stop(sprintf("Unable to save file to %s", output))
}
if (verbose) {
cat(sprintf("Successfully patched file to auto refresh pivot tables. File saved at %s\n", output))
}
} else {
if (file != output) { # only make a copy if output is different from orig file
file.copy(file, output)
}
warning(sprintf("This excel file has no pivot table %s", file))
if (verbose) {
cat("Nothing's done\n")
}
}
}
# # Unit testing
# # Run this file from the xlsx project home directory.
# input <- "resources/test_template1_stale.xlsx"
#
# # unit test 1. Take source file output.xlsx and patch & save to output2.xlsx
# cat("Unit test 1\n")
# tmp <- "/tmp/temp.xlsx" # intermediate file for two operations below
# output <- "/tmp/test_pivot_refresh_1.xlsx"
# cat(sprintf("output file: %s\n", output))
# if (file.exists(tmp)) { file.remove(tmp) }
# if (file.exists(output)) { file.remove(output) }
# forcePivotTableRefresh(input, tmp)
# forceFormulaRefresh(tmp, output)
#
# # unit test 2. Make a copy of the source file. Then patch in-place.
# # this usage seems more natural
# cat("Unit test 2\n")
# output <- "/tmp/test_pivot_refresh_2.xlsx"
# cat(sprintf("output file: %s\n", output))
# file.copy(input, output, overwrite = TRUE)
# forcePivotTableRefresh(output)
# forceFormulaRefresh(output)
#
# # unit test 3. Non-verbose.
# cat("Unit test 3 (expect no output)\n")
# output <- "/tmp/test_pivot_refresh_3.xlsx"
# cat(sprintf("output file: %s\n", output))
# file.copy(input, output, overwrite = TRUE)
# forcePivotTableRefresh(output, verbose = FALSE)
# forceFormulaRefresh(output, verbose = FALSE)
#
# cat("Unit test completed!\n")
#
#
# # experiment how to patch Excel file
# # lines <- readLines("/tmp/good_pivot_cache_def_file.xml", warn = FALSE)
# # lines <- gsub('refreshedBy=', 'refreshOnLoad="1" refreshedBy=', lines)
# # lines <- paste(lines, collapse = '\r\n')
# # cat(lines, file = "/tmp/test_pivot_cache_def_file.xml", fill = FALSE)
#
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/autoRefresh.R |
######################################################################
# create ONE comment
#' Functions to manipulate cell comments.
#'
#' These functions are not vectorized.
#'
#' @param cell a \code{Cell} object.
#' @param string a string for the comment.
#' @param author a string with the author's name
#' @param visible a logical value. If \code{TRUE} the comment will be visible.
#' @return
#'
#' \code{createCellComment} creates a \code{Comment} object.
#'
#' \code{getCellComment} returns a the \code{Comment} object if it exists.
#'
#' \code{removeCellComment} removes a comment from the given cell.
#' @author Adrian Dragulescu
#' @seealso For cells, see \code{\link{Cell}}. To format cells, see
#' \code{\link{CellStyle}}.
#' @examples
#'
#'
#' wb <- createWorkbook()
#' sheet1 <- createSheet(wb, "Sheet1")
#' rows <- createRow(sheet1, rowIndex=1:10) # 10 rows
#' cells <- createCell(rows, colIndex=1:8) # 8 columns
#'
#' cell1 <- cells[[1,1]]
#' setCellValue(cell1, 1) # add value 1 to cell A1
#'
#' # create a cell comment
#' createCellComment(cell1, "Cogito", author="Descartes")
#'
#'
#' # extract the comments
#' comment <- getCellComment(cell1)
#' stopifnot(comment$getAuthor()=="Descartes")
#' stopifnot(comment$getString()$toString()=="Cogito")
#'
#' # don't forget to save your workbook!
#'
#' @export
#' @name Comment
createCellComment <- function(cell, string,
author=NULL, visible=TRUE)
{
sheet <- .jcall(cell,
"Lorg/apache/poi/ss/usermodel/Sheet;", "getSheet")
wb <- .jcall(sheet,
"Lorg/apache/poi/ss/usermodel/Workbook;", "getWorkbook")
factory <- .jcall(wb,
"Lorg/apache/poi/ss/usermodel/CreationHelper;", "getCreationHelper")
anchor <- .jcall(factory,
"Lorg/apache/poi/ss/usermodel/ClientAnchor;", "createClientAnchor")
drawing <- .jcall(sheet,
"Lorg/apache/poi/ss/usermodel/Drawing;", "createDrawingPatriarch")
comment <- .jcall(drawing,
"Lorg/apache/poi/ss/usermodel/Comment;", "createCellComment", anchor)
rtstring <- factory$createRichTextString(string) # rich text string
comment$setString(rtstring)
if (!is.null(author))
.jcall(comment, "V", "setAuthor", author)
if (visible)
.jcall(cell, "V", "setCellComment", comment)
invisible(comment)
}
#' @export
#' @rdname Comment
removeCellComment <- function(cell){
.jcall(cell, "V", "removeCellComment")
}
## setCellComment <- function(cell, comment){
## .jcall(cell, "V", "setCellComment", comment)
## }
#' @export
#' @rdname Comment
getCellComment <- function(cell)
{
comment <- .jcall(cell, "Lorg/apache/poi/ss/usermodel/Comment;",
"getCellComment")
comment
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/comment.R |
# addAutoFilter
# addHyperlink
# addMergedRegion
# autoSizeColumn
# createFreezePane
# createSplitPane
# removeMergedRegion
# setColumnWidth
# setPrintArea
# setZoom
#
#
#' Functions to do various spreadsheets effects.
#'
#' Function \code{autoSizeColumn} expands the column width to match the column
#' contents thus removing the ###### that you get when cell contents are larger
#' than cell width.
#'
#' You may need other functionality that is not exposed. Take a look at the
#' java docs and the source code of these functions for how you can implement
#' it in R.
#'
#' @param cellRange a string specifying the cell range. For example a standard
#' area ref (e.g. "B1:D8"). May be a single cell ref (e.g. "B5") in which case
#' the result is a 1 x 1 cell range. May also be a whole row range (e.g.
#' "3:5"), or a whole column range (e.g. "C:F")
#' @param colIndex a numeric vector specifiying the columns you want to auto
#' size.
#' @param colSplit a numeric value for the column to split.
#' @param colWidth a numeric value to specify the width of the column. The
#' units are in 1/256ths of a character width.
#' @param denominator a numeric value representing the denomiator of the zoom
#' ratio.
#' @param endColumn a numeric value for the ending column.
#' @param endRow a numeric value for the ending row.
#' @param ind a numeric value indicating which merged region you want to
#' remove.
#' @param numerator a numeric value representing the numerator of the zoom
#' ratio.
#' @param position a character. Valid value are "PANE_LOWER_LEFT",
#' "PANE_LOWER_RIGHT", "PANE_UPPER_LEFT", "PANE_UPPER_RIGHT".
#' @param rowSplit a numeric value for the row to split.
#' @param sheet a \code{\link{Worksheet}} object.
#' @param sheetIndex a numeric value for the worksheet index.
#' @param startColumn a numeric value for the starting column.
#' @param startRow a numeric value for the starting row.
#' @param xSplitPos a numeric value for the horizontal position of split in
#' 1/20 of a point.
#' @param ySplitPos a numeric value for the vertical position of split in 1/20
#' of a point.
#' @param wb a \code{\link{Workbook}} object.
#' @return \code{addMergedRegion} returns a numeric value to label the merged
#' region. You should use this value as the \code{ind} if you want to
#' \code{removeMergedRegion}.
#' @author Adrian Dragulescu
#' @examples
#'
#'
#' wb <- createWorkbook()
#' sheet1 <- createSheet(wb, "Sheet1")
#' rows <- createRow(sheet1, 1:10) # 10 rows
#' cells <- createCell(rows, colIndex=1:8) # 8 columns
#'
#' ## Merge cells
#' setCellValue(cells[[1,1]], "A title that spans 3 columns")
#' addMergedRegion(sheet1, 1, 1, 1, 3)
#'
#' ## Set zoom 2:1
#' setZoom(sheet1, 200, 100)
#'
#' sheet2 <- createSheet(wb, "Sheet2")
#' rows <- createRow(sheet2, 1:10) # 10 rows
#' cells <- createCell(rows, colIndex=1:8) # 8 columns
#' #createFreezePane(sheet2, 1, 1, 1, 1)
#' createFreezePane(sheet2, 5, 5, 8, 8)
#'
#' sheet3 <- createSheet(wb, "Sheet3")
#' rows <- createRow(sheet3, 1:10) # 10 rows
#' cells <- createCell(rows, colIndex=1:8) # 8 columns
#' createSplitPane(sheet3, 2000, 2000, 1, 1, "PANE_LOWER_LEFT")
#'
#' # set the column width of first column to 25 characters wide
#' setColumnWidth(sheet1, 1, 25)
#'
#' # add a filter on the 3rd row, columns C:E
#' addAutoFilter(sheet1, "C3:E3")
#'
#' # Don't forget to save the workbook ...
#'
#' @name OtherEffects
NULL
######################################################################
# Add autofilter to a cell range
# @param sheet a Sheet object
# @param cellRange a string, "C5:F200", or one row "C1:F1",
# a column range "C:F", a singe cell "B5", or a row range "3:5"
#
#' @export
#' @rdname OtherEffects
addAutoFilter <- function(sheet, cellRange)
{
cellRangeAddress <- J("org/apache/poi/ss/util/CellRangeAddress")$valueOf(cellRange)
invisible(sheet$setAutoFilter(cellRangeAddress))
}
######################################################################
# Add hyperlink
#
#' Add a hyperlink to a cell.
#'
#' Add a hyperlink to a cell to point to an external resource.
#'
#' The cell needs to have content before you add a hyperlink to it. The
#' contents of the cells don't need to be the same as the address of the
#' hyperlink. See the examples.
#'
#' @param cell a \code{\link{Cell}} object.
#' @param address a string pointing to the resource.
#' @param linkType a the type of the resource.
#' @param hyperlinkStyle a \code{\link{CellStyle}} object. If \code{NULL} a
#' default cell style is created, blue underlined font.
#' @return None. The modification to the cell is done in place.
#' @author Adrian Dragulescu
#' @examples
#'
#'
#' wb <- createWorkbook()
#' sheet1 <- createSheet(wb, "Sheet1")
#' rows <- createRow(sheet1, 1:10) # 10 rows
#' cells <- createCell(rows, colIndex=1:8) # 8 columns
#'
#' ## Add hyperlinks to a cell
#' cell <- cells[[1,1]]
#' address <- "https://poi.apache.org/"
#' setCellValue(cell, "click me!")
#' addHyperlink(cell, address)
#'
#' # Don't forget to save the workbook ...
#'
#' @export
addHyperlink <- function(cell, address, linkType=c("URL", "DOCUMENT",
"EMAIL", "FILE"), hyperlinkStyle=NULL)
{
linkType <- match.arg(linkType)
sh <- .jcall(cell, "Lorg/apache/poi/ss/usermodel/Sheet;", "getSheet")
wb <- .jcall(sh, "Lorg/apache/poi/ss/usermodel/Workbook;", "getWorkbook")
if (is.null(hyperlinkStyle)) {
# create a cell style for hyperlinks
hyperFont <- Font(wb, color="blue", underline=1)
hyperlinkStyle <- CellStyle(wb) + hyperFont
}
# create the link
creationHelper <- .jcall(wb, "Lorg/apache/poi/ss/usermodel/CreationHelper;",
"getCreationHelper")
type <- switch(linkType, URL=1L, DOCUMENT=2L, EMAIL=3L, FILE=4L)
link <- .jcall(creationHelper, "Lorg/apache/poi/ss/usermodel/Hyperlink;",
"createHyperlink", type)
.jcall(link, "V", "setAddress", address)
# add the link to the cell and set the cell style
.jcall(cell, "V", "setHyperlink", link)
setCellStyle(cell, hyperlinkStyle)
invisible()
}
######################################################################
# Merge regions
#
#' @export
#' @rdname OtherEffects
addMergedRegion <- function(sheet, startRow, endRow, startColumn,
endColumn)
{
cellRangeAddress <- .jnew("org/apache/poi/ss/util/CellRangeAddress",
as.integer(startRow-1), as.integer(endRow-1), as.integer(startColumn-1),
as.integer(endColumn-1))
ind <- .jcall(sheet, "I", "addMergedRegion", cellRangeAddress)
invisible(ind)
}
#' @export
#' @rdname OtherEffects
removeMergedRegion <- function(sheet, ind)
.jcall(sheet, "V", as.integer(ind))
######################################################################
# fit contents to column. col can be a vector of column indices.
#
#' @export
#' @rdname OtherEffects
autoSizeColumn <- function(sheet, colIndex)
{
for (ic in (colIndex-1))
.jcall(sheet, "V", "autoSizeColumn", as.integer(ic), TRUE)
invisible()
}
######################################################################
# fit contents to column. col can be a vector of column indices.
#
#' @export
#' @rdname OtherEffects
createFreezePane <- function(sheet, rowSplit, colSplit, startRow=NULL,
startColumn=NULL)
{
if (is.null(startRow) & is.null(startColumn)){
.jcall(sheet, "V", "createFreezePane", as.integer(colSplit-1),
as.integer(rowSplit-1))
} else {
.jcall(sheet, "V", "createFreezePane", as.integer(colSplit-1),
as.integer(rowSplit-1), as.integer(startColumn-1),
as.integer(startRow-1))
}
invisible()
}
######################################################################
# fit contents to column. col can be a vector of column indices.
#
#' @export
#' @rdname OtherEffects
createSplitPane <- function(sheet, xSplitPos=2000, ySplitPos=2000,
startRow=1, startColumn=1, position="PANE_LOWER_LEFT")
{
ind <- .jfield(sheet, "B", position)
.jcall(sheet, "V", "createSplitPane", as.integer(xSplitPos),
as.integer(ySplitPos), as.integer(startRow-1),
as.integer(startColumn-1), ind)
invisible()
}
######################################################################
#
#
#' @export
#' @rdname OtherEffects
setColumnWidth <- function(sheet, colIndex, colWidth)
{
for (ic in (colIndex - 1))
.jcall(sheet, "V", "setColumnWidth", as.integer(ic),
as.integer(colWidth*256))
invisible()
}
######################################################################
# set the zoom
#
#' @export
#' @rdname OtherEffects
setPrintArea <- function(wb, sheetIndex, startColumn, endColumn, startRow,
endRow)
{
.jcall(wb, "V", "setPrintArea", as.integer(sheetIndex-1),
as.integer(startColumn-1), as.integer(endColumn-1),
as.integer(startRow-1), as.integer(endRow-1))
}
######################################################################
# set the zoom
#
#' @export
#' @rdname OtherEffects
setZoom <- function(sheet, numerator=100, denominator=100)
{
.jcall(sheet, "V", "setZoom", as.integer(numerator),
as.integer(denominator))
invisible()
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/otherEffects.R |
# One sheet extraction. Similar to read.csv.
#
#
#' Read the contents of a worksheet into an R \code{data.frame}.
#'
#'
#' The \code{read.xlsx} function provides a high level API for reading data
#' from an Excel worksheet. It calls several low level functions in the
#' process. Its goal is to provide the conveniency of
#' \code{\link[utils]{read.table}} by borrowing from its signature.
#'
#' The function pulls the value of each non empty cell in the worksheet into a
#' vector of type \code{list} by preserving the data type. If
#' \code{as.data.frame=TRUE}, this vector of lists is then formatted into a
#' rectangular shape. Special care is needed for worksheets with ragged data.
#'
#' An attempt is made to guess the class type of the variable corresponding to
#' each column in the worksheet from the type of the first non empty cell in
#' that column. If you need to impose a specific class type on a variable, use
#' the \code{colClasses} argument. It is recommended to specify the column
#' classes and not rely on \code{R} to guess them, unless in very simple cases.
#'
#' Excel internally stores dates and datetimes as numeric values, and does not
#' keep track of time zones and DST. When a datetime column is brought into ,
#' it is converted to \code{POSIXct} class with a \emph{GMT} timezone.
#' Occasional rounding errors may appear and the and Excel string
#' representation my differ by one second. For \code{read.xlsx2} bring in a
#' datetime column as a numeric one and then convert to class \code{POSIXct} or
#' \code{Date}. Also rounding the \code{POSIXct} column in R usually does the
#' trick too.
#'
#' The \code{read.xlsx2} function does more work in Java so it achieves better
#' performance (an order of magnitude faster on sheets with 100,000 cells or
#' more). The result of \code{read.xlsx2} will in general be different from
#' \code{read.xlsx}, because internally \code{read.xlsx2} uses
#' \code{readColumns} which is tailored for tabular data.
#'
#' Reading of password protected workbooks is supported for Excel 2007 OOXML
#' format only.
#'
#' @param file the path to the file to read.
#' @param sheetIndex a number representing the sheet index in the workbook.
#' @param sheetName a character string with the sheet name.
#' @param rowIndex a numeric vector indicating the rows you want to extract.
#' If \code{NULL}, all rows found will be extracted, unless \code{startRow} or
#' \code{endRow} are specified.
#' @param colIndex a numeric vector indicating the cols you want to extract.
#' If \code{NULL}, all columns found will be extracted.
#' @param as.data.frame a logical value indicating if the result should be
#' coerced into a \code{data.frame}. If \code{FALSE}, the result is a list
#' with one element for each column.
#' @param header a logical value indicating whether the first row corresponding
#' to the first element of the \code{rowIndex} vector contains the names of the
#' variables.
#' @param colClasses For \code{read.xlsx} a character vector that represent the
#' class of each column. Recycled as necessary, or if the character vector is
#' named, unspecified values are taken to be \code{NA}. For \code{read.xlsx2}
#' see \code{\link{readColumns}}.
#' @param keepFormulas a logical value indicating if Excel formulas should be
#' shown as text in and not evaluated before bringing them in.
#' @param encoding encoding to be assumed for input strings. See
#' \code{\link[utils]{read.table}}.
#' @param startRow a number specifying the index of starting row. For
#' \code{read.xlsx} this argument is active only if \code{rowIndex} is
#' \code{NULL}.
#' @param endRow a number specifying the index of the last row to pull. If
#' \code{NULL}, read all the rows in the sheet. For \code{read.xlsx} this
#' argument is active only if \code{rowIndex} is \code{NULL}.
#' @param password a String with the password.
#' @param ... other arguments to \code{data.frame}, for example
#' \code{stringsAsFactors}
#' @return A data.frame or a list, depending on the \code{as.data.frame}
#' argument. If some of the columns are read as NA's it's an indication that
#' the \code{colClasses} argument has not been set properly.
#'
#' If the sheet is empty, return \code{NULL}. If the sheet does not exist,
#' return an error.
#' @author Adrian Dragulescu
#' @seealso \code{\link{write.xlsx}} for writing \code{xlsx} documents. See
#' also \code{\link{readColumns}} for reading only a set of columns into R.
#' @examples
#'
#' \dontrun{
#'
#' file <- system.file("tests", "test_import.xlsx", package = "xlsx")
#' res <- read.xlsx(file, 1) # read first sheet
#' head(res)
#' # NA. Population Income Illiteracy Life.Exp Murder HS.Grad Frost Area
#' # 1 Alabama 3615 3624 2.1 69.05 15.1 41.3 20 50708
#' # 2 Alaska 365 6315 1.5 69.31 11.3 66.7 152 566432
#' # 3 Arizona 2212 4530 1.8 70.55 7.8 58.1 15 113417
#' # 4 Arkansas 2110 3378 1.9 70.66 10.1 39.9 65 51945
#' # 5 California 21198 5114 1.1 71.71 10.3 62.6 20 156361
#' # 6 Colorado 2541 4884 0.7 72.06 6.8 63.9 166 103766
#' # >
#'
#'
#' # To convert an Excel datetime colum to POSIXct, do something like:
#' # as.POSIXct((x-25569)*86400, tz="GMT", origin="1970-01-01")
#' # For Dates, use a conversion like:
#' # as.Date(x-25569, origin="1970-01-01")
#'
#' res2 <- read.xlsx2(file, 1)
#'
#' }
#'
#' @export
read.xlsx <- function(file, sheetIndex, sheetName=NULL,
rowIndex=NULL, startRow=NULL, endRow=NULL, colIndex=NULL,
as.data.frame=TRUE, header=TRUE, colClasses=NA,
keepFormulas=FALSE, encoding="unknown", password=NULL, ...)
{
if (is.null(sheetName) & missing(sheetIndex))
stop("Please provide a sheet name OR a sheet index.")
wb <- loadWorkbook(file, password=password)
sheets <- getSheets(wb)
sheet <- if (is.null(sheetName)) {
sheets[[sheetIndex]]
} else {
sheets[[sheetName]]
}
if (is.null(sheet))
stop("Cannot find the sheet you requested in the file!")
rowIndex <- if (is.null(rowIndex)) {
if (is.null(startRow))
startRow <- .jcall(sheet, "I", "getFirstRowNum") + 1
if (is.null(endRow))
endRow <- .jcall(sheet, "I", "getLastRowNum") + 1
startRow:endRow
} else rowIndex
rows <- getRows(sheet, rowIndex)
if (length(rows)==0)
return(NULL) # exit early
cells <- getCells(rows, colIndex)
res <- lapply(cells, getCellValue, keepFormulas=keepFormulas,
encoding=encoding)
if (as.data.frame) {
# need to use the index from the names because of empty cells
ind <- lapply(strsplit(names(res), "\\."), as.numeric)
namesIndM <- do.call(rbind, ind)
row.names <- sort(as.numeric(unique(namesIndM[,1])))
col.names <- paste("V", sort(unique(namesIndM[,2])), sep="")
col.names <- sort(unique(namesIndM[,2]))
cols <- length(col.names)
VV <- matrix(list(NA), nrow=length(row.names), ncol=cols,
dimnames=list(row.names, col.names))
# you need indM for empty rows/columns when indM != namesIndM
indM <- apply(namesIndM, 2, function(x){as.numeric(as.factor(x))})
VV[indM] <- res
if (header){ # first row of cells that you want
colnames(VV) <- VV[1,]
VV <- VV[-1,,drop=FALSE]
}
res <- vector("list", length=cols)
names(res) <- colnames(VV)
for (ic in seq_len(cols)) {
aux <- unlist(VV[,ic], use.names=FALSE)
nonNA <- which(!is.na(aux))
if (length(nonNA)>0) { # not a NA column in the middle of data
ind <- min(nonNA)
if (class(aux[ind])=="numeric") {
# test first not NA cell if it's a date/datetime
dateUtil <- .jnew("org/apache/poi/ss/usermodel/DateUtil")
cell <- cells[[paste(row.names[ind + header], ".", col.names[ic], sep = "")]]
isDatetime <- dateUtil$isCellDateFormatted(cell)
if (isDatetime){
if (identical(aux, round(aux))){ # you have dates
aux <- as.Date(aux-25569, origin="1970-01-01")
} else { # Excel does not know timezones?!
aux <- as.POSIXct((aux-25569)*86400, tz="GMT",
origin="1970-01-01")
}
}
}
}
if (!is.na(colClasses[ic]))
suppressWarnings(class(aux) <- colClasses[ic]) # if it gets specified
res[[ic]] <- aux
}
res <- data.frame(res, ...)
}
res
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/read.xlsx.R |
# One sheet extraction. Similar to read.csv.
#
#
#' @export
#' @rdname read.xlsx
read.xlsx2 <- function(file, sheetIndex, sheetName=NULL, startRow=1,
colIndex=NULL, endRow=NULL, as.data.frame=TRUE, header=TRUE,
colClasses="character", password=NULL, ...)
{
if (is.null(sheetName) & missing(sheetIndex))
stop("Please provide a sheet name OR a sheet index.")
wb <- loadWorkbook(file, password=password)
sheets <- getSheets(wb)
if (is.null(sheetName)){
sheet <- sheets[[sheetIndex]]
} else {
sheet <- sheets[[sheetName]]
}
if (is.null(sheet))
stop("Cannot find the sheet you requested in the file!")
if (is.null(endRow)) { # get it from the sheet
endRow <- sheet$getLastRowNum() + 1
}
if (is.null(colIndex)){ # get it from the startRow
row <- sheet$getRow(as.integer(startRow-1))
if (is.null(row)) {
if (endRow == startRow)
return(NULL) # sheet is empty
stop(paste("Row with index startRow is EMPTY! ",
"Specify a different startRow value."))
}
startColumn <- .jcall(row, "T", "getFirstCellNum") + 1
endColumn <- .jcall(row, "T", "getLastCellNum")
colIndex <- startColumn:endColumn
listColIndex <- list(startColumn:endColumn)
} else {
listColIndex <- .splitBlocks(sort(colIndex))
}
# if the colIndex is not contiguous, split into contiguous blocks
# and then cbind the blocks together.
res <- NULL
for (b in seq_along(listColIndex)) {
startColumn <- listColIndex[[b]][1]
endColumn <- tail(listColIndex[[b]],1)
res[[b]] <- readColumns(sheet, startColumn, endColumn, startRow,
endRow=endRow, as.data.frame=as.data.frame, header=header,
colClasses=colClasses[which(colIndex %in% listColIndex[[b]])], ...)
}
do.call(cbind, res)
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/read.xlsx2.R |
#
#
# For CellType: FORMULA, ERROR or blanks, it defaults to "character"
#
#
#' Read a contiguous set of columns from sheet into an R data.frame
#'
#' Read a contiguous set of columns from sheet into an R data.frame. Uses the
#' \code{RInterface} for speed.
#'
#'
#' Use the \code{readColumns} function when you want to read a rectangular
#' block of data from an Excel worksheet. If you request columns which are
#' blank, these will be read in as empty character "" columns. Internally, the
#' loop over columns is done in R, the loop over rows is done in Java, so this
#' function achieves good performance when number of rows >> number of columns.
#'
#' Excel internally stores dates and datetimes as numeric values, and does not
#' keep track of time zones and DST. When a numeric column is formatted as a
#' datetime, it will be converted into \code{POSIXct} class with a \emph{GMT}
#' timezone. If you need a \code{Date} column, you need to specify explicitly
#' using \code{colClasses} argument.
#'
#' For a numeric column Excels's errors and blank cells will be returned as NaN
#' values. Excel's \code{#N/A} will be returned as NA. Formulas will be
#' evaluated. For a chracter column, blank cells will be returned as "".
#'
#' @param sheet a \code{\link{Worksheet}} object.
#' @param startColumn a numeric value for the starting column.
#' @param endColumn a numeric value for the ending column.
#' @param startRow a numeric value for the starting row.
#' @param endRow a numeric value for the ending row. If \code{NULL} it reads
#' all the rows in the sheet. If you request more than the existing rows in
#' the sheet, the result will be truncated by the actual row number.
#' @param as.data.frame a logical value indicating if the result should be
#' coerced into a \code{data.frame}. If \code{FALSE}, the result is a list
#' with one element for each column.
#' @param header a logical value indicating whether the first row corresponding
#' to the first element of the \code{rowIndex} vector contains the names of the
#' variables.
#' @param colClasses a character vector that represents the class of each
#' column. Recycled as necessary, or if \code{NA} an attempt is made to guess
#' the type of each column by reading the first row of data. Only
#' \code{numeric}, \code{character}, \code{Date}, \code{POSIXct}, column types
#' are accepted. Anything else will be coverted to a \code{character} type.
#' If the length is less than the number of columns requested, replicate it.
#' @param ... other arguments to \code{data.frame}, for example
#' \code{stringsAsFactors}
#' @return A data.frame or a list, depending on the \code{as.data.frame}
#' argument.
#' @author Adrian Dragulescu
#' @seealso \code{\link{read.xlsx2}} for reading entire sheets. See also
#' \code{\link{addDataFrame}} for writing a \code{data.frame} to a sheet.
#' @examples
#'
#' \dontrun{
#'
#' file <- system.file("tests", "test_import.xlsx", package = "xlsx")
#'
#' wb <- loadWorkbook(file)
#' sheets <- getSheets(wb)
#'
#' sheet <- sheets[["all"]]
#' res <- readColumns(sheet, startColumn=3, endColumn=10, startRow=3,
#' endRow=7)
#'
#' sheet <- sheets[["NAs"]]
#' res <- readColumns(sheet, 1, 6, 1, colClasses=c("Date", "character",
#' "integer", rep("numeric", 2), "POSIXct"))
#'
#'
#' }
#'
#' @export
readColumns <- function(sheet, startColumn, endColumn, startRow,
endRow=NULL, as.data.frame=TRUE, header=TRUE, colClasses=NA, ...)
{
trueEndRow <- sheet$getLastRowNum() + 1
if (is.null(endRow)) # get it from the sheet
endRow <- trueEndRow
if (endRow > trueEndRow) {
warning(paste("This sheet has only", trueEndRow, "rows"))
endRow <- min(endRow, trueEndRow)
}
noColumns <- endColumn - startColumn + 1
Rintf <- .jnew("org/cran/rexcel/RInterface") # create an interface object
if (header) {
cnames <- try(.jcall(Rintf, "[S", "readRowStrings",
.jcast(sheet, "org/apache/poi/ss/usermodel/Sheet"),
as.integer(startColumn-1), as.integer(endColumn-1),
as.integer(startRow-1)))
if (class(cnames) == "try-error")
stop(paste("Cannot read the header. ",
"The header row doesn't have all requested cells non-blank!"))
startRow <- startRow + 1
} else {
cnames <- as.character(1:noColumns)
}
# guess or expand colClasses
if (is.na(colClasses)[1]) {
row <- getRows(sheet, rowIndex=startRow)
cells <- getCells(row, colIndex=startColumn:endColumn)
if (length(cells) != noColumns)
warning("Not enough columns in the first row of data to correctly guess colClasses!")
colClasses <- .guess_cell_type(cells)
}
colClasses <- rep(colClasses, length.out=noColumns) # extend colClasses
res <- vector("list", length=noColumns)
for (i in seq_len(noColumns)) {
if (any(c("numeric", "POSIXct", "Date") %in% colClasses[i])) {
aux <- .jcall(Rintf, "[D", "readColDoubles",
.jcast(sheet, "org/apache/poi/ss/usermodel/Sheet"),
as.integer(startRow-1), as.integer(endRow-1),
as.integer(startColumn-1+i-1))
if (colClasses[i]=="Date")
aux <- as.Date(aux-25569, origin="1970-01-01")
if (colClasses[i]=="POSIXct")
aux <- as.POSIXct((aux-25569)*86400, tz="GMT", origin="1970-01-01")
} else {
aux <- .jcall(Rintf, "[S", "readColStrings",
.jcast(sheet, "org/apache/poi/ss/usermodel/Sheet"),
as.integer(startRow-1), as.integer(endRow-1),
as.integer(startColumn-1+i-1))
}
#browser()
if (!is.na(colClasses[i]))
suppressWarnings(class(aux) <- colClasses[i]) # if it gets specified
res[[i]] <- aux
}
if (as.data.frame) {
cnames[cnames == ""] <- " " # remove some silly c.......... colnames!
names(res) <- cnames
res <- data.frame(res, ...)
}
res
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/readColumns.R |
# Useful when you have a "fat" spreadsheet (few rows and many columns.)
#
# Only reads Strings for now.
#
#
#' Read a contiguous set of rows into an R matrix
#'
#' Read a contiguous set of rows into an R character matrix. Uses the
#' \code{RInterface} for speed.
#'
#'
#' Use the \code{readRows} function when you want to read a row or a block
#' block of data from an Excel worksheet. Internally, the loop over rows is
#' done in R, and the loop over columns is done in Java, so this function
#' achieves good performance when number of rows << number of columns.
#'
#' In general, you should prefer the function \code{\link{readColumns}} over
#' this one.
#'
#' @param sheet a \code{\link{Worksheet}} object.
#' @param startRow a numeric value for the starting row.
#' @param endRow a numeric value for the ending row. If \code{NULL} it reads
#' all the rows in the sheet.
#' @param startColumn a numeric value for the starting column.
#' @param endColumn a numeric value for the ending column. Empty cells will be
#' returned as "".
#' @return A character matrix.
#' @author Adrian Dragulescu
#' @seealso \code{\link{read.xlsx2}} for reading entire sheets. See also
#' \code{\link{addDataFrame}} for writing a \code{data.frame} to a sheet.
#' @examples
#'
#' \dontrun{
#'
#' file <- system.file("tests", "test_import.xlsx", package = "xlsx")
#'
#' wb <- loadWorkbook(file)
#' sheets <- getSheets(wb)
#'
#' sheet <- sheets[["all"]]
#' res <- readRows(sheet, startRow=3, endRow=7, startColumn=3, endColumn=10)
#'
#'
#'
#' }
#'
#' @export
readRows <- function(sheet, startRow, endRow, startColumn,
endColumn=NULL)
{
row1 <- sheet$getRow(as.integer(startRow-1)) # first row
if (is.null(row1))
stop("First row, with index ", startRow, " is empty. Please check!")
trueEndColumn <- row1$getLastCellNum()
if (is.null(endColumn)) # get it from the first row
endColumn <- trueEndColumn
noRows <- endRow - startRow + 1
Rintf <- .jnew("org/cran/rexcel/RInterface") # create an interface object
res <- matrix(NA, nrow=noRows, ncol=endColumn-startColumn+1)
for (i in seq_len(noRows)) {
aux <- .jcall(Rintf, "[S", "readRowStrings",
.jcast(sheet, "org/apache/poi/ss/usermodel/Sheet"),
as.integer(startColumn-1), as.integer(endColumn-1),
as.integer(startRow-1+i-1))
res[i,] <- aux
}
res
}
## if (endColumn > trueEndColumn) {
## warning(paste("First row requested has only", trueEndColumn, "columns."))
## endColumn <- min(endColumn, trueEndColumn)
## }
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/readRows.R |
# .guess_cell_type
# .onLoad
# .Rcolor2XLcolor
# .splitBlocks
# .hssfcolor
# .xssfcolor
###################################################################
# given a vector of cells, return the "appropriate" R type
# you cannot decide if it's a Date or a POSIXct
#
# only returns "numeric", "character", "POSIXct"
#
.guess_cell_type <- function(cells)
{
cellType <- sapply(cells, function(x){x$getCellType()}) + 1
dateUtil <- .jnew("org/apache/poi/ss/usermodel/DateUtil")
isDateTime <- mapply(function(x,y) {
if (y != 1) { # if it's not numeric, forget about it
FALSE
} else {
dateUtil$isCellDateFormatted(x)
}
}, cells, cellType)
guessedColClasses <- ifelse(cellType==1,"numeric", "character")
guessedColClasses[isDateTime] <- "POSIXct"
guessedColClasses
}
####################################################################
#
.onLoad <- function(libname, pkgname)
{
rJava::.jpackage("xlsxjars")
rJava::.jpackage(pkgname, lib.loc = libname) # needed to load RInterface.java
set_java_tmp_dir(getOption("xlsx.tempdir", tempdir()))
wb <- createWorkbook() # load/initialize jars here as it takes
rm(wb) # a few seconds ...
options(xlsx.date.format = "m/d/yyyy") # e.g. 3/18/2013
options(xlsx.datetime.format = "m/d/yyyy h:mm:ss") # e.g. 3/18/2013 05:25:51
}
####################################################################
# Converts R color into Excel compatible color
# rcolor <- c("red", "blue")
#
.Rcolor2XLcolor <- function( rcolor, isXSSF=TRUE )
{
if ( isXSSF ) {
sapply( rcolor, .xssfcolor )
} else {
sapply( rcolor, .hssfcolor )
}
}
###################################################################
# Split a vector into contiguous chunks c(1,2,3, 6,7, 9,10,11)
# @param x an integer vector
# @return a list of integer vectors, each vector being a group.
#
.splitBlocks <- function(x)
{
blocks <- list(x[1])
if (length(x)==1)
return(blocks)
k <- 1
for (i in 2:length(x)) {
if (x[i]==(x[i-1]+1)) {
blocks[[k]] <- c(blocks[[k]], x[i])
} else {
k <- k+1
blocks[[k]] <- x[i]
}
}
blocks
}
########################################################################
# Take an R color and return an HSSFColor object
# @param Rcolor is a string
# NOTE: Only a limited set of colors are supported. See the java API.
#
.hssfcolor <- function(Rcolor)
{
.jshort(INDEXED_COLORS_[toupper( Rcolor )])
}
########################################################################
# Take an R color and return an XSSFColor object
# @param Rcolor is a string returned from "colors()" or a hex string
# starting with #, e.g. "#FF0000" is red.
#
#' @importFrom grDevices col2rgb
.xssfcolor <- function(Rcolor)
{
if (grepl("^#", Rcolor)) {
rgb <- c(strtoi(substring(Rcolor, 2, 3), base=16L),
strtoi(substring(Rcolor, 4, 5), base=16L),
strtoi(substring(Rcolor, 6, 7), base=16L))
} else {
rgb <- as.integer(col2rgb(Rcolor))
}
jcol <- .jnew("java.awt.Color", rgb[1], rgb[2], rgb[3])
.jnew("org.apache.poi.xssf.usermodel.XSSFColor", jcol)
}
#' Set Java Temp Directory
#'
#' Java sets the java temp directory to `/tmp` by default. However, this is
#' usually not desirable in R. As a result, this function allows changing that
#' behavior. Further, this function is fired on package load to ensure all
#' temp files are written to the R temp directory.
#'
#' On package load, we use `getOption("xlsx.tempdir", tempdir())` for the
#' default value, in case you want to have this value set by an option.
#'
#' @param tmp_dir optional. The new temp directory. Defaults to the R temp
#' directory
#'
#' @return The previous java temp directory (prior to any changes).
#'
#' @export
set_java_tmp_dir <- function(tmp_dir = tempdir()) {
rJava::.jcall(
"java/lang/System",
"Ljava/lang/String;",
"setProperty",
"java.io.tmpdir", tmp_dir
)
}
#' @rdname set_java_tmp_dir
#' @export
get_java_tmp_dir <- function() {
rJava::.jcall(
"java/lang/System",
"Ljava/lang/String;",
"getProperty",
"java.io.tmpdir"
)
}
#' @title Constants used in the project.
#'
#' @description Document some Apache POI constants used in the project.
#'
#' @return A named vector.
#' @author Adrian Dragulescu
#' @seealso \code{\link{CellStyle}} for using the \code{POI_constants}.
#' @name POI_constants
NULL
#' @rdname POI_constants
#' @export
HALIGN_STYLES_ <- c(2,6,4,0,5,1,3)
names(HALIGN_STYLES_) <- c('ALIGN_CENTER' ,'ALIGN_CENTER_SELECTION'
,'ALIGN_FILL' ,'ALIGN_GENERAL' ,'ALIGN_JUSTIFY' ,'ALIGN_LEFT'
,'ALIGN_RIGHT')
#' @rdname POI_constants
#' @export
VALIGN_STYLES_<- c(2,1,3,0)
names(VALIGN_STYLES_) <- c('VERTICAL_BOTTOM' ,'VERTICAL_CENTER',
'VERTICAL_JUSTIFY' ,'VERTICAL_TOP')
#' @rdname POI_constants
#' @export
BORDER_STYLES_ <- c(9,11,3,7,6,4,2,10,12,8,0,13,5,1)
names(BORDER_STYLES_) <- c("BORDER_DASH_DOT", "BORDER_DASH_DOT_DOT",
"BORDER_DASHED", "BORDER_DOTTED", "BORDER_DOUBLE", "BORDER_HAIR",
"BORDER_MEDIUM", "BORDER_MEDIUM_DASH_DOT",
"BORDER_MEDIUM_DASH_DOT_DOT", "BORDER_MEDIUM_DASHED",
"BORDER_NONE", "BORDER_SLANTED_DASH_DOT", "BORDER_THICK",
"BORDER_THIN")
#' @rdname POI_constants
#' @export
FILL_STYLES_<- c(3,9,10,16,2,18,17,0,1,4,15,7,8,5,6,13,14,11,12)
names(FILL_STYLES_) <- c('ALT_BARS', 'BIG_SPOTS','BRICKS' ,'DIAMONDS'
,'FINE_DOTS' ,'LEAST_DOTS' ,'LESS_DOTS' ,'NO_FILL'
,'SOLID_FOREGROUND' ,'SPARSE_DOTS' ,'SQUARES'
,'THICK_BACKWARD_DIAG' ,'THICK_FORWARD_DIAG' ,'THICK_HORZ_BANDS'
,'THICK_VERT_BANDS' ,'THIN_BACKWARD_DIAG' ,'THIN_FORWARD_DIAG'
,'THIN_HORZ_BANDS' ,'THIN_VERT_BANDS')
# from org.apache.poi.ss.usermodel.CellStyle
#' @rdname POI_constants
#' @export
CELL_STYLES_ <- c(HALIGN_STYLES_, VALIGN_STYLES_,
BORDER_STYLES_, FILL_STYLES_)
#' @rdname POI_constants
#' @export
INDEXED_COLORS_ <- c(8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,28,29,30,31,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,
56,57,58,59,60,61,62,63,64)
names(INDEXED_COLORS_) <- c('BLACK' ,'WHITE' ,'RED' ,'BRIGHT_GREEN'
,'BLUE' ,'YELLOW' ,'PINK' ,'TURQUOISE' ,'DARK_RED' ,'GREEN'
,'DARK_BLUE' ,'DARK_YELLOW' ,'VIOLET' ,'TEAL' ,'GREY_25_PERCENT'
,'GREY_50_PERCENT' ,'CORNFLOWER_BLUE' ,'MAROON' ,'LEMON_CHIFFON'
,'ORCHID' ,'CORAL' ,'ROYAL_BLUE' ,'LIGHT_CORNFLOWER_BLUE'
,'SKY_BLUE' ,'LIGHT_TURQUOISE' ,'LIGHT_GREEN' ,'LIGHT_YELLOW'
,'PALE_BLUE' ,'ROSE' ,'LAVENDER' ,'TAN' ,'LIGHT_BLUE' ,'AQUA'
,'LIME' ,'GOLD' ,'LIGHT_ORANGE' ,'ORANGE' ,'BLUE_GREY'
,'GREY_40_PERCENT' ,'DARK_TEAL' ,'SEA_GREEN' ,'DARK_GREEN'
,'OLIVE_GREEN' ,'BROWN' ,'PLUM' ,'INDIGO' ,'GREY_80_PERCENT'
,'AUTOMATIC')
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/utilities.R |
# Write a data.frame to a new xlsx file.
# A convenience function.
#
# System.gc() # to call the garbage collection in Java
#######################################################################
# NO rownames for this function. Just the contents of the data.frame!
# have showNA=TRUE for legacy reason
#
.write_block <- function(wb, sheet, y, rowIndex=seq_len(nrow(y)),
colIndex=seq_len(ncol(y)), showNA=TRUE)
{
rows <- createRow(sheet, rowIndex) # create rows
cells <- createCell(rows, colIndex) # create cells
for (ic in seq_len(ncol(y)))
mapply(setCellValue, cells[seq_len(nrow(cells)), colIndex[ic]], y[,ic], FALSE, showNA)
# Date and POSIXct classes need to be formatted
indDT <- which(sapply(y, function(x) inherits(x, "Date")))
if (length(indDT) > 0) {
dateFormat <- CellStyle(wb) + DataFormat(getOption("xlsx.date.format"))
for (ic in indDT){
lapply(cells[seq_len(nrow(cells)),colIndex[ic]], setCellStyle, dateFormat)
}
}
indDT <- which(sapply(y, function(x) inherits(x, "POSIXct")))
if (length(indDT) > 0) {
datetimeFormat <- CellStyle(wb) + DataFormat(getOption("xlsx.datetime.format"))
for (ic in indDT){
lapply(cells[seq_len(nrow(cells)),colIndex[ic]], setCellStyle, datetimeFormat)
}
}
}
#######################################################################
# High-level API
#
#' Write a data.frame to an Excel workbook.
#'
#' Write a \code{data.frame} to an Excel workbook.
#'
#'
#' This function provides a high level API for writing a \code{data.frame} to
#' an Excel 2007 worksheet. It calls several low level functions in the
#' process. Its goal is to provide the conveniency of
#' \code{\link[utils]{write.csv}} by borrowing from its signature.
#'
#' Internally, \code{write.xlsx} uses a double loop in over all the elements of
#' the \code{data.frame} so performance for very large \code{data.frame} may be
#' an issue. Please report if you experience slow performance. Dates and
#' POSIXct classes are formatted separately after the insertion. This also
#' adds to processing time.
#'
#' If \code{x} is not a \code{data.frame} it will be converted to one.
#'
#' Function \code{write.xlsx2} uses \code{addDataFrame} which speeds up the
#' execution compared to \code{write.xlsx} by an order of magnitude for large
#' spreadsheets (with more than 100,000 cells).
#'
#' The default formats for Date and DateTime columns can be changed via the two
#' package options \code{xlsx.date.format} and \code{xlsx.datetime.format}.
#' They need to be specified in Java date format
#' \url{https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html}.
#'
#' Writing of password protected workbooks is supported for Excel 2007 OOXML
#' format only. Note that in Linux, LibreOffice is not able to read password
#' protected spreadsheets.
#'
#' @param x a \code{data.frame} to write to the workbook.
#' @param file the path to the output file.
#' @param sheetName a character string with the sheet name.
#' @param col.names a logical value indicating if the column names of \code{x}
#' are to be written along with \code{x} to the file.
#' @param row.names a logical value indicating whether the row names of
#' \code{x} are to be written along with \code{x} to the file.
#' @param append a logical value indicating if \code{x} should be appended to
#' an existing file. If \code{TRUE} the file is read from disk.
#' @param showNA a logical value. If set to \code{FALSE}, NA values will be
#' left as empty cells.
#' @param ... other arguments to \code{addDataFrame} in the case of
#' \code{read.xlsx2}.
#' @param password a String with the password.
#' @author Adrian Dragulescu
#' @seealso \code{\link{read.xlsx}} for reading \code{xlsx} documents. See
#' also \code{\link{addDataFrame}} for writing a \code{data.frame} to a sheet.
#' @examples
#'
#' \dontrun{
#'
#' file <- paste(tempdir(), "/usarrests.xlsx", sep="")
#' res <- write.xlsx(USArrests, file)
#'
#' # to change the default date format
#' oldOpt <- options()
#' options(xlsx.date.format="dd MMM, yyyy")
#' write.xlsx(x, sheet) # where x is a data.frame with a Date column.
#' options(oldOpt) # revert back to defaults
#'
#' }
#'
#' @export
write.xlsx <- function(x, file, sheetName="Sheet1",
col.names=TRUE, row.names=TRUE, append=FALSE, showNA=TRUE,
password=NULL)
{
if (!is.data.frame(x))
x <- data.frame(x) # just because the error message is too ugly
iOffset <- jOffset <- 0
if (col.names)
iOffset <- 1
if (row.names)
jOffset <- 1
if (append && file.exists(file)){
wb <- loadWorkbook(file, password=password)
} else {
ext <- gsub(".*\\.(.*)$", "\\1", basename(file))
wb <- createWorkbook(type=ext)
}
sheet <- createSheet(wb, sheetName)
noRows <- nrow(x) + iOffset
noCols <- ncol(x) + jOffset
if (col.names){
rows <- createRow(sheet, 1) # create top row
cells <- createCell(rows, colIndex=1:noCols) # create cells
mapply(setCellValue, cells[1,(1+jOffset):noCols], colnames(x))
}
if (row.names) # add rownames to data x
x <- cbind(rownames=rownames(x), x)
colIndex <- seq_len(ncol(x))
rowIndex <- seq_len(nrow(x)) + iOffset
.write_block(wb, sheet, x, rowIndex, colIndex, showNA)
saveWorkbook(wb, file, password=password)
invisible()
}
# .jcall("java/lang/System", "V", "gc") # doesn't do anything!
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/write.xlsx.R |
# Write a data.frame to a new xlsx file.
# with a java back-end
#
#' @export
#' @rdname write.xlsx
write.xlsx2 <- function(x, file, sheetName="Sheet1",
col.names=TRUE, row.names=TRUE, append=FALSE,
password=NULL, ...)
{
if (append && file.exists(file)){
wb <- loadWorkbook(file, password=password)
} else {
ext <- gsub(".*\\.(.*)$", "\\1", basename(file))
wb <- createWorkbook(type=ext)
}
sheet <- createSheet(wb, sheetName)
addDataFrame(x, sheet, col.names=col.names, row.names=row.names,
startRow=1, startColumn=1, colStyle=NULL, colnamesStyle=NULL,
rownamesStyle=NULL)
saveWorkbook(wb, file, password=password)
invisible()
}
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/write.xlsx2.R |
#' Read, write, format Excel 2007 and Excel 97/2000/XP/2003 files
#'
#' The \code{xlsx} package gives programatic control of Excel files using R. A
#' high level API allows the user to read a sheet of an xlsx document into a
#' \code{data.frame} and write a \code{data.frame} to a file. Lower level
#' functionality permits the direct manipulation of sheets, rows and cells.
#' For example, the user has control to set colors, fonts, data formats, add
#' borders, hide/unhide sheets, add/remove rows, add/remove sheets, etc.
#'
#' Behind the scenes, the \code{xlsx} package uses a java library from the
#' Apache project, \url{https://poi.apache.org/index.html}. This Apache project
#' provides a Java API to Microsoft Documents (Excel, Word, PowerPoint,
#' Outlook, Visio, etc.) By using the \code{rJava} package that links and
#' Java, we can piggyback on the excellent work already done by the folks at
#' the Apache project and provide this functionality in R. The \code{xlsx}
#' package uses only a subset of the Apache POI project, namely the one dealing
#' with Excel files. All the necessary jar files are kept in package
#' \code{xlsxjars} that is imported by package \code{xlsx}.
#'
#' A collection of tests that can be used as examples are located in folder
#' \code{/tests/}. They are a good source of examples of how to use the
#' package.
#'
#' Please see \url{https://github.com/colearendt/xlsx/} for a Wiki and the
#' development version. To report a bug, use the Issues page at
#' \url{https://github.com/colearendt/xlsx/issues}.
#'
#' \tabular{ll}{ Package: \tab xlsx\cr Type: \tab Package\cr Version: \tab
#' 0.6.0\cr Date: \tab 2015-11-29\cr License: \tab GPL-3\cr }
#'
#' @aliases xlsx-package xlsx
#' @docType package
#'
#' @seealso \code{\link{Workbook}} for ways to work with \code{Workbook}
#' objects.
#' @references Apache POI project for Microsoft Excel format:
#' \url{https://poi.apache.org/components/spreadsheet/index.html}.
#'
#' The Java Doc detailing the classes:
#' \url{https://poi.apache.org/apidocs/index.html}. This can be useful if you
#' are looking for something that is not exposed in R as it may be available on
#' the Java side. Inspecting the source code for some the the functions in
#' this package can show you how to do it (even if you are Java shy.)
#' @keywords package
#' @examples
#'
#' \dontrun{
#'
#' library(xlsx)
#'
#' # example of reading xlsx sheets
#' file <- system.file("tests", "test_import.xlsx", package = "xlsx")
#' res <- read.xlsx(file, 2) # read the second sheet
#'
#' # example of writing xlsx sheets
#' file <- paste(tempfile(), "xlsx", sep=".")
#' write.xlsx(USArrests, file=file)
#'
#' }
#'
#' @import rJava
#' @import xlsxjars
#' @importFrom utils unzip
#' @importFrom utils zip
#' @name xlsx-package
NULL
| /scratch/gouwar.j/cran-all/cranData/xlsx/R/xlsx-package.R |
## ----setup, echo=FALSE, message=FALSE-----------------------------------------
knitr::opts_chunk$set(echo=TRUE, collapse=T, comment='#>')
library(rJava)
library(xlsx)
## ----theme--------------------------------------------------------------------
## fonts require a workbook
createFonts <- function(wb) {
list(
data = Font(wb, heightInPoints = 11, name='Arial')
, title = Font(wb, heightInPoints = 16, name='Arial', isBold = TRUE)
, subtitle = Font(wb, heightInPoints = 13, name='Arial', isBold = FALSE, isItalic = TRUE)
)
}
## alignment
alignLeft <- Alignment(horizontal='ALIGN_LEFT', vertical='VERTICAL_CENTER', wrapText = TRUE)
alignCenter <- Alignment(horizontal='ALIGN_CENTER', vertical='VERTICAL_CENTER', wrapText=TRUE)
## data formats
dataFormatDate <- DataFormat('m/d/yyyy')
dataFormatNumberD <- DataFormat('0.0')
## fill
fillPrimary <- Fill('#cc0000','#cc0000','SOLID_FOREGROUND')
fillSecondary <- Fill('#ff6666','#ff6666','SOLID_FOREGROUND')
## ----prep_for_report, include=FALSE-------------------------------------------
## todo: fix the xlsx jars being available when generating vignette
#.jaddClassPath(rprojroot::is_r_package$find_file('inst/java/rexcel-0.5.1.jar'))
## ----build_report, results='hide'---------------------------------------------
## The dataset
numbercol <- 9
mydata <- as.data.frame(lapply(1:numbercol,function(x){runif(15, 0,200)}))
mydata <- setNames(mydata,paste0('col',1:numbercol))
## Build report
wb <- createWorkbook()
sh <- createSheet(wb, 'Report')
f <- createFonts(wb)
headerrow <- createRow(sh, 1:2)
headercell <- createCell(headerrow, 1:ncol(mydata))
## title
addMergedRegion(sh,1,1,1,ncol(mydata))
lapply(headercell[1,],function(cell) {
setCellValue(cell, 'Title of Report')
setCellStyle(cell, CellStyle(wb) + f$title + alignCenter)
})
## subtitle
addMergedRegion(sh, 2,2, 1,ncol(mydata))
lapply(headercell[2,],function(cell) {
setCellValue(cell, 'A fantastic report about nothing')
setCellStyle(cell, CellStyle(wb) + f$subtitle + alignCenter )
})
## cell styles for data
cslist <- lapply(1:ncol(mydata), function(x){CellStyle(wb) + f$data + alignCenter + dataFormatNumberD})
cslist[1:2] <- lapply(cslist[1:2], function(x){x + alignLeft}) ## left align first two columns
## add data
workrow <- 4
addDataFrame(mydata, sh
, col.names=TRUE
, row.names = FALSE
, startRow = workrow
, startColumn = 1
, colStyle = setNames(cslist,1:numbercol)
, colnamesStyle = CellStyle(wb) + f$subtitle + alignCenter + fillPrimary
)
workrow <- workrow + nrow(mydata) + 1 ## + 1 for header
## add total row... sorta
## - (just the first row because I am lazy)
addDataFrame(mydata[1,], sh
, col.names=FALSE
, row.names=FALSE
, startRow = workrow
, startColumn = 1
, colStyle = setNames(lapply(cslist,function(x){x + fillSecondary}),1:numbercol)
)
saveWorkbook(wb, 'excel_report.xlsx')
| /scratch/gouwar.j/cran-all/cranData/xlsx/inst/doc/excel_report.R |
---
title: "Build Excel Reports from R"
author: "Cole Arendt"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
Vignette: >
%\VignetteIndexEntry{Build Excel Reports from R}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
%\VignetteKeywords{spreadsheet, Excel, java, report}
%\VignettePackage{xlsx}
---
```{r setup, echo=FALSE, message=FALSE}
knitr::opts_chunk$set(echo=TRUE, collapse=T, comment='#>')
library(rJava)
library(xlsx)
```
## Building Excel Reports in R
Excel has a lot of buy-in. This is generally pretty unfortunate, as there are
much better tools for data analysis (i.e. \R). Excel is also not
platform-agnostic, so there are difficulties generating Excel reports on
non-Windows systems. However, Java is, and the excellent [Apache
POI](https://poi.apache.org/) project provides a nice interface to Excel
documents in a platform-agnostic manner. Further, \R integrates nicely with
this project through the `xlsx` package to provide a suite of tools to be used
in data science and report generation on any operating system.
# From Scratch
The first step of any report generation from scratch is data preparation.
Suffice it to say that R has many tools to expedite that process. For instance,
the [`tidyverse`](https://www.tidyverse.org/) provides several packages for getting
data into a nice, _tidy_ format for modeling and visualization. We will presume
that you have your data structured the way that you want and focus on getting
that presentation into Excel.
## Functional Cell Styles
The `CellStyle` class in the `xlsx` package makes possible many of the desirable
traits of a good Excel report - Borders, DataFormats, Alignment, Font, and Fill.
While a bit verbose to type at times, the `+` operator is implemented to make
*building* these styles more natural. For instance, we might define a theme
which has a standard selection of fonts, colors, and formats.
```{r theme}
## fonts require a workbook
createFonts <- function(wb) {
list(
data = Font(wb, heightInPoints = 11, name='Arial')
, title = Font(wb, heightInPoints = 16, name='Arial', isBold = TRUE)
, subtitle = Font(wb, heightInPoints = 13, name='Arial', isBold = FALSE, isItalic = TRUE)
)
}
## alignment
alignLeft <- Alignment(horizontal='ALIGN_LEFT', vertical='VERTICAL_CENTER', wrapText = TRUE)
alignCenter <- Alignment(horizontal='ALIGN_CENTER', vertical='VERTICAL_CENTER', wrapText=TRUE)
## data formats
dataFormatDate <- DataFormat('m/d/yyyy')
dataFormatNumberD <- DataFormat('0.0')
## fill
fillPrimary <- Fill('#cc0000','#cc0000','SOLID_FOREGROUND')
fillSecondary <- Fill('#ff6666','#ff6666','SOLID_FOREGROUND')
```
Once we have defined such standard cell-styles, it is straightforward to use
them with the additive CellStyle framework.
```{r prep_for_report, include=FALSE}
## todo: fix the xlsx jars being available when generating vignette
#.jaddClassPath(rprojroot::is_r_package$find_file('inst/java/rexcel-0.5.1.jar'))
```
```{r build_report, results='hide'}
## The dataset
numbercol <- 9
mydata <- as.data.frame(lapply(1:numbercol,function(x){runif(15, 0,200)}))
mydata <- setNames(mydata,paste0('col',1:numbercol))
## Build report
wb <- createWorkbook()
sh <- createSheet(wb, 'Report')
f <- createFonts(wb)
headerrow <- createRow(sh, 1:2)
headercell <- createCell(headerrow, 1:ncol(mydata))
## title
addMergedRegion(sh,1,1,1,ncol(mydata))
lapply(headercell[1,],function(cell) {
setCellValue(cell, 'Title of Report')
setCellStyle(cell, CellStyle(wb) + f$title + alignCenter)
})
## subtitle
addMergedRegion(sh, 2,2, 1,ncol(mydata))
lapply(headercell[2,],function(cell) {
setCellValue(cell, 'A fantastic report about nothing')
setCellStyle(cell, CellStyle(wb) + f$subtitle + alignCenter )
})
## cell styles for data
cslist <- lapply(1:ncol(mydata), function(x){CellStyle(wb) + f$data + alignCenter + dataFormatNumberD})
cslist[1:2] <- lapply(cslist[1:2], function(x){x + alignLeft}) ## left align first two columns
## add data
workrow <- 4
addDataFrame(mydata, sh
, col.names=TRUE
, row.names = FALSE
, startRow = workrow
, startColumn = 1
, colStyle = setNames(cslist,1:numbercol)
, colnamesStyle = CellStyle(wb) + f$subtitle + alignCenter + fillPrimary
)
workrow <- workrow + nrow(mydata) + 1 ## + 1 for header
## add total row... sorta
## - (just the first row because I am lazy)
addDataFrame(mydata[1,], sh
, col.names=FALSE
, row.names=FALSE
, startRow = workrow
, startColumn = 1
, colStyle = setNames(lapply(cslist,function(x){x + fillSecondary}),1:numbercol)
)
saveWorkbook(wb, 'excel_report.xlsx')
```
Once you get used to some of the verbosity, the elegance of automatically
creating nicely formatted Excel reports on a UNIX platform from R begins to
shine. Further, with a bit of work implementing an R API, we get the benefit of
a robust Java community debugging issues behind the scenes at Apache. If you
would like to contribute on improving the R API and adding functionality, you
can do so [on github](https://github.com/colearendt/xlsx).
`)
Bonus: you can even customize print formatting and a whole host of other things!
There is more to come on that.
| /scratch/gouwar.j/cran-all/cranData/xlsx/inst/doc/excel_report.Rmd |
---
title: "Build Excel Reports from R"
author: "Adrian A. Dragulescu"
date: "`r Sys.Date()`"
output:
rmarkdown::html_vignette:
toc: true
number_sections: true
Vignette: >
%\VignetteIndexEntry{Read, write, format Excel 2007 (xlsx) files}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
%\VignetteKeywords{spreadsheet, Excel 2007, java}
%\VignettePackage{xlsx}
abstract: The `xlsx` package provides tools neccessary to interact with
Excel 2007 files from R. The user can read and write xlsx files, and
can control the appearance of the spreadsheet by setting data formats,
fonts, colors, borders. Set the print area, the zoom control, create
split and freeze panels, adding headers and footers. The package uses
a java library from the Apache POI project.
---
```{r setup, echo=FALSE, message=FALSE}
knitr::opts_chunk$set(echo=TRUE, collapse=T, comment='#>')
library(RefManageR)
bib <- ReadBib('xlsx.bib')
BibOptions(check.entries = FALSE, style = "markdown", cite.style = "numeric",bib.style = "numeric")
```
# Introduction
The package `xlsx` makes possible to interact with Excel 2007 files from R `r
Cite(bib,'R-base')`. While a power R user usually does not need to use Excel or
even avoids it altogether, there are cases when being able to generate Excel
output or read Excel files into R is a must. One such case is in an office
environment when you need to collaborate with co-workers who use Excel as their
primary tool. Another case is to use Excel for basic reporting of results. For
moderate data sets, the formatting capabilities of Excel can prove useful. A
flexible way to manipulate Excel 2007 xlsx files from R would then be a nice
addition.
The `xlsx` package focuses on Excel 2007 because for Excel 97 there are already
several solutions, `RODBC` `r Cite(bib,'RODBC')`, `readxl``r
Cite(bib,'readxl')`, etc. While some of these packages work with Excel 2007
files too, the contribution of the `xlsx` package is different.
The xlsx Excel 2007 file format is essentially a zipped set of xml
files. It is possible to interact directly with these files from R
as shown by the package `RExcelXML``r Cite(bib,'RExcelXML')`. All the
functionality of the `xlsx` package can be replicated with
`RExcelXML` package or by extending it. Working directly with
the zipped xml files, and using the xml schema to extract the useful
information into R gives you ultimate control.
The approach taken in the `xlsx` package is to use a proven,
existing API between Java and Excel 2007 and use the `rJava`
`r Cite(bib,'rJava')` package to link Java and R. The advantage of this
approach is that the code on the R side is very compact, easy to
maintain, and easy to extend even for people with little Java
experience. All the heavy lifting of parsing XML schemas is being
done in Java. We also benefit from a mature software project with
many developers, test suites, and users that report issues on the Java
side. In principle, this should make the maintainance of the
`xlsx` package easy. The Java API used by the `xlsx` is one
project of the Apache Software Foundation, called Apache POI and can
be found at [https://poi.apache.org/](https://poi.apache.org/).
The Apache POI Project's mission is to create and maintain Java APIs
for manipulating various file formats based upon the Office Open XML
standards (OOXML) and Microsoft's OLE 2 Compound Document format
(OLE2). These include Excel, Word, and PowerPoint documents. While
the focus of the `xlsx` package has been only on Excel files, extensions for
Word and PowerPoint documents are available in the
[ReporteRs](https://CRAN.R-project.org/package=ReporteRs)
package.
That said, sometimes using Java from R can be a bit tricky to configure and work
with. While using Apache POI allows us to benefit from a robust Java community,
others might prefer to use a C++ API and `Rcpp` to interact with the raw XML in
a way more natural to R. For more reading on this approach, see the
[openxlsx](https://CRAN.R-project.org/package=openxlsx)
package or [officer](https://CRAN.R-project.org/package=officer)
(for Word / PowerPoint).
# High level API
See `read.xlsx` for reading the sheet of an xlsx file into a
data.frame. See `write.xlsx` writing a data.frame to an xlsx
file.
# Low level API
See `Workbook` for creating workbooks. See `Worksheet` for
code to manipulate worksheets. See `Cell` for manipulating
cells.
See `OtherEffects` for various spreadsheet effects, for example,
merge cells, auto size columns, create freeze panels, create split
panels, set print area, set the zoom, etc.
Use `PrintSetup` for customizing the settings for printing.
## Cell Formatting
See `CellStyle` for how to format a particular cell.
Use `Font` to set a font.
# Conclusion
By adding a lightweight R layer on top of the Apache project Java
interface to Excel 2007 documents, we achieve a multi-platform
solution for interacting with Excel 2007 file formats from R.
# References
```{r results = "asis", echo = FALSE}
PrintBibliography(bib, .opts = list(check.entries = FALSE, sorting = "ynt"))
```
| /scratch/gouwar.j/cran-all/cranData/xlsx/inst/xlsx.Rmd |
---
title: "Build Excel Reports from R"
author: "Cole Arendt"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
Vignette: >
%\VignetteIndexEntry{Build Excel Reports from R}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
%\VignetteKeywords{spreadsheet, Excel, java, report}
%\VignettePackage{xlsx}
---
```{r setup, echo=FALSE, message=FALSE}
knitr::opts_chunk$set(echo=TRUE, collapse=T, comment='#>')
library(rJava)
library(xlsx)
```
## Building Excel Reports in R
Excel has a lot of buy-in. This is generally pretty unfortunate, as there are
much better tools for data analysis (i.e. \R). Excel is also not
platform-agnostic, so there are difficulties generating Excel reports on
non-Windows systems. However, Java is, and the excellent [Apache
POI](https://poi.apache.org/) project provides a nice interface to Excel
documents in a platform-agnostic manner. Further, \R integrates nicely with
this project through the `xlsx` package to provide a suite of tools to be used
in data science and report generation on any operating system.
# From Scratch
The first step of any report generation from scratch is data preparation.
Suffice it to say that R has many tools to expedite that process. For instance,
the [`tidyverse`](https://www.tidyverse.org/) provides several packages for getting
data into a nice, _tidy_ format for modeling and visualization. We will presume
that you have your data structured the way that you want and focus on getting
that presentation into Excel.
## Functional Cell Styles
The `CellStyle` class in the `xlsx` package makes possible many of the desirable
traits of a good Excel report - Borders, DataFormats, Alignment, Font, and Fill.
While a bit verbose to type at times, the `+` operator is implemented to make
*building* these styles more natural. For instance, we might define a theme
which has a standard selection of fonts, colors, and formats.
```{r theme}
## fonts require a workbook
createFonts <- function(wb) {
list(
data = Font(wb, heightInPoints = 11, name='Arial')
, title = Font(wb, heightInPoints = 16, name='Arial', isBold = TRUE)
, subtitle = Font(wb, heightInPoints = 13, name='Arial', isBold = FALSE, isItalic = TRUE)
)
}
## alignment
alignLeft <- Alignment(horizontal='ALIGN_LEFT', vertical='VERTICAL_CENTER', wrapText = TRUE)
alignCenter <- Alignment(horizontal='ALIGN_CENTER', vertical='VERTICAL_CENTER', wrapText=TRUE)
## data formats
dataFormatDate <- DataFormat('m/d/yyyy')
dataFormatNumberD <- DataFormat('0.0')
## fill
fillPrimary <- Fill('#cc0000','#cc0000','SOLID_FOREGROUND')
fillSecondary <- Fill('#ff6666','#ff6666','SOLID_FOREGROUND')
```
Once we have defined such standard cell-styles, it is straightforward to use
them with the additive CellStyle framework.
```{r prep_for_report, include=FALSE}
## todo: fix the xlsx jars being available when generating vignette
#.jaddClassPath(rprojroot::is_r_package$find_file('inst/java/rexcel-0.5.1.jar'))
```
```{r build_report, results='hide'}
## The dataset
numbercol <- 9
mydata <- as.data.frame(lapply(1:numbercol,function(x){runif(15, 0,200)}))
mydata <- setNames(mydata,paste0('col',1:numbercol))
## Build report
wb <- createWorkbook()
sh <- createSheet(wb, 'Report')
f <- createFonts(wb)
headerrow <- createRow(sh, 1:2)
headercell <- createCell(headerrow, 1:ncol(mydata))
## title
addMergedRegion(sh,1,1,1,ncol(mydata))
lapply(headercell[1,],function(cell) {
setCellValue(cell, 'Title of Report')
setCellStyle(cell, CellStyle(wb) + f$title + alignCenter)
})
## subtitle
addMergedRegion(sh, 2,2, 1,ncol(mydata))
lapply(headercell[2,],function(cell) {
setCellValue(cell, 'A fantastic report about nothing')
setCellStyle(cell, CellStyle(wb) + f$subtitle + alignCenter )
})
## cell styles for data
cslist <- lapply(1:ncol(mydata), function(x){CellStyle(wb) + f$data + alignCenter + dataFormatNumberD})
cslist[1:2] <- lapply(cslist[1:2], function(x){x + alignLeft}) ## left align first two columns
## add data
workrow <- 4
addDataFrame(mydata, sh
, col.names=TRUE
, row.names = FALSE
, startRow = workrow
, startColumn = 1
, colStyle = setNames(cslist,1:numbercol)
, colnamesStyle = CellStyle(wb) + f$subtitle + alignCenter + fillPrimary
)
workrow <- workrow + nrow(mydata) + 1 ## + 1 for header
## add total row... sorta
## - (just the first row because I am lazy)
addDataFrame(mydata[1,], sh
, col.names=FALSE
, row.names=FALSE
, startRow = workrow
, startColumn = 1
, colStyle = setNames(lapply(cslist,function(x){x + fillSecondary}),1:numbercol)
)
saveWorkbook(wb, 'excel_report.xlsx')
```
Once you get used to some of the verbosity, the elegance of automatically
creating nicely formatted Excel reports on a UNIX platform from R begins to
shine. Further, with a bit of work implementing an R API, we get the benefit of
a robust Java community debugging issues behind the scenes at Apache. If you
would like to contribute on improving the R API and adding functionality, you
can do so [on github](https://github.com/colearendt/xlsx).
`)
Bonus: you can even customize print formatting and a whole host of other things!
There is more to come on that.
| /scratch/gouwar.j/cran-all/cranData/xlsx/vignettes/excel_report.Rmd |
#####################################################################
library(openxlsx)
#####################################################################
# read xlsx files to dfs list
#####################################################################
#' Read-in Excel file (workbook) as a list of data frames.
#'
#' @param xlsxPath A path to the Excel file, a character.
#' @param rowNames Whether to read-in row names, a boolean.
#' @param colNames Whether to read-in column names, a boolean.
#' @param ... ... passed to read.xlsx function in the openxlsx package.
#' @return A list of data frames, each representing a sheet in the Excel file (sheet names are list element names).
#' @import openxlsx
#' @examples
#' # create example file
#' df1 <- data.frame(A=c(1, 2), B=c(3, 4))
#' df2 <- data.frame(C=c(5, 6), D=c(7, 8))
#' xlsx_fpath <- file.path(tempdir(), "testout.xlsx")
#' dfs2xlsx(withNames("sheet1", df1, "sheet2", df2), xlsx_fpath)
#' # read created file
#' dfs <- xlsx2dfs(xlsx_fpath)
#' file.remove(xlsx_fpath)
#' @export
xlsx2dfs <- function(xlsxPath, rowNames = TRUE, colNames = TRUE, ...) {
wb <- openxlsx::loadWorkbook(xlsxPath)
sheetNames <- names(wb)
res <- lapply(sheetNames, function(sheetName) {
openxlsx::read.xlsx(wb, sheet = sheetName, rowNames = rowNames, colNames = colNames, ...)
})
names(res) <- sheetNames
res
}
#####################################################################
# printing dfs to xlsx files
#####################################################################
#' Helper function for more convenient input (sheet name, data frame, sheet name, data frame, ...).
#'
#' @param ... alterning arguments: sheet name 1, data frame 1, sheet name 2, data frame 2, ...
#' @return A list of the data frames with the names given each before.
#' @examples
#' df1 <- data.frame(A=c(1, 2), B=c(3, 4))
#' df2 <- data.frame(C=c(5, 6), D=c(7, 8))
#' xlsx_fpath <- file.path(tempdir(), "testout.xlsx")
#' dfs2xlsx(withNames("sheet1", df1, "sheet2", df2), xlsx_fpath)
#' file.remove(xlsx_fpath)
#' @export
withNames <- function(...) {
p.l <- list(...)
len <- length(p.l)
if (len %% 2 == 1) {
stop("withNames call with odd numbers of arguments")
print()
}
seconds <- p.l[seq(2, len, 2)]
firsts <- p.l[seq(1, len, 2)]
names(seconds) <- unlist(firsts)
seconds
}
#' Write a list of data frames into an excel file with each data frame in a new sheet and the list element name as its sheet name.
#'
#' @param dfs A list of data frames (names in the list are the names of the sheets).
#' @param fpath A character string representing path and filename of the output.
#' @param rowNames A boolean indicating whether the first column of a table in every sheet contains row names of the table.
#' @param colNames A boolean indicating whether the first line of a table in every sheet contains a header.
#' @return Nothing. Writes out data frames into specified Excel file.
#' @import openxlsx
#' @examples
#' df1 <- data.frame(A=c(1, 2), B=c(3, 4))
#' df2 <- data.frame(C=c(5, 6), D=c(7, 8))
#' xlsx_fpath <- file.path(tempdir(), "testout.xlsx")
#' dfs2xlsx(withNames("sheet1", df1, "sheet2", df2), xlsx_fpath)
#' file.remove(xlsx_fpath)
#' @export
dfs2xlsx <- function(dfs, fpath, rowNames=TRUE, colNames=TRUE) {
wb <- createWorkbook()
Map(function(data, name) {
openxlsx::addWorksheet(wb, name)
openxlsx::writeData(wb, name, data, rowNames = rowNames, colNames = colNames)
}, dfs, names(dfs))
openxlsx::saveWorkbook(wb, file = fpath, overwrite = TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/xlsx2dfs/R/xlsx2dfs.R |
## ----setup, include = FALSE----------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
#devtools::use_mit_license()
## ----examples------------------------------------------------------------
#devtools::load_all()
library(xlsx2dfs)
df1 <- data.frame(genes = c("gene1", "gene2"),
count = c(23, 50))
df2 <- data.frame(genes = c("gene3", "gene4"),
count = c(100, 500))
# write one data frame on one sheet
dfs2xlsx(withNames("first sheet", df1), "../inst/extdata/test_one_df.xlsx")
# write more data frames into one file
dfs2xlsx(withNames("first data frame", df1,
"second data frame", df2), "../inst/extdata/test_two_dfs.xlsx")
# or create a data frame list with the desired names
# and print into xlsx file
df.list <- list(`first data frame`=df1,
`second data frame`=df2)
# actually "withNames()" is superfluous ...
dfs2xlsx(df.list, "../inst/extdata/test_two_dfs1.xlsx")
# write one data frame into a file
dfs2xlsx(list(`one data frame`=df1),
"../inst/extdata/one_df.xlsx")
# read-in excel file as a data frame list
dfs.list <- xlsx2dfs("../inst/extdata/test_two_dfs1.xlsx")
| /scratch/gouwar.j/cran-all/cranData/xlsx2dfs/inst/doc/xlsx2dfs.R |
---
title: "xlsx2dfs: Reading/Writing Excel File Sheets from/to List of Data Frames"
author: "Gwang-Jin Kim"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{"xlsx2dfs: Reading/Writing Excel File Sheets from/to List of Data Frames"}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
#devtools::use_mit_license()
```
This package is a wrapper for `openxlsx`.
It reads entire excel files with all their sheets into a list of data frames (one data frame for each sheet, one list of data frame for one excel file).
For creating an excel file, put together all your data frames into a list and give them names for the sheet titles.
The `withNames()` function helps during the input by making it possible to alternate name and data frame.
```{r examples}
#devtools::load_all()
library(xlsx2dfs)
df1 <- data.frame(genes = c("gene1", "gene2"),
count = c(23, 50))
df2 <- data.frame(genes = c("gene3", "gene4"),
count = c(100, 500))
# write one data frame on one sheet
dfs2xlsx(withNames("first sheet", df1), "../inst/extdata/test_one_df.xlsx")
# write more data frames into one file
dfs2xlsx(withNames("first data frame", df1,
"second data frame", df2), "../inst/extdata/test_two_dfs.xlsx")
# or create a data frame list with the desired names
# and print into xlsx file
df.list <- list(`first data frame`=df1,
`second data frame`=df2)
# actually "withNames()" is superfluous ...
dfs2xlsx(df.list, "../inst/extdata/test_two_dfs1.xlsx")
# write one data frame into a file
dfs2xlsx(list(`one data frame`=df1),
"../inst/extdata/one_df.xlsx")
# read-in excel file as a data frame list
dfs.list <- xlsx2dfs("../inst/extdata/test_two_dfs1.xlsx")
```
| /scratch/gouwar.j/cran-all/cranData/xlsx2dfs/inst/doc/xlsx2dfs.Rmd |
---
title: "xlsx2dfs: Reading/Writing Excel File Sheets from/to List of Data Frames"
author: "Gwang-Jin Kim"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{"xlsx2dfs: Reading/Writing Excel File Sheets from/to List of Data Frames"}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
#devtools::use_mit_license()
```
This package is a wrapper for `openxlsx`.
It reads entire excel files with all their sheets into a list of data frames (one data frame for each sheet, one list of data frame for one excel file).
For creating an excel file, put together all your data frames into a list and give them names for the sheet titles.
The `withNames()` function helps during the input by making it possible to alternate name and data frame.
```{r examples}
#devtools::load_all()
library(xlsx2dfs)
df1 <- data.frame(genes = c("gene1", "gene2"),
count = c(23, 50))
df2 <- data.frame(genes = c("gene3", "gene4"),
count = c(100, 500))
# write one data frame on one sheet
dfs2xlsx(withNames("first sheet", df1), "../inst/extdata/test_one_df.xlsx")
# write more data frames into one file
dfs2xlsx(withNames("first data frame", df1,
"second data frame", df2), "../inst/extdata/test_two_dfs.xlsx")
# or create a data frame list with the desired names
# and print into xlsx file
df.list <- list(`first data frame`=df1,
`second data frame`=df2)
# actually "withNames()" is superfluous ...
dfs2xlsx(df.list, "../inst/extdata/test_two_dfs1.xlsx")
# write one data frame into a file
dfs2xlsx(list(`one data frame`=df1),
"../inst/extdata/one_df.xlsx")
# read-in excel file as a data frame list
dfs.list <- xlsx2dfs("../inst/extdata/test_two_dfs1.xlsx")
```
| /scratch/gouwar.j/cran-all/cranData/xlsx2dfs/vignettes/xlsx2dfs.Rmd |
## .onLoad <- function(libname, pkgname)
## {
## .jpackage(pkgname)
## # what's your java version? Need >= 1.5.0.
## jversion <- .jcall('java.lang.System','S','getProperty','java.version')
## if (jversion < "1.5.0")
## stop(paste("Your java version is ", jversion,
## ". Need 1.5.0 or higher.", sep=""))
## }
| /scratch/gouwar.j/cran-all/cranData/xlsxjars/R/utilities.R |
#' @import plotrix
#' @import mvmeta
#' @title Galaxy Plot: A New Visualization Tool of Bivariate Meta-Analysis Studies
#' @description A new visualization method that simultaneously presents the effect sizes of bivariate outcomes and their standard errors in a two-dimensional space.
#' @author Chuan Hong, Chongliang Luo, Yong Chen
#' @usage galaxy(data, y1, s1, y2, s2, scale1, scale2, scale.adj,
#' corr, group, study.label, annotate, xlab, ylab, main, legend.pos)
#'
#' @param data dataset with at least 4 columns for the effect sizes of the two outcomes and their standard errors
#' @param y1 column name for outcome 1, default is 'y1'
#' @param s1 column name for standard error of \code{y1}, default is 's1'
#' @param y2 column name for outcome 2, default is 'y2'
#' @param s2 column name for standard error of \code{y2}, default is 's2'
#' @param scale1 parameter for the length of the cross hair: the ellipse width is scale1 / s1 * scale.adj
#' @param scale2 parameter for the length of the cross hair: the ellipse height is scale2 / s2 * scale.adj
#' @param scale.adj a pre-specified parameter to adjust for \code{scale1} and \code{scale2}
#' @param corr column name for within-study correlation
#' @param group column name for study group
#' @param study.label column name for study label
#' @param annotate logical specifying whether study label should be added to the plot, default is FALSE.
#' @param xlab x axis label, default \code{y1}
#' @param ylab y axis label, default \code{y2}
#' @param main main title
#' @param legend.pos The position of the legend for study groups if \code{group} is specified, see \code{legend}, default is 'bottomright'.
#' @details This function returns the galaxy plot to visualize bivariate meta-analysis data,
#' which faithfully retains the information in two separate funnel plots, while providing
#' useful insights into outcome correlations, between-study heterogeneity and joint asymmetry.
#' Galaxy plot: a new visualization tool of bivariate meta-analysis studies.
#' Funnel plots have been widely used to detect small study effects in the results of
#' univariate meta-analyses. However, there is no existing visualization tool that is
#' the counterpart of the funnel plot in the multivariate setting. We propose a new
#' visualization method, the galaxy plot, which can simultaneously present the effect sizes
#' of bivariate outcomes and their standard errors in a two-dimensional space.
#' The galaxy plot is an intuitive visualization tool that can aid in interpretation
#' of results of multivariate meta-analysis. It preserves all of the information presented
#' by separate funnel plots for each outcome while elucidating more complex features that
#' may only be revealed by examining the joint distribution of the bivariate outcomes.
#' @return NULL
#'
#' @references Hong, C., Duan, R., Zeng, L., Hubbard, R., Lumley, T., Riley, R., Chu, H., Kimmel, S., and Chen, Y. (2020)
#' Galaxy Plot: A New Visualization Tool of Bivariate Meta-Analysis Studies, American Journal of Epidemiology, https://doi.org/10.1093/aje/kwz286.
#' @examples
#' data(sim_dat)
#' galaxy(data=sim_dat, scale.adj = 0.9, corr = 'corr', group = 'subgroup',
#' study.label = 'study.id', annotate = TRUE, main = 'galaxy plot')
#'
#' @export
galaxy <- function(data, y1='y1', s1='s1', y2='y2', s2='s2', scale1, scale2, scale.adj=1,
corr=NULL, group=NULL, study.label=NULL, annotate=F,
xlab, ylab, main, legend.pos='bottomright'){
if(!y1 %in% names(data)) stop('column y1 = ', y1, ' not found, please specify it!')
if(!s1 %in% names(data)) stop('column s1 = ', s1, ' not found, please specify it!')
if(!y2 %in% names(data)) stop('column y2 = ', y2, ' not found, please specify it!')
if(!s2 %in% names(data)) stop('column s2 = ', s2, ' not found, please specify it!')
names(data)[names(data)==y1] <- 'y1'
names(data)[names(data)==s1] <- 's1'
names(data)[names(data)==y2] <- 'y2'
names(data)[names(data)==s2] <- 's2'
n.remove <- sum(is.na(data$y1) | is.na(data$s1) | is.na(data$y2) | is.na(data$s2) | data$s1==0 | data$s2==0)
if(n.remove > 0) warning(n.remove, ' studies removed due to NA or zero se!' )
data <- data[!(is.na(data$y1) | is.na(data$s1) | is.na(data$y2) | is.na(data$s2) | data$s1==0 | data$s2==0),]
n <- nrow(data)
## within-study correlation
if(!is.null(corr)){
names(data)[names(data) == corr] <- 'corr'
angle1 <- asin(data$corr)
}
## group variable
if(!is.null(group)){
names(data)[names(data) == group] <- 'group'
data$group <- factor(data$group)
}
## study label
if(!is.null(study.label)){
names(data)[names(data) == study.label] <- 'study.label'
}
## scale of the ellipses for y1 and y2
if(missing(scale1)){
scale1 <- (max(data$y1) - min(data$y1) ) / n * quantile(data$s1, 0.2)
}
if(missing(scale2)){
scale2 <- (max(data$y2) - min(data$y2) ) / n * quantile(data$s2, 0.2)
}
scale1 <- scale1 * scale.adj
scale2 <- scale2 * scale.adj
message('scale of the ellipses are: scale1 = ', round(scale1,4), ', scale2 = ', round(scale2,4))
## galaxy center
junk1 = mvmeta(data$y1, data$s1^2, method = "fixed")
junk2 = mvmeta(data$y2, data$s2^2, method = "fixed")
b = c(junk1$coefficients, junk2$coefficients)
## endpoints of the hairs
ax0 <- data$y1 - scale1 * 1.2/data$s1
ax1 <- data$y1 + scale1 * 1.2/data$s1
ay0 <- data$y2 - scale2 * 1.2/data$s2
ay1 <- data$y2 + scale2 * 1.2/data$s2
## span of x and y axis
dx <- max(ax1) - min(ax0)
dy <- max(ay1) - min(ay0)
res = plot(# c(min(data$y1) - 1, max(data$y1) + 1), c(min(data$y2) - 1, max(data$y2) + 1),
c(min(ax0), max(ax1)) + 0.05 * c(-1, 1) * dx, c(min(ay0), max(ay1)) + 0.05 * c(-1, 1) * dy,
type = "n", xlab = ifelse(missing(xlab), y1, xlab),
ylab = ifelse(missing(ylab), y2, ylab),
cex.main = 2, main = ifelse(missing(main), '', main))
draw.ellipse(data$y1, data$y2, scale1/data$s1, scale2/data$s2, col=as.numeric(data$group)+1)
if(!is.null(group)){ # color fill ellipse for group of studies
legend(legend.pos, pch=19, col=seq_along(levels(data$group))+1, legend = levels(data$group))
}
if(!is.null(corr)){ # arrow for within-study correlation
ll <- sqrt((scale1/data$s1)^2+(scale2/data$s2)^2) / sqrt(dx^2+dy^2) * 0.7
arrows(data$y1, data$y2, data$y1+ll*cos(angle1)*dx, data$y2+ll*sin(angle1)*dy, length = 0.05)
}
points(x = b[1], y = b[2], col = "red", pch = 8, cex = 2, lwd = 3)
segments(data$y1, ay0, data$y1, ay1 )
segments(ax0, data$y2, ax1, data$y2 )
# segments(data$y1, data$y2, data$y1, (data$y2 + scale2 * 1.2/data$s2) )
# segments(data$y1, data$y2, data$y1, (data$y2 - scale2 * 1.2/data$s2) )
# segments(data$y1, data$y2, (data$y1 + scale1 * 1.2/data$s1), data$y2 )
# segments(data$y1, data$y2, (data$y1 - scale1 * 1.2/data$s1), data$y2 )
if(annotate==T) text(data$y1, data$y2, data$study.label, adj = c(0,1)) # annotate study id's
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/xmeta/R/galaxy.R |
####' @useDynLib
#' @import MASS
#' @import metafor
#' @import mvmeta
#' @title Bivariate trim&fill method
#' @description Bivariate T&F method accounting for small-study effects in bivariate meta-analysis, based on symmetry of the galaxy plot.
#' @author Chongliang Luo, Yong Chen
#'
#' @param y1 vector of the effect size estimates of the first outcome
#' @param v1 estimated variance of \code{y1}
#' @param y2 vector of the effect size estimates of the second outcome
#' @param v2 estimated variance of \code{y2}
#' @param n.grid number of grid (equally spaced) candidate directions that the optimal projection direction are searched among, see Details
#' @param angle angles of candidate projection directions not by grid, this will overwrite n.grid
#' @param estimator estimator used for the number of trimmed studies in univariate T&F on the projected studies, one of c('R0', 'L0', 'Q0')
#' @param side either "left" or "right", indicating on which side of the galaxy plot
#' the missing studies should be imputed. If null determined by the univariate T&F
#' @param rho correlation between y1 and y2 when computing the variance of the projected studies. Default is the estimated cor(y1, y2)
#' @param method method to estimate the center for the bivariate outcomes. Default is 'mm', i.e. random-effects model
#' @param method.uni method to estimate the center for the univariate projected studies using a univariate T&F procedure. Default is 'DL', i.e. fixed-effects model
#' @param maxiter max number of iterations used in the univariate T&F. Default is 20.
#' @param var.names names of the two outcomes used in the galaxy plot (if plotted). Default is c('y1', 'y2')
#' @param scale constant scale for plotting the galaxy plot for the bivariate studies, Default is 0.02.
#' @param verbose plot the galaxy plot? Default is FALSE.
#' @return List with component:
#' @return res a data.frame of 9 columns and n.grid rows. Each row is the result for projection along one candidate grid direction, and the columns are named:
#' 'y1.c', 'y2.c' for projected bivariate center, 'y1.f', 'y2.f' for bivariate center using filled studies,
#' 'k0', 'se.k0' for estimated number of trimmed studies and its standard error, 'se.y1.f', 'se.y2.f' for standard errors of 'y1.f', 'y2.f',
#' 'side.left' for the estimated side
#' @return ID.trim list of vectors of ids of studies been trimmed along each of the candidate direction.
#' @details The bivariate T&F method assumes studies are suppressed based on a weighted sum of the two outcomes, i.e. the studies with smallest values
#' of z_i = c_1 * y_1i + c_2 * y_2i, i=1,...,N are suppressed. We use a searching algorithm to find the optimal ratio of c_1 and c_2 (i.e. a direction),
#' which gives the most trimmed studies. This is based on the observation that the closer a direction is to the truth, the more studies
#' are expected to be trimmed along that direction. We set a sequence of equally-spaced candidate directions with angle a_m = m*pi/M,
#' and (c_1, c_2) = (cos(a_m), sin(a_m)), m=1,...,M.
#'
#' @references Luo C, Marks-Anglin AK, Duan R, Lin L, Hong C, Chu H, Chen Y. Accounting for small-study effects
#' using a bivariate trim and fill meta-analysis procedure. medRxiv. 2020 Jan 1.
#' @examples
#' \dontrun{
#' require(MASS)
#' require(mvmeta)
#' require(metafor)
#' set.seed(123)
#' mydata <- dat.gen(m.o=50, m.m=20, # # observed studies, # missing studies
#' s.m= c(0.5, 0.5), # c(mean(s1), mean(s2))
#' angle.LC = pi/4, # suppress line direction
#' mybeta=c(2,2), # true effect size
#' tau.sq=c(0.1, 0.1), # true between-study var
#' rho.w=0.5, rho.b=0.5, # true within-study and between-study corr
#' s.min = 0.1, # s1i ~ Unif(s.min, 2*s.m[1]-s.min)
#' verbose = TRUE)
#'
#' y1 <- mydata$mydat.sps$y1
#' y2 <- mydata$mydat.sps$y2
#' v1 <- mydata$mydat.sps$s1^2
#' v2 <- mydata$mydat.sps$s2^2
#'
#' ## unadjusted est
#' mv_obs <- mvmeta(cbind(y1, y2), cbind(v1, v2), method='mm')
#' c(mv_obs$coef)
#' # 2.142687 2.237741
#'
#' estimator <- 'R0'
#' ## univariate T&F based on y1 or y2
#' y1.rma <- rma(y1, v1, method='FE')
#' y2.rma <- rma(y2, v2, method='FE')
#' y1.tf <- trimfill_rma(y1.rma, estimator = estimator, method.fill = 'DL')
#' y2.tf <- trimfill_rma(y2.rma, estimator = estimator, method.fill = 'DL')
#' c(y1.tf$beta, y2.tf$beta)
#' # 2.122231 2.181333
#' c(y1.tf$k0, y2.tf$k0)
#' # 2 8
#'
#' ## bivariate T&F method (based on galaxy plot)
#' tf.grid <- galaxy.trimfill(y1, v1, y2, v2, n.grid = 12,
#' estimator=estimator, side='left',
#' method.uni = 'FE',
#' method = 'mm',
#' rho=0.5, maxiter=100, verbose=FALSE)
#' tf.grid$res
#' tf.grid$res[which(tf.grid$res$k0==max(tf.grid$res$k0)),3:5]
#' # y1.f y2.f k0
#' # 2.053306 2.162347 14
#'
#' ## less bias by the proposed bivariate T&F method
#' rbind(true = c(2,2),
#' unadjusted=c(mv_obs$coef),
#' tf.uni = c(y1.tf$beta, y2.tf$beta),
#' tf.biv = tf.grid$res[which(tf.grid$res$k0==max(tf.grid$res$k0)),3:4])
#'
#' ## unlike the univariate T&Fs, biv T&F obtains one estimate of # missing studies
#' c(k0.true = 20,
#' k0.tf.uni.y1 = y1.tf$k0,
#' k0.tf.uni.y2 = y2.tf$k0,
#' k0.tf.biv = tf.grid$res[which(tf.grid$res$k0==max(tf.grid$res$k0)),5])
#' # k0.true k0.tf.uni.y1 k0.tf.uni.y2 k0.tf.biv
#' # 20 2 8 14
#' }
#' @export
galaxy.trimfill <- function(y1, v1, y2, v2, n.grid = 12, angle, estimator, side, rho=0, method='mm', method.uni='DL',
maxiter=20, var.names=c('y1', 'y2'), scale=0.02, verbose=FALSE){
k <- length(y1)
## calculate initial mean est
# y1.rma <- rma(y1, v1)$beta
# y2.rma <- rma(y2, v2)$beta
# y.center <- c(y1.rma$beta, y2.rma$beta)
mv_obs = mvmeta(cbind(y1,y2), cbind(v1,v2), method=method)
y.center <- mv_obs$coef
##
if(verbose){
ylim <- c(min(y2), (max(y2)-min(y2))*1.5+min(y2))
plot(y2 ~ y1, pch='.', ylim=ylim,
xlab=var.names[1], ylab=var.names[2],
main=paste('Trim-fill of galaxy plot, # study =', k))
plotrix::draw.ellipse(x=y1, y=y2,
a = sqrt(max(v1) / v1)*scale,
b = sqrt(max(v2) / v2)*scale, angle = 0)
text(y.center[1], y.center[2], '*', col=0+2, cex=3)
text(min(y1)*0.3+max(y1)*0.7, ylim[1]+(ylim[2]-ylim[1])*(0.99-0*0.03),
paste(round(y.center[1],3), round(y.center[2],3)), col=0+2) # 'iter =', 0, ', k0 =', 0,
}
# the Linear Combination of (y1, y2) along the n.grid projection lines
if(!missing(angle)){
n.grid <- length(angle)
} else{
angle <- c(0:(n.grid-1)) * pi / n.grid
}
# cat(angle, '\n')
res <- matrix(NA, n.grid, 2*4+1) # add side, 1=left, 0=right
ID.trim <- list() # keep id trimmed for each direction
for(ig in 1:n.grid){
theta <- angle[ig]
LC.grid <- y1 * cos(theta) + y2 * sin(theta)
LC.v.grid <- v1*cos(theta)^2 + v2*sin(theta)^2 + rho*sin(theta*2)*sqrt(v1*v2)
rma.grid <- rma.uni(LC.grid, LC.v.grid, method=method.uni)
# cat(ig, rma.grid$beta, '\n')
res[ig, 1:2] <- c(y.center) * c(cos(theta), sin(theta)) # c(rma.grid$beta)
# LC.center <- sum( y.center * c(cos(theta), sin(theta)) )
tf.grid <- trimfill_rma(rma.grid, side=side, estimator=estimator, maxiter=maxiter)
res[ig, 5:6] <- c(tf.grid$k0, tf.grid$se.k0)
# fill studies symmetric to the trimmed studies
if(tf.grid$k0 > 0){
id.trim <- order(LC.grid, decreasing = ifelse(tf.grid$side=='left',TRUE, FALSE))[1:tf.grid$k0]
ID.trim[[ig]] <- id.trim
y.c.grid <- c(mvmeta(cbind(y1,y2)[-id.trim,], cbind(v1,v2)[-id.trim,], method=method)$coef)
y.fill <- rbind(cbind(y1,y2), t(2*y.c.grid - t(matrix(cbind(y1,y2)[id.trim,], ncol=2)) ))
v.fill <- rbind(cbind(v1,v2), cbind(v1,v2)[id.trim,] )
tmp <- mvmeta(y.fill, v.fill, method=method)
res[ig, c(3:4,7:8)] <- c(tmp$coef, sqrt(diag(tmp$vcov)))
} else {
res[ig, c(3:4,7:8)] <- c(y.center, sqrt(diag(mv_obs$vcov)))
}
# add side, 1=left, 0=right
res[ig, 9] <- ifelse(tf.grid$side=='left', 1, 0)
} # end for grid
colnames(res) <- c('y1.c', 'y2.c', 'y1.f', 'y2.f', 'k0', 'se.k0', 'se.y1.f', 'se.y2.f', 'side.left')
i.max <- which.max(res[,5])[1]
angle.max <- angle[i.max]
if(verbose){
text(min(y1)*0.3+max(y1)*0.7, ylim[1]+(ylim[2]-ylim[1])*(0.95), paste(res[,5], collapse = ',') )
text(min(y1)*0.3+max(y1)*0.7, ylim[1]+(ylim[2]-ylim[1])*(0.9), paste(estimator, ', max # trimmed= ', max(res[,5])) )
abline(0, tan(angle.max+0.0001), lty='dashed' )
text(res[i.max, 3], res[i.max, 4], '+', col=0+4, cex=3)
# text(min(y1)*0.3+max(y1)*0.7, ylim[1]+(ylim[2]-ylim[1])*(0.8), paste(round(center.true[1],3), round(center.true[2],3)), col='green')
# text(min(y1)*0.3+max(y1)*0.7, ylim[1]+(ylim[2]-ylim[1])*(0.75), paste(round(res[i.max,3],3), round(res[i.max,4],3)), col='blue')
# if(is.null(center.true)){
ll = c('* obs', '+ T&F')
cc = c(2,4)
# }else{
# ll = c('* obs', '# true', '+ T&F')
# cc = c(2:4)
# }
legend('topleft', legend=ll, col=cc)
}
return(list(res=data.frame(res),
ID.trim=ID.trim))
}
#' @import metafor
#' @title Trim&fill method for univariate meta analysis
#'
#' @description Modified metafor::trimfill.rma.uni to avoid the invalid sqrt in k0 calculation when estimator == "Q0"
#' @author Chongliang Luo, Yong Chen
#'
#' @param x an object of class "rma.uni".
#' @param side the same as in metafor::trimfill
#' @param estimator the same as in metafor::trimfill
#' @param maxiter the same as in metafor::trimfill
#' @param method.trim the model used in rma.uni() for estimating the center when trimming studies, default is x$method
#' @param method.fill the model used in rma.uni() for estimating the center after filling studies, default is x$method
#' @param verbose the same as in metafor::trimfill
#' @param ilim limits for the imputed values as in metafor::trimfill. If unspecified, no limits are used.
#' @return the same as in metafor::trimfill
#' @details It is recommend using fixed-effects for method.trim and random-effects for method.fill when heterogeneity exists.
#'
#' @export
trimfill_rma <- function(x, side, estimator = "L0", maxiter = 100, method.trim=NULL,
method.fill=NULL,verbose = FALSE, ilim) {
if(is.null(method.trim)) method.trim <- x$method
if(is.null(method.fill)) method.fill <- x$method
Tn.coef=2
if (missing(side))
side <- NULL
estimator <- match.arg(estimator, c("L0", "R0", "Q0"))
if (x$k == 1)
stop("Stopped because k = 1.")
yi <- x$yi
vi <- x$vi
wi <- x$weights
ni <- x$ni
res <- suppressWarnings(rma.uni(yi, vi, weights = wi, mods = sqrt(vi), method = 'DL', weighted = x$weighted))
tau2 <- res$tau2
if (is.null(side)) {
if (res$beta[2] < 0) {
side <- "right"
}
else {
side <- "left"
}
}
else {
side <- match.arg(side, c("left", "right"))
}
if (side == "right")
yi <- -1 * yi
ix <- sort(yi, index.return = TRUE)$ix
yi <- yi[ix]
vi <- vi[ix]
wi <- wi[ix]
ni <- ni[ix]
k <- length(yi)
k0.sav <- -1
k0 <- 0
iter <- 0
if (verbose)
cat("\n")
while (abs(k0 - k0.sav) > 0 & iter <= maxiter) {
k0.sav <- k0
iter <- iter + 1
if (iter > maxiter)
warning("Trim and fill algorithm did not converge.") # output with warning
yi.t <- yi[seq_len(k - k0)]
vi.t <- vi[seq_len(k - k0)]
wi.t <- wi[seq_len(k - k0)]
res <- suppressWarnings(rma.uni(yi.t, vi.t, weights = wi.t,
method = method.trim, weighted = x$weighted))
beta <- c(res$beta)
yi.c <- yi - beta
yi.cp <- yi.c
yi.c.r <- rank(abs(yi.cp), ties.method = "first")
yi.c.r.s <- sign(yi.cp) * yi.c.r
if (estimator == "R0") {
k0 <- (k - max(-1 * yi.c.r.s[yi.c.r.s < 0])) - 1
se.k0 <- sqrt(2 * max(0, k0) + 2)
}
if (estimator == "L0") {
Sr <- sum(yi.c.r.s[yi.c.r.s > 0])
k0 <- (4 * Sr - k * (k + 1))/(Tn.coef * k - 1)
varSr <- 1/24 * (k * (k + 1) * (2 * k + 1) + 10 *
k0^3 + 27 * k0^2 + 17 * k0 - 18 * k * k0^2 -
18 * k * k0 + 6 * k^2 * k0)
se.k0 <- 4 * sqrt(varSr)/(Tn.coef * k - 1)
}
if (estimator == "Q0") {
# Sr <- sum(yi.c.r.s[yi.c.r.s > 0])
Sr <- min(sum(yi.c.r.s[yi.c.r.s > 0]), k*(k-1)/2) # cap Sr to avoid sqrt in k0 invalid
# cat(iter, Sr, '\n')
k0 <- k - 1/2 - sqrt(2 * k^2 - 4 * Sr + 1/4)
varSr <- 1/24 * (k * (k + 1) * (2 * k + 1) + 10 *
k0^3 + 27 * k0^2 + 17 * k0 - 18 * k * k0^2 -
18 * k * k0 + 6 * k^2 * k0)
se.k0 <- 2 * sqrt(varSr)/sqrt((k - 1/2)^2 - k0 *
(2 * k - k0 - 1))
}
k0 <- max(0, round(k0))
se.k0 <- max(0, se.k0)
}
if (k0 > 0) {
if (side == "right") {
yi.c <- -1 * (yi.c - beta)
}
else {
yi.c <- yi.c - beta
}
yi.fill <- c(x$yi.f, -1 * yi.c[(k - k0 + 1):k])
if (!missing(ilim)) {
ilim <- sort(ilim)
yi.fill[yi.fill < ilim[1]] <- ilim[1]
yi.fill[yi.fill > ilim[2]] <- ilim[2]
}
vi.fill <- c(x$vi.f, vi[(k - k0 + 1):k])
wi.fill <- c(x$weights.f, wi[(k - k0 + 1):k])
ni.fill <- c(x$ni.f, ni[(k - k0 + 1):k])
attr(yi.fill, "measure") <- x$measure
res <- suppressWarnings(rma.uni(yi.fill, vi.fill, weights = wi.fill,
ni = ni.fill, method = method.fill, weighted = x$weighted ))
res$fill <- c(rep(FALSE, x$k.f), rep(TRUE, k0))
res$ids <- c(x$ids, (max(x$ids) + 1):(max(x$ids) + k0))
if (x$slab.null) {
res$slab <- c(paste("Study", x$ids), paste("Filled", seq_len(k0)))
}
else {
res$slab <- c(x$slab, paste("Filled", seq_len(k0)))
}
res$slab.null <- FALSE
}
else {
res <- x
res$fill <- rep(FALSE, k)
}
res$k0 <- k0
res$se.k0 <- se.k0
res$side <- side
res$k0.est <- estimator
res$k.all <- x$k.all + k0
if (estimator == "R0") {
m <- -1:(k0 - 1)
res$p.k0 <- 1 - sum(choose(0 + m + 1, m + 1) * 0.5^(0 + m + 2))
}
else {
res$p.k0 <- NA
}
class(res) <- c("rma.uni.trimfill", class(res))
return( res)
}
#' @import MASS
#' @title Generate bivariate meta analysis studies
#' @description Generate bivariate meta analysis studies based on random-effects model,
#' some studies with smallest weighted sum of the two outcomes are suppressed.
#' @author Chongliang Luo, Yong Chen
#'
#' @param m.o number of observed studies
#' @param m.m number of missing / suppressed studies
#' @param s.m vector of the mean of the variances of the two outcomes
#' @param angle.LC direction of suppressing line, default is pi/4, i.e. the studies on the left bottom corner are missing
#' @param mybeta the true center of the effect sizes
#' @param tau.sq between-study variance, the larger it is the more heterogeneity.
#' @param rho.w within-study correlation of the two outcomes
#' @param rho.b between-study correlation of the two outcomes
#' @param s.min minimum of the variances of the outcomes, default is 0.01
#' @param m.m.o number of studies on one side of the suppressing line been observed,
#' i.e. non-deterministic suppressing, default is 0, i.e. deterministic suppressing
#' @param s2.dist options for generating the outcomes' variances. 1=runif, 2=runif^2, 3=runif^4, 4=rnorm
#' @param verbose logical, galaxy plot the studies? Default FALSE
#' @references Luo C, Marks-Anglin AK, Duan R, Lin L, Hong C, Chu H, Chen Y. Accounting for small-study effects
#' using a bivariate trim and fill meta-analysis procedure. medRxiv. 2020 Jan 1.
#' @export
dat.gen <- function(m.o, m.m, s.m, angle.LC = pi/4,
mybeta,
tau.sq,
rho.w,
rho.b,
s.min=0.01,
m.m.o=0,
s2.dist = 2,
verbose=F ){
# total SS = observed + missing (suppressed)
m <- m.o+m.m
n.m.o <- m.m * m.m.o
# s1.sq <- runif(m, s1.m*0.1, s1.m*1.9); s2.sq <- runif(m, s2.m*0.1, s2.m*1.9);
s1.m <- s.m[1]; s2.m <- s.m[2];
tau1.sq <- tau.sq[1]; tau2.sq <- tau.sq[2]
myCov.theta = matrix(c(tau1.sq, rho.b*sqrt(tau1.sq*tau2.sq),
rho.b*sqrt(tau1.sq*tau2.sq), tau2.sq), nrow=2)
myTheta = mvrnorm(n=m, mu=mybeta, Sigma=myCov.theta)
# s1.sq <- rgamma(m, 3, 3/s1.m)^2 * sqrt(abs(myTheta[,1] - mybeta[1]));
# s2.sq <- rgamma(m, 3, 3/s2.m)^2 * sqrt(abs(myTheta[,2] - mybeta[2]));
if(s2.dist==1){
s1.sq <- runif(m, s.min, 2*s1.m-s.min)
s2.sq <- runif(m, s.min, 2*s2.m-s.min)
} else if(s2.dist==2){
s1.sq <- runif(m, s.min, 2*s1.m-s.min)^2
s2.sq <- runif(m, s.min, 2*s2.m-s.min)^2
}else if(s2.dist==3){
s1.sq <- runif(m, s.min, 2*s1.m-s.min)^4
s2.sq <- runif(m, s.min, 2*s2.m-s.min)^4
}else if(s2.dist==4){
s1.sq <- rnorm(m, s1.m, s.min)^2
s2.sq <- rnorm(m, s2.m, s.min)^2
}
y=array(NA, c(m,2))
for (i in 1:m){
mySigma = matrix(c(s1.sq[i], rho.w*sqrt(s1.sq[i]*s2.sq[i]),
rho.w*sqrt(s1.sq[i]*s2.sq[i]), s2.sq[i]), nrow=2, byrow=TRUE)
y[i,]=mvrnorm(n=1, myTheta[i,], Sigma=mySigma)
}
y1=y[,1]
y2=y[,2]
a.sps <- cos(angle.LC+0.0001)
b.sps <- sin(angle.LC+0.0001)
##suppress by y1
LC.sps=y1*a.sps + y2*b.sps
# mydat = data.frame(cbind(LC.sps, y1, y2, s1.sq, s2.sq, tau1.sq, tau2.sq, rho.w, rho.b))
mydat = data.frame(LC.sps, y1, y2, s1=sqrt(s1.sq), s2=sqrt(s2.sq), tau1.sq, tau2.sq, rho.w, rho.b)
mydat = mydat[order(mydat$LC.sps),]
LC.cut <- (mydat$LC.sps[m.m] + mydat$LC.sps[m.m+1])/2
id=c(sample(1:m.m, n.m.o), (m.m+1):nrow(mydat))
mydat.sps=mydat[id,]
mydat.sps=data.frame(cbind(id,na.omit(mydat.sps)))
y.mvmeta <- list()
y.sps.mvmeta <- list()
if(verbose){
# y.mvmeta <- mvmeta(cbind(y1,y2), cbind(s1.sq,s2.sq), data=mydat, method = "mm")
# y.sps.mvmeta <- mvmeta(cbind(y1,y2), cbind(s1.sq,s2.sq), data=mydat.sps, method = "mm")
# plot.galaxy(mydat$y1,mydat$y2,mydat$s1.sq,mydat$s2.sq, c(1:m)%in% mydat.sps$id, # mydat$LC.sps>LC.cut,
# main=paste0('# studies = ', m.o, '+', m.m), xlab='y1', ylab='y2', scale=scale)
# text(y.mvmeta$coef[1], y.mvmeta$coef[2], '#', col=1, cex=2)
# text(y.sps.mvmeta$coef[1], y.sps.mvmeta$coef[2], '*', col=2, cex=2)
# tmp_dat = data.frame(y1=y1, s1=sqrt(s1.sq), y2=y2, s2=sqrt(s2.sq))
myplot = galaxy(data=mydat)
abline(LC.cut / sin(angle.LC+0.0001), -1/tan(angle.LC+0.0001))
}
return(list(mydat=mydat, mydat.sps=mydat.sps, y.sps.mvmeta=y.sps.mvmeta, y.mvmeta=y.mvmeta, LC.cut=LC.cut))
}
| /scratch/gouwar.j/cran-all/cranData/xmeta/R/galaxy.trimfill.R |
#' Methods for multiviarate random-effects meta-analysis
#'
#' @param data dataset
#' @param rhow within-study correlation
#' @param type either "continuous" or "binary", indicating the type of outcomes.
#' @param k integer indicating the number of outcomes
#' @param method either "nn.reml", "nn.cl", "nn.mom", "nn.rs", "bb.cl", "bn.cl", "tb.cl" or "tn.cl", indicating the estimation method.
#' @return res
#' @examples
#' data(prostate)^M
#' fit.nn=mmeta(data=prostate, type="continuous", k=2, method="nn.cl") ^M
#' summary(fit.nn)
#' rhow=runif(dim(prostate)[1], -0.2, 0.8)
#' fit.reml=mmeta(data=prostate, rhow=rhow, type="continuous", k=2, method="nn.reml")
#' print(fit.reml)
#' data(nat2)^M
#' fit.bb=mmeta(data=nat2, type="binary", k=2, method="bb.cl") ^M
#' summary(fit.bb)^M
#' data(ca125)^M
#' fit.tb=mmeta(data=ca125, type="binary", k=2, method="tb.cl") ^M
#' summary(fit.tb)^M
mmeta <-
function(data, rhow, type, k, method) {
nn.reml <-
function(y1, s1, y2, s2, rhow) {
S=cbind(s1^2, rhow*s1*s2, s2^2)
myreml= mvmeta(cbind(y1, y2), S, method="reml")
coef = coef(myreml)
vcov = vcov(myreml)
rhob <- cov2cor(myreml$Psi)[2,1]
myresults = list(coefficients = coef, vcov= vcov, rhob=rhob)
return(myresults)
}
nn.cl <-
function(y1, s1, y2, s2) {
m=length(y1)
estim.pseudo=rep(NA, 4)
my.pseudo1= mvmeta(y1,s1^2,method="reml")
my.pseudo2= mvmeta(y2,s2^2,method="reml")
estim.pseudo[c(1:2)]=c(coef(my.pseudo1), my.pseudo1$Psi)
estim.pseudo[c(3:4)]=c(coef(my.pseudo2), my.pseudo2$Psi)
estim.pseudo = matrix(estim.pseudo, nrow=1)
colnames(estim.pseudo)=c("beta1", "tau1.2", "beta2", "tau2.2")
Score1.beta = (y1-coef(my.pseudo1))/(s1^2+my.pseudo1$Psi)
Score2.beta = (y2-coef(my.pseudo2))/(s2^2+my.pseudo2$Psi)
Score1.tau2 = -1/(2*(s1^2+my.pseudo1$Psi)) + (y1-coef(my.pseudo1))^2/(s1^2+my.pseudo1$Psi)^2/2
Score2.tau2 = -1/(2*(s2^2+my.pseudo2$Psi)) + (y2-coef(my.pseudo2))^2/(s2^2+my.pseudo2$Psi)^2/2
Score1 = rbind(Score1.beta, Score1.tau2); Score2 = rbind(Score2.beta, Score2.tau2)
I11.hat = Score1%*%t(Score1)/m; I22.hat = Score2%*%t(Score2)/m
I12.hat = Score1%*%t(Score2)/m
myoff.diag = solve(I11.hat,tol=1e-100)%*%I12.hat%*%solve(I22.hat,tol=1e-100)/m
myupper = cbind(solve(m*I11.hat,tol=1e-100), (myoff.diag))
mylower = cbind(t(myoff.diag), solve(m*I22.hat,tol=1e-100))
myV=rbind(myupper,mylower)
colnames(myV)=c("beta1", "tau1.2", "beta2", "tau2.2")
rownames(myV)=c("beta1", "tau1.2", "beta2", "tau2.2")
myresults = list(coefficients = estim.pseudo, vcov= myV)
return(myresults)
}
nn.mom= function(y1, s1, y2, s2){
v1 = s1^2
v2 = s2^2
w1 = 1/(v1)
w2 = 1/(v2)
y1.weight = sum(w1*y1)/sum(w1)
y2.weight = sum(w2*y2)/sum(w2)
n1 = sum(1-1*(v1 > 10^4))
n2 = sum(1-1*(v2 > 10^4))
Q1 = sum(w1*(y1-y1.weight)^2)
Q2 = sum(w2*(y2-y2.weight)^2)
tau1.2.hat = max(0, (Q1-(n1-1))/(sum(w1)-sum(w1^2)/sum(w1)))
tau2.2.hat = max(0, (Q2-(n2-1))/(sum(w2)-sum(w2^2)/sum(w2)))
## variance estimate:
w1.star = 1/(v1 + tau1.2.hat)
w2.star = 1/(v2 + tau2.2.hat)
beta1.hat = sum(w1.star*y1)/sum(w1.star)
beta2.hat = sum(w2.star*y2)/sum(w2.star)
var.beta1.hat = 1/sum(w1.star)
var.beta2.hat = 1/sum(w2.star)
mycov.beta = sum((w1.star/sum(w1.star))*(w2.star/sum(w2.star))*(y1 - beta1.hat)*(y2 - beta2.hat))
beta.hat = cbind(beta1=beta1.hat,beta2=beta2.hat)
myV = matrix(c(var.beta1.hat,mycov.beta,mycov.beta,var.beta2.hat),nrow = 2, byrow = T)
colnames(myV)=c("beta1", "beta2")
rownames(myV)=c("beta1", "beta2")
myresults = list(coefficients = beta.hat, vcov= myV)
return(myresults)
}
log.Riley.Lik.reml.func = function(mygamma, y1, s1, y2, s2){
m = length(y1)
beta1 = mygamma[1]; beta2= mygamma[2]
log.psi1.2 = mygamma[3]; log.psi2.2 = mygamma[4]; omega = mygamma[5]
psi1.2 = exp(log.psi1.2); psi2.2 = exp(log.psi2.2)
rho = 2*plogis(omega)-1
s1.2 = s1^2
s2.2 = s2^2
Sigma = matrix(0, nrow=(2*m), ncol=(2*m))
for(i in 1:m){
cov.y1.y2 = rho*sqrt((psi1.2+s1.2[i])*(psi2.2+s2.2[i]))
Sigma.i = matrix(c(s1.2[i]+psi1.2, cov.y1.y2, cov.y1.y2, s2.2[i]+psi2.2), nrow=2)
Sigma[((i-1)*2+c(1:2)), ((i-1)*2+c(1:2))] = Sigma.i
}
y1.temp = rep(y1, each=2); y2.temp = rep(y2, each=2)
y1.temp2 = y1.temp%*%diag(rep(c(1,0), times=m))
y2.temp2 = y2.temp%*%diag(rep(c(0,1), times=m))
Y = as.vector(y1.temp2+y2.temp2)
x.design=cbind(rep(c(1,0), times=m), rep(c(0,1),times=m))
mybeta=x.design%*%c(beta1,beta2)
mylik = -0.5*((m-2)*log(2*pi)-log(det(t(x.design)%*%x.design)) +
log(det(Sigma))+log(det(t(x.design)%*%solve(Sigma,tol=1e-100)%*%x.design)) +
t(Y-mybeta)%*%solve(Sigma,tol=1e-100)%*%(Y-mybeta))
mylik = as.numeric(mylik)
return(mylik)
}
log.Riley.Lik.reml.i.func=function(mygamma, y1.i, s1.i, y2.i, s2.i){
result=log.Riley.Lik.reml.func(mygamma, y1.i, s1.i, y2.i, s2.i)
return(result)
}
robustV.ftn=function(mygamma, y1, s1, y2, s2){
m = length(y1)
SigmaB=array(NA, c(5,5,m))
SigmaA=array(NA, c(5,5,m))
for (i in 1:m){
y1.i=y1[i]
s1.i=s1[i]
y2.i=y2[i]
s2.i=s2[i]
myB=jacobian(log.Riley.Lik.reml.i.func, mygamma, y1.i=y1.i, s1.i=s1.i, y2.i=y2.i, s2.i=s2.i)
SigmaB[,,i]=t(myB)%*%myB
myA=hessian(log.Riley.Lik.reml.i.func, mygamma, y1.i=y1.i, s1.i=s1.i, y2.i=y2.i, s2.i=s2.i)
SigmaA[,,i]=-myA
}
E.A=apply(SigmaA, c(1:2), mean) # sensitivity matrix
E.B=apply(SigmaB, c(1:2), mean) # variability matrix
myV=solve(E.A)%*%E.B%*%solve(E.A)
return(myV)
}
nn.rs=function(y1, s1, y2, s2){
mygamma.init = c(0,0,0,0,0)
myresults = optim(mygamma.init, log.Riley.Lik.reml.func, y1=y1, s1=s1, y2=y2, s2=s2, hessian=TRUE,
control = list(fnscale=-1,maxit=1000))
beta1=myresults$par[1]
tau1.2=exp(myresults$par[3])
beta2=myresults$par[2]
tau2.2=exp(myresults$par[4])
rhos=2*plogis(myresults$par[5])-1
par=cbind(beta1, tau1.2, beta2, tau2.2, rhos)
myV=robustV.ftn(myresults$par, y1=y1, s1=s1, y2=y2, s2=s2)/length(y1)
colnames(myV)=c("beta1", "log.tau1.2", "beta2", "log.tau2.2", "omega")
rownames(myV)=c("beta1", "log.tau1.2", "beta2", "log.tau2.2", "omega")
return(list(coefficients=par, vcov=myV))
}
myLik.indep.log=function(mypar, mydat) {
a1.temp <- mypar[1]; b1.temp <- mypar[2]
a2.temp <- mypar[3]; b2.temp <- mypar[4]
a1 <- exp(a1.temp); b1 <- exp(b1.temp)
a2 <- exp(a2.temp); b2 <- exp(b2.temp)
temp1 <- (lgamma(a1+mydat$y1) + lgamma(b1+mydat$n1-mydat$y1)
+ lgamma(a2+mydat$y2) + lgamma(b2+mydat$n2-mydat$y2)
+ lgamma(a1+b1) + lgamma(a2+b2))
temp2 <- (lgamma(a1) + lgamma(b1) + lgamma(a2) + lgamma(b2)
+ lgamma(a1+b1+mydat$n1) + lgamma(a2+b2+mydat$n2))
myLogLik <- sum(temp1 - temp2)
return(myLogLik)
}
par.cal=function(mypar) {
a1 <- exp(mypar[1]); b1 <- exp(mypar[2])
a2 <- exp(mypar[3]); b2 <- exp(mypar[4])
eta <- mypar[5]
cc <- sqrt(a1*a2*b1*b2)/sqrt((a1+b1+1)*(a2+b2+1))
upper.bound <- cc/max(a1*b2, a2*b1)
lower.bound <- -cc/max(a1*a2, b1*b2)
expit.eta= exp(eta)/(1+exp(eta))
rho <- (upper.bound-lower.bound)*expit.eta + lower.bound
return(c(a1,b1,a2,b2,rho,eta))
}
bb.cl=function(y1,n1,y2,n2){
nstudy=length(y1)
initial.val.gen <- function(y, n) {
BBfit <- betabin(cbind(y, n-y)~1, ~1, data=data.frame(y=y,n=n))
expit.BB <- exp(as.numeric(BBfit@param[1]))/(1+exp(as.numeric(BBfit@param[1])))
a.ini <- expit.BB*(1/as.numeric(BBfit@param[2])-1)
b.ini <- (1/as.numeric(BBfit@param[2])-1)*(1-expit.BB)
return(list(a=a.ini, b=b.ini))
}
mle.CL <- function(y1=y1,n1=n1,y2=y2,n2=n2) {
init.val <- rep(0, 5)
fit1 <- initial.val.gen(y1, n1)
fit2 <- initial.val.gen(y2, n2)
init.val[1] <- log(fit1$a);
init.val[2] <- log(fit1$b)
init.val[3] <- log(fit2$a);
init.val[4] <- log(fit2$b)
MLE.inde.log <- optim(init.val[1:4], myLik.indep.log, method = "L-BFGS-B",
lower=rep(-20,4), upper=rep(20,4),
control = list(fnscale=-1,maxit=1000),
hessian = T, mydat=list(y1=y1,n1=n1,y2=y2,n2=n2))
mypar<- par.cal(MLE.inde.log$par)
rho<-0;
eta<-NA;
hessian.log<-MLE.inde.log$hessian
colnames(hessian.log)<-c("loga1","logb1","loga2","logb2")
rownames(hessian.log)<-c("loga1","logb1","loga2","logb2")
conv=MLE.inde.log$convergence
a1 <- mypar[1]; b1 <- mypar[2];
a2 <- mypar[3]; b2 <- mypar[4];
prior.MLE<-c(a1, b1, a2, b2, rho ,eta)
return(list(MLE=prior.MLE,hessian.log=hessian.log,conv=conv))
}
myLik.indep.vector=function(mypar, mydat) {
a1.temp <- mypar[1]; b1.temp <- mypar[2]
a2.temp <- mypar[3]; b2.temp <- mypar[4]
a1 <- exp(a1.temp); b1 <- exp(b1.temp)
a2 <- exp(a2.temp); b2 <- exp(b2.temp)
temp1 <- (lgamma(a1+mydat$y1) + lgamma(b1+mydat$n1-mydat$y1)
+ lgamma(a2+mydat$y2) + lgamma(b2+mydat$n2-mydat$y2)
+ lgamma(a1+b1) + lgamma(a2+b2))
temp2 <- (lgamma(a1) + lgamma(b1) + lgamma(a2) + lgamma(b2)
+ lgamma(a1+b1+mydat$n1) + lgamma(a2+b2+mydat$n2))
myLogLik <- (temp1 - temp2)
return(myLogLik)
}
sandwich.var.cal=function(mypar, myhessian.indep, mydat){
npar=length(mypar)
delta=1e-8
myD = matrix(NA, nrow=npar, ncol=nstudy)
for(i in 1:npar){
par.for=par.back=mypar
par.for[i]=par.for[i]+delta
par.back[i]=par.back[i]-delta
myD[i,] = (myLik.indep.vector(par.for, mydat)-myLik.indep.vector(par.back,mydat))/(2*delta)
}
score.squared = myD%*%t(myD)
inv.hessian = solve(-myhessian.indep)
results=inv.hessian%*% score.squared %*%inv.hessian
return(results)
}
out=mle.CL(y1=y1,n1=n1,y2=y2,n2=n2)
mle=out$MLE
hessian.log=out$hessian.log
a1=mle[1];b1=mle[2]
a2=mle[3];b2=mle[4]
mypar=log(c(a1,b1,a2,b2))
mydat=list(y1=y1,n1=n1,y2=y2,n2=n2)
covar.sandwich=sandwich.var.cal(mypar, hessian.log, mydat)
myD <- matrix(c(-1, 1, 1, -1), nrow=1)
myVar.log <- as.numeric(myD %*% covar.sandwich %*% t(myD))
logOR <- log((a2/b2)/(a1/b1))
OR_CI=c(exp(logOR-1.96*sqrt(myVar.log)), exp(logOR+1.96*sqrt(myVar.log)))
#return(list(logOR=logOR, OR_CI=OR_CI, se=sqrt(myVar.log),hessian.log=hessian.log,conv=out$conv,mle=mle))
return(list(logOR=logOR, OR_CI=OR_CI, se=sqrt(myVar.log),hessian.log=hessian.log,conv=out$conv,mle=mle))
}
logit = function(p) log(p/(1-p))
expit = function(b) exp(b)/(1+exp(b))
dlogitnorm = function(p, mu, tau2){
(2*pi*tau2)^(-1/2)*exp(-(qlogis(p)-mu)^2/(2*tau2))/(p*(1-p))
}
integrand1<-function(n,y, mypar2, p.grid){
dbinom(y, size=n, prob=p.grid)*dlogitnorm(p.grid, mypar2[1], mypar2[2])
}
integrand2<-function(n,y,mypar2, p.grid){
dbinom(y, size=n, prob=p.grid)*dlogitnorm(p.grid, mypar2[1], mypar2[2])*2*(qlogis(p.grid)-mypar2[1])/(2*mypar2[2])
}
integrand3<-function(n,y,mypar2, p.grid){
dbinom(y, size=n, prob=p.grid)*dlogitnorm(p.grid, mypar2[1], mypar2[2])*(-1/(2*mypar2[2])+(qlogis(p.grid)-mypar2[1])^2/(2*mypar2[2]^2))
}
mystandize = function(MM){
diag(1/sqrt(diag(MM)))%*%MM%*%diag((1/sqrt(diag(MM))))
}
bn.cl=function(y1, n1, y2, n2){
id=c(1:length(y1))
mydat1 = data.frame(id,n1,y1,n2,y2)
names(mydat1) = c("id","Nd","SeY","Nn","SpY")
m = nrow(mydat1)
estim = estim.orig = mbse.orig = matrix(NA, nrow=4, ncol=1)
mySandwich = matrix(NA,nrow=4,ncol=4)
fit.SeY = glmmML(cbind(SeY, Nd-SeY)~1, data = mydat1, cluster = id, method= "ghq", n.points=8, control=list(epsilon=1e-08 , maxit=50000,trace=FALSE))
fit.SpY = glmmML(cbind(SpY, Nn-SpY)~1, data = mydat1, cluster = id, method= "ghq", n.points=8, control=list(epsilon=1e-08 , maxit=50000,trace=FALSE))
estim[c(1: 2), 1] = c(as.numeric(fit.SeY$coefficients), (fit.SeY$sigma)^2)
estim[c(3: 4), 1] = c(as.numeric(fit.SpY$coefficients), (fit.SpY$sigma)^2)
estim.orig[c(1: 2), 1] = c(plogis(estim[1, 1]), estim[2, 1])
estim.orig[c(3: 4), 1] = c(plogis(estim[3, 1]), estim[4, 1])
rownames(estim)=c("SeY", "SeY.S.2", "SpY", "SpY.S.2")
rownames(estim.orig)=c("SeY", "SeY.S.2", "SpY", "SpY.S.2")
I11.hat = solve(m*fit.SeY$variance)
I22.hat = solve(m*fit.SpY$variance)
int1 = int2 = int3 = rep(NA, length=m)
est1 = estim[c(1: 2), 1] ##plug in the point estimate based on sensitivity
for(i in 1: m){
int1[i] = integrate(integrand1, lower=0, upper=1, n=mydat1$Nd[i], mypar2=est1, y=mydat1$SeY[i])$value
int2[i] = integrate(integrand2, lower=0, upper=1, n=mydat1$Nd[i], mypar2=est1, y=mydat1$SeY[i])$value
int3[i] = integrate(integrand3, lower=0, upper=1, n=mydat1$Nd[i], mypar2=est1, y=mydat1$SeY[i])$value
}
deriveSeY.mu = int2/int1
deriveSeY.tau2 = int3/int1
B.SeY = cbind(deriveSeY.mu, deriveSeY.tau2)
int1 = int2 = int3 = rep(NA, length=m)
est2 = estim[c(3: 4), 1] ##plug in the point estimate based on specificity
for(i in 1: m){
int1[i] = integrate(integrand1, lower=0, upper=1, n=mydat1$Nn[i], mypar2=est2, y=mydat1$SpY[i])$value
int2[i] = integrate(integrand2, lower=0, upper=1, n=mydat1$Nn[i], mypar2=est2, y=mydat1$SpY[i])$value
int3[i] = integrate(integrand3, lower=0, upper=1, n=mydat1$Nn[i], mypar2=est2, y=mydat1$SpY[i])$value
}
deriveSpY.mu = int2/int1
deriveSpY.tau2 = int3/int1
B.SpY = cbind(deriveSpY.mu, deriveSpY.tau2)
I12.hat = t(B.SeY)%*%B.SpY/m
myoff.diag = solve(I11.hat)%*%I12.hat%*%solve(I22.hat)/m
myupper = cbind(fit.SeY$variance, myoff.diag)
mylower = cbind(t(myoff.diag), fit.SpY$variance)
myV = rbind(myupper, mylower)
colnames(myV)=c("SeY", "SeY.S.2", "SpY", "SpY.S.2")
rownames(myV)=c("SeY", "SeY.S.2", "SpY", "SpY.S.2")
return(list(coefficients=estim, par.orig=estim.orig, vcov=myV))
}
score.Li.func = function(PiY,SeY,SpY,n,n1,n0,PiY.est,SeY.est,SpY.est){
beta0 = PiY.est[1]; beta1 = SeY.est[1]; beta2 = SpY.est[1]
mu0 = expit(beta0); mu1 = expit(beta1); mu2 = expit(beta2)
phi0 = PiY.est[2]; phi1 = SeY.est[2]; phi2 = SpY.est[2]
theta0 = phi0/(1-phi0); theta1 = phi1/(1-phi1); theta2 = phi2/(1-phi2)
k01 = c(0:(PiY-1)); k02 = c(0:(n-PiY-1)); k03 = c(0:(n-1))
k11 = c(0:(SeY-1)); k12 = c(0:(n1-SeY-1)); k13 = c(0:(n1-1))
k21 = c(0:(SpY-1)); k22 = c(0:(n0-SpY-1)); k23 = c(0:(n0-1))
# notice for outbound
if(PiY == 0) k01 = NULL; if(PiY == n) k02 = NULL
if(SeY == 0) k11 = NULL; if(SeY == n1) k12 = NULL
if(SpY == 0) k21 = NULL; if(SpY == n0) k22 = NULL
Dbeta0 = Dbeta1 = Dbeta2 = Dphi0 = Dphi1 = Dphi2 = 0
Dphi0 = (sum(k01/(mu0+k01*theta0))+sum(k02/(1-mu0+k02*theta0))- sum(k03/(1+k03*theta0)))/((1-phi0)^2)
Dphi1 = (sum(k11/(mu1+k11*theta1))+sum(k12/(1-mu1+k12*theta1))-sum(k13/(1+k13*theta1)))/((1-phi1)^2)
Dphi2 = (sum(k21/(mu2+k21*theta2))+sum(k22/(1-mu2+k22*theta2))-sum(k23/(1+k23*theta2)))/((1-phi2)^2)
Dbeta0 = sum(mu0*(1-mu0)/(mu0+k01*theta0))-sum(mu0*(1-mu0)/(1-mu0+k02*theta0))
Dbeta1 = sum(mu1*(1-mu1)/(mu1+k11*theta1))-sum(mu1*(1-mu1)/(1-mu1+k12*theta1))
Dbeta2 = sum(mu2*(1-mu2)/(mu2+k21*theta2))-sum(mu2*(1-mu2)/(1-mu2+k22*theta2))
score.PiY = as.vector(c(Dbeta0,Dphi0))
score.SeY = as.vector(c(Dbeta1,Dphi1))
score.SpY = as.vector(c(Dbeta2,Dphi2))
return(list(score.PiY=score.PiY, score.SeY=score.SeY, score.SpY=score.SpY))
}
score.Li.all.func= function(SeY,SpY,n1,n0,SeY.est,SpY.est){
beta1 = SeY.est[1] ; beta2 = SpY.est[1]
mu1 = expit(beta1) ; mu2 = expit(beta2)
phi1 = SeY.est[2] ; phi2 =SpY.est[2]
theta1 = phi1/(1-phi1) ; theta2 = phi2/(1-phi2)
k11 = c(0:(SeY-1)); k12 = c(0:(n1-SeY-1)); k13 = c(0:(n1-1))
k21 = c(0:(SpY-1)); k22 = c(0:(n0-SpY-1)); k23 = c(0:(n0-1))
# notice for outbound
if(SeY == 0) k11 = NULL ; if(SeY == n1) k12 = NULL
if(SpY == 0) k21 = NULL ; if(SpY == n0) k22 = NULL
Dbeta1 = Dbeta2 = Dphi1 = Dphi2 = 0
Dphi1 = (sum(k11/(mu1+k11*theta1))+sum(k12/(1-mu1+k12*theta1))- sum(k13/(1+k13*theta1)))/((1-phi1)^2)
Dphi2 = (sum(k21/(mu2+k21*theta2))+sum(k22/(1-mu2+k22*theta2))- sum(k23/(1+k23*theta2)))/((1-phi2)^2)
Dbeta1 = sum(mu1*(1-mu1)/(mu1+k11*theta1))- sum(mu1*(1-mu1)/(1-mu1+k12*theta1))
Dbeta2 = sum(mu2*(1-mu2)/(mu2+k21*theta2))-sum(mu2*(1-mu2)/(1-mu2+k22*theta2))
score.SeY = as.vector(c(Dbeta1,Dphi1))
score.SpY = as.vector(c(Dbeta2,Dphi2))
return(list(score.SeY=score.SeY, score.SpY=score.SpY))
}
Fisher.inf = function(PiY.del,SeY.del,SpY.del,n.del,n1.del, n0.del, SeY,SpY,n1,n0,PiY.est,SeY.est, SpY.est){
m = length(SeY) # the length of all study, including case control study & cohort study
m2 = length(PiY.del) # the length of the cohort study only
I00.array = I01.array = I02.array = array(NA,c(2,2,m2))
I11.array = I12.array = I22.array = array(NA,c(2,2,m))
for(i in 1:m2){
temp = score.Li.func (PiY.del[i], SeY.del[i],SpY.del[i],n.del[i], n1.del[i],n0.del[i],PiY.est, SeY.est, SpY.est)
score.PiY = temp$score.PiY
score.SeY = temp$score.SeY
score.SpY = temp$score.SpY
I00.array[ , , i] = score.PiY%*%t(score.PiY)
I01.array[ , , i] = score.PiY%*%t(score.SeY)
I02.array[ , , i] = score.PiY%*%t(score.SpY)
}
for(i in 1:m){
temp = score.Li.all.func (SeY[i],SpY[i],n1[i],n0[i],SeY.est,SpY.est)
score.SeY = temp$score.SeY
score.SpY = temp$score.SpY
I11.array[ , , i] = score.SeY%*%t(score.SeY)
I12.array[ , , i] = score.SeY%*%t(score.SpY)
I22.array[ , , i] = score.SpY%*%t(score.SpY)
}
I00 = apply(I00.array, c(1,2), mean)
I01 = apply(I01.array, c(1,2), mean)
I02 = apply(I02.array, c(1,2), mean)
I11 = apply(I11.array, c(1,2), mean)
I12 = apply(I12.array, c(1,2), mean)
I22 = apply(I22.array, c(1,2), mean)
return(list(I00=I00, I01=I01, I02=I02, I11=I11, I12=I12, I22=I22))
}
tb.cl=function(n, PiY, SeY, n1, SpY, n2){
m = length(SeY) # the length of all study, including case control study & cohort study
m2 = sum(is.na(PiY)!=1) # the length of the cohort study only
estim = estim.orig = mbse.orig = matrix(NA,nrow=6,ncol=1)
mySandwich = matrix(NA,nrow=6,ncol=6)
mydat1 = data.frame(n,PiY,n1,SeY,n2, SpY)
names(mydat1) = c("n","PiY", "n1","SeY","n0","SpY")
mydat2 = mydat1[is.na(mydat1$PiY)==FALSE, ] ## dataset used for estimating prevalence
fit.PiY = betabin(cbind(PiY, n-PiY)~1, ~1, hessian=T, data=mydat2, link="logit")
fit.SeY = betabin(cbind(SeY, n1-SeY)~1, ~1, hessian=T, data=mydat1, link="logit")
fit.SpY = betabin(cbind(SpY, n0-SpY)~1, ~1, hessian=T, data=mydat1, link="logit")
estim[c(1:2), 1] = c(as.numeric(fit.PiY@param))
estim[c(3:4), 1] = c(as.numeric(fit.SeY@param))
estim[c(5:6), 1] = c(as.numeric(fit.SpY@param))
estim.orig[c(1: 2), 1] = c(expit(estim[1, 1]), estim[2, 1])
estim.orig[c(3: 4), 1] = c(expit(estim[3, 1]), estim[4, 1])
estim.orig[c(5: 6), 1] = c(expit(estim[5, 1]), estim[6, 1])
rownames(estim)=c("PiY1", "PiY2", "SeY1", "SeY2", "SpY1", "SpY2")
rownames(estim.orig)=c("PiY1", "PiY2", "SeY1", "SeY2", "SpY1", "SpY2")
fit.PiY.var = matrix(c(fit.PiY@varparam[1,1], fit.PiY@varparam[1,2], fit.PiY@varparam[2,1],fit.PiY@varparam[2,2]), nrow=2,byrow=TRUE)
fit.SeY.var = matrix(c(fit.SeY@varparam[1,1], fit.SeY@varparam[1,2], fit.SeY@varparam[2,1],fit.SeY@varparam[2,2]), nrow=2,byrow=TRUE)
fit.SpY.var = matrix(c(fit.SpY@varparam[1,1], fit.SpY@varparam[1,2], fit.SpY@varparam[2,1],fit.SpY@varparam[2,2]), nrow=2,byrow=TRUE)
I00.hat = solve(m2*fit.PiY.var)
I11.hat = solve(m*fit.SeY.var)
I22.hat = solve(m*fit.SpY.var)
estim.PiY = estim[c(1:2), 1]
estim.SeY = estim[c(3:4), 1]
estim.SpY = estim[c(5:6), 1]
temp = Fisher.inf(mydat2$PiY,mydat2$SeY,mydat2$SpY,mydat2$n,mydat2$n1,mydat2$n0, mydat1$SeY,mydat1$SpY,mydat1$n1,mydat1$n0,estim.PiY, estim.SeY, estim.SpY)
I01.hat = temp$I01 ; I02.hat = temp$I02 ; I12.hat = temp$I12
myoff.diag01 = solve(I00.hat)%*%I01.hat%*%solve(I11.hat)/m
myoff.diag02 = solve(I00.hat)%*%I02.hat%*%solve(I22.hat)/m
myoff.diag12 = solve(I11.hat)%*%I12.hat%*%solve(I22.hat)/m
myupper = cbind((fit.PiY.var), sqrt(m/m2)*(myoff.diag01), sqrt(m/m2)*(myoff.diag02))
mymiddle = cbind(sqrt(m/m2)*t(myoff.diag01), (fit.SeY.var), (myoff.diag12))
mylower = cbind(sqrt(m/m2)*t(myoff.diag02), t(myoff.diag12), (fit.SpY.var))
myV = rbind(myupper, mymiddle, mylower)
colnames(myV)=c("PiY1", "PiY2", "SeY1", "SeY2", "SpY1", "SpY2")
rownames(myV)=c("PiY1", "PiY2", "SeY1", "SeY2", "SpY1", "SpY2")
mu0.mbse = (estim.orig[1, 1]*(1-estim.orig[1, 1]))*sqrt(diag(myV)[1])
mu1.mbse = (estim.orig[3, 1]*(1-estim.orig[3, 1]))*sqrt(diag(myV)[3])
mu2.mbse = (estim.orig[5, 1]*(1-estim.orig[5, 1]))*sqrt(diag(myV)[5])
s1.2.mbse = sqrt(diag(myV)[2])
s2.2.mbse = sqrt(diag(myV)[4])
s3.2.mbse = sqrt(diag(myV)[6])
mbse.orig = c(mu0.mbse, s1.2.mbse, mu1.mbse, s2.2.mbse, mu2.mbse, s3.2.mbse)
return(list(coefficients=estim, estim.orig=estim.orig, vcov=myV))
}
tn.cl=function(n, PiY2, SeY1, SeY2, SpY1, SpY2, Nd, Nn){
estim = estim.orig = mbse.orig = matrix(NA, nrow=6, ncol=1)
m1=length(SeY1)
m2=length(SeY2)
m=m1+m2
PiY = c(rep(NA, length=m1),PiY2)
SeY = c(SeY1, SeY2)
SpY = c(SpY1, SpY2)
id=c(1:m)
mydat = data.frame(id, rep(n, length=m), PiY, Nd ,SeY,Nn, SpY)
names(mydat) = c("id", "Nt","PiY", "Nd","SeY","Nn","SpY") ## codebook for mydat: study id, number of total subjects, number of disease ppl among total subjects, number of diease ppl, number of being postive test among disease ppl, number of disease-free ppl, number of being negative test among disease-free ppl
mydat2=na.omit(mydat)
fit.PiY = glmmML(cbind(PiY, Nt-PiY)~1, data = mydat2, cluster = id, method= "ghq", n.points=8, control=list(epsilon=1e-08 , maxit=50000,trace=FALSE))
fit.SeY = glmmML(cbind(SeY, Nd-SeY)~1, data = mydat, cluster = id, method= "ghq", n.points=8, control=list(epsilon=1e-08 , maxit=50000,trace=FALSE))
fit.SpY = glmmML(cbind(SpY, Nn-SpY)~1, data = mydat, cluster = id, method= "ghq", n.points=8, control=list(epsilon=1e-08 , maxit=50000,trace=FALSE))
estim[c(1: 2),1] = c(as.numeric(fit.PiY$coefficients), (fit.PiY$sigma)^2)
estim[c(3: 4),1] = c(as.numeric(fit.SeY$coefficients), (fit.SeY$sigma)^2)
estim[c(5: 6),1] = c(as.numeric(fit.SpY$coefficients), (fit.SpY$sigma)^2)
estim.orig[c(1: 2),1] = c(plogis(estim[1,1]), estim[2,1])
estim.orig[c(3: 4),1] = c(plogis(estim[3,1]), estim[4,1])
estim.orig[c(5: 6),1] = c(plogis(estim[5,1]), estim[6,1])
rownames(estim)=c("PiY1", "PiY2", "SeY1", "SeY2", "SpY1", "SpY2")
rownames(estim.orig)=c("PiY1", "PiY2", "SeY1", "SeY2", "SpY1", "SpY2")
I00.hat = solve(m2*fit.PiY$variance)
I11.hat = solve(m*fit.SeY$variance)
I22.hat = solve(m*fit.SpY$variance)
int1 = int2 = int3 = rep(NA, length=m2)
est0 = estim[c(1: 2),1] ##plug in the point estimate based on disease prevalence
for(i in 1: m2){
int1[i] = integrate(integrand1, lower=0, upper=1, n=mydat2$Nt[i], mypar2=est0, y=mydat2$PiY[i])$value
int2[i] = integrate(integrand2, lower=0, upper=1, n=mydat2$Nt[i], mypar2=est0, y=mydat2$PiY[i])$value
int3[i] = integrate(integrand3, lower=0, upper=1, n=mydat2$Nt[i], mypar2=est0, y=mydat2$PiY[i])$value
}
##
derivePiY.mu = int2/int1
derivePiY.tau2 = int3/int1
B.PiY = cbind(derivePiY.mu, derivePiY.tau2)
int1 = int2 = int3 = rep(NA, length=m)
est1 = estim[c(3: 4),1] ##plug in the point estimate based on sensitivity
for(i in 1: m){
int1[i] = integrate(integrand1, lower=0, upper=1, n=mydat$Nd[i], mypar2=est1, y=mydat$SeY[i])$value
int2[i] = integrate(integrand2, lower=0, upper=1, n=mydat$Nd[i], mypar2=est1, y=mydat$SeY[i])$value
int3[i] = integrate(integrand3, lower=0, upper=1, n=mydat$Nd[i], mypar2=est1, y=mydat$SeY[i])$value
}
deriveSeY.mu = int2/int1
deriveSeY.tau2 = int3/int1
B.SeY = cbind(deriveSeY.mu, deriveSeY.tau2)
B.SeY.del = B.SeY[-c(1:m1), ] ## delete the first m1 studies
int1 = int2 = int3 = rep(NA, length=m)
est2 = estim[c(5: 6),1] ##plug in the point estimate based on specificity
for(i in 1: m){
int1[i] = integrate(integrand1, lower=0, upper=1, n=mydat$Nn[i], mypar2=est2, y=mydat$SpY[i])$value
int2[i] = integrate(integrand2, lower=0, upper=1, n=mydat$Nn[i], mypar2=est2, y=mydat$SpY[i])$value
int3[i] = integrate(integrand3, lower=0, upper=1, n=mydat$Nn[i], mypar2=est2, y=mydat$SpY[i])$value
}
deriveSpY.mu = int2/int1
deriveSpY.tau2 = int3/int1
B.SpY = cbind(deriveSpY.mu, deriveSpY.tau2)
B.SpY.del = B.SpY[-c(1:m1), ] ## delete the first m1 studies
I01.hat = t(B.PiY)%*%B.SeY.del/m2
I02.hat = t(B.PiY)%*%B.SpY.del/m2
I12.hat = t(B.SeY)%*%B.SpY/m
myoff.diag01 = solve(I00.hat)%*%I01.hat%*%solve(I11.hat)/m
myoff.diag02 = solve(I00.hat)%*%I02.hat%*%solve(I22.hat)/m
myoff.diag12 = solve(I11.hat)%*%I12.hat%*%solve(I22.hat)/m
myupper = cbind(fit.PiY$variance, sqrt(m/m2)*(myoff.diag01), sqrt(m/m2)*(myoff.diag02))
mymiddle = cbind(sqrt(m/m2)*t(myoff.diag01), fit.SeY$variance, (myoff.diag12))
mylower = cbind(sqrt(m/m2)*t(myoff.diag02), t(myoff.diag12), fit.SpY$variance)
myV = rbind(myupper, mymiddle, mylower)
colnames(myV)=c("PiY1", "PiY2", "SeY1", "SeY2", "SpY1", "SpY2")
rownames(myV)=c("PiY1", "PiY2", "SeY1", "SeY2", "SpY1", "SpY2")
return(list(coefficients=estim, estim.orig=estim.orig, vcov=myV))
}
if (missing(data)){data=NULL}
if (is.null(data)){
stop("The dataset must be specified.")
}
if (missing(k)){k=NULL}
if (is.null(k)){
stop("The number of outcomes must be specified.")
}
if (missing(type)){type=NULL}
if (is.null(type)){
stop('The type of outcome must be specified. Please input "continuous" or "binary". ')
}
if (missing(method)){method=NULL}
if (is.null(method)){
stop("A method must be specified. ")
}
if (missing(rhow)){rhow=NULL}
if ((is.null(rhow))&(method=="nn.reml")){
stop('The within-study correlations are required for the input method "nn.reml".')
}
if (k>2){
stop('The method for MMA with more than 2 outcomes are currently under development. ')
}
if (type=="continuous"){
y1=data$y1
s1=data$s1
y2=data$y2
s2=data$s2
if(method=="nn.cl"){
fit=nn.cl(y1, s1, y2, s2)}
if(method=="nn.reml"){
fit=nn.reml(y1, s1, y2, s2, rhow)}
if(method=="nn.mom"){
fit=nn.mom(y1, s1, y2, s2)}
if(method=="nn.rs"){
fit=nn.rs(y1, s1, y2, s2)}
if ((method%in%c("nn.reml", "nn.cl", "nn.mom", "nn.rs"))!=1){
stop('The input method is not available for continuous outcomes. Please choose from
"nn.reml", "nn.cl", "nn.mom", or "nn.rs". ')
}
}
if(type=="binary"){
if (method=="bb.cl"){
y1=data$y1
n1=data$n1
y2=data$y2
n2=data$n2
fit=bb.cl(y1,n1,y2,n2)
}
if (method=="bn.cl"){
y1=data$y1
n1=data$n1
y2=data$y2
n2=data$n2
fit=bn.cl(y1,n1,y2,n2)
}
if (method=="tb.cl"){
n=data$n
PiY=data$PiY
SeY=data$SeY
n1=data$n1
SpY=data$SpY
n2=data$n2
fit=tb.cl(n, PiY, SeY, n1, SpY, n2)
}
if (method=="tn.cl"){
n=data$n
PiY2=data$PiY2
SeY1=data$SeY1
SeY2=data$SeY2
SpY1=data$SpY1
SpY2=data$SpY2
Nd=data$Nd
Nn=data$Nn
fit=tn.cl(n, PiY2, SeY1, SeY2, SpY1, SpY2, Nd, Nn)
}
if ((method%in%c("bb.cl", "bn.cl", "tb.cl", "tn.cl"))!=1){
stop('The input method is not available for binary outcomes. Please choose from
"bb.cl", "bn.cl", "tb.cl", or "tn.cl". ')
}
}
res=list(type=type, k=k, method=method, coefficients=fit$coefficients, vcov=fit$vcov)
if(method=="bb.cl"){
res=list(type=type, k=k, method=method, logOR=fit$logOR, OR_CI=fit$OR_CI, se=fit$se,hessian.log=fit$hessian.log,conv=fit$conv,mle=fit$mle)
}
class(res) = c("mmeta")
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/xmeta/R/mmeta.R |
msset <-
function(data, nm.y1, nm.s1, nm.y2, nm.s2, method, type, k) {
nn.cl=function(y1, s1, y2, s2){
n=length(y1)
s1.sq=s1^2
s2.sq=s2^2
y1[is.na(y1)==1]=0
y2[is.na(y2)==1]=0
s1.sq[is.na(s1.sq)==1]=10^10
s2.sq[is.na(s2.sq)==1]=10^10
dat.obs=data.frame(cbind(y1, y2, s1.sq, s2.sq))
colnames(dat.obs)=c("y1", "y2", "s1.sq", "s2.sq")
fit1 = mvmeta(y1,s1.sq, data=dat.obs,method="reml")
fit2 = mvmeta(y2,s2.sq, data=dat.obs,method="reml")
tau1.sq.est=fit1$Psi[1,1]
tau2.sq.est=fit2$Psi[1,1]
A=A.star=array(NA, c(n, 2,2))
SND=P=SND.star=P.star=array(NA, c(n, 2))
s1.sq=dat.obs$s1.sq
s2.sq=dat.obs$s2.sq
y1=dat.obs$y1
y2=dat.obs$y2
y=cbind(y1, y2)
for (i in 1:n){
A[i,,]=matrix(c((s1.sq[i]+tau1.sq.est)^(-0.5), 0, 0, (s2.sq[i]+tau2.sq.est)^(-0.5)), ncol=2)
SND[i,]=y[i,]%*%A[i,,]
P[i,]=c(1,1)%*%A[i,,]
}
SND1=SND[,1]
SND2=SND[,2]
P1=P[,1]
P2=P[,2]
est1.ftn=function(SND1, SND2, P1, P2){
b1=(sum(SND1)-sum(SND1*P1))/(sum(P1)-sum(P1^2))
a1=(sum(SND1)-b1*sum(P1))/n
b2=(sum(SND2)-sum(SND2*P2))/(sum(P2)-sum(P2^2))
a2=(sum(SND2)-b1*sum(P2))/n
est=c(a1,b1, a2, b2)
return(est)
}
est2.ftn=function(SND1, SND2, P1, P2){
b1=sum(SND1*P1)/sum(P1^2)
b2=sum(SND2*P2)/sum(P2^2)
est=c(b1,b2)
return(est)
}
est1=est1.ftn(SND1, SND2, P1, P2)
est2=est2.ftn(SND1, SND2, P1, P2)
###### CL ##############################
loglik.CL=function(t,SND1, SND2, P1, P2){
n=length(SND1)
mu1=t[1]+t[2]*P1
mu2=t[3]+t[4]*P2
loglik=-0.5*sum((SND1-mu1)^2)-0.5*sum((SND2-mu2)^2)
return(loglik)
}
loglik.CL0=function(tt,SND1, SND2, P1, P2){
t=c(0, tt[1], 0, tt[2])
result=loglik.CL(t, SND1, SND2, P1, P2)
return(result)
}
##### score tests ###########################
sc=sc0=array(NA, c(4,n))
sc0.sq=sc.sq=hc0=hc=array(NA, c(4,4,n))
for (j in 1:n){
sc[,j]=as.matrix(jacobian(loglik.CL, x=est1, SND1=SND1[j], P1=P1[j], SND2=SND2[j], P2=P2[j]), ncol=4)
sc0[,j]=as.matrix(jacobian(loglik.CL, x=c(0, est2[1], 0, est2[2]), SND1=SND1[j], P1=P1[j], SND2=SND2[j], P2=P2[j]), ncol=4)
}
JC0=cov(t(sc0))
esc=apply(sc0, 1, mean)
sct=n*t(esc)%*%solve(JC0)%*%esc
######
u.sc.gg=n*esc[c(1,3)]
I0.sc=-as.matrix(hessian(loglik.CL, x=c(0, est2[1], 0, est2[2]), SND1=SND1, P1=P1, SND2=SND2, P2=P2), ncol=4)
I1.sc=cov(t(sc0))
sigma.sc=solve(I0.sc)%*%I1.sc%*%solve(I0.sc)
sigma.sc.gg=sigma.sc[c(1,3), c(1,3)]
sigma.sc.inv=solve(sigma.sc)
sigma.sc.inv.gg=sigma.sc.inv[c(1,3), c(1,3)]
I0.sc.inv=solve(I0.sc)
I0.sc.inv.gg=I0.sc.inv[c(1,3), c(1,3)]
sc.ec=1/n*t(u.sc.gg)%*%I0.sc.inv.gg%*%solve(sigma.sc.gg)%*%I0.sc.inv.gg%*%u.sc.gg
sc.mb=1/n*t(u.sc.gg)%*%I0.sc.inv.gg%*%u.sc.gg
mylambda.sc=eigen(solve(I0.sc.inv.gg)%*%sigma.sc.gg)$values
bar.lambda.sc=mean(mylambda.sc)
sc.mb.a=sc.mb/bar.lambda.sc
pv=pchisq(q=sc.mb.a, df=2, lower.tail=FALSE)
return(list(msset.TS=sc.mb.a, pv=pv))
}
if (missing(data)){data=NULL}
if (is.null(data)){
stop("The dataset must be specified.")
}
if (missing(type)){type=NULL}
if (is.null(type)){
stop('The type of outcome must be specified. Please input "continuous" or "binary". ')
}
if (missing(k)){k=NULL}
if (is.null(k)){
stop("The number of outcomes must be specified.")
}
if (k>2){
stop("The method for MMA with more than 2 outcomes is currently under development. ")
}
if (missing(method)){method=NULL}
if (is.null(method)){
stop("A method must be specified. ")
}
if (type=="binary"){
stop("The method for meta-analysis with binary outcome is currently
under development. ")
}
if (type=="continuous"){
y1=data[,nm.y1]
s1=data[,nm.s1]
y2=data[,nm.y2]
s2=data[,nm.s2]
if(method=="nn.cl"){
fit=nn.cl(y1, s1, y2, s2)
}
if ((method%in%c("nn.cl"))!=1){
stop("The input method is not available for continuous data")
}
}
res=list(type=type, k=k, method=method, msset.TS=fit$msset.TS, msset.pv=fit$pv)
class(res) = c("msset")
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/xmeta/R/msset.R |
summary.mmeta <- function(object,...) {
summary_mmeta <- function(object) {
type <- object$type
k <- object$k
method <- object$method
cat("Outcome:",type,fill=TRUE)
if (method=="nn.reml") {
cat("Method: restricted maximum likelihood method",fill=TRUE)
cat("Number of outcomes:",k,"\n")
}
if (method=="nn.cl") {
cat("Method: composite likelihood method",fill=TRUE)
cat("Number of outcomes:",k,"\n")
}
if (method=="nn.mom") {
cat("Method: method of moment",fill=TRUE)
cat("Number of outcomes:",k,"\n")
}
if (method=="nn.mom") {
cat("Method: improved method for Riley model",fill=TRUE)
cat("Number of outcomes:",k,"\n")
}
if (method=="bn.cl") {
cat("Method: marginal bivariate normal model",fill=TRUE)
cat("Number of outcomes:",k,"\n")
}
if (method=="bb.cl") {
cat("Method: marginal beta-binomial model",fill=TRUE)
cat("Number of outcomes:",k,"\n")
}
if (method=="tb.cl") {
cat("Method: hybrid model for disease prevalence along with sensitivity and specificity for diagnostic test accuracy",fill=TRUE)
cat("Number of outcomes:",k,"\n")
}
if (method=="tn.cl") {
cat("Method: trivariate model for multivariate meta-analysis of diagnostic test accuracy",fill=TRUE)
cat("Number of outcomes:",k,"\n")
}
## print the object
if(method=="nn.reml"){
cat("Fixed-effects coefficients:",fill=TRUE)
beta.coefficients=data.frame(cbind(object$coefficients[1],object$coefficients[3]))
colnames(beta.coefficients)=c("beta1", "beta2")
rownames(beta.coefficients)=c("")
print(beta.coefficients)
cat("Between-study variances:",fill=TRUE)
tau2.coefficients=data.frame(cbind(object$coefficients[2],object$coefficients[4]))
colnames(tau2.coefficients)=c("tau1.2", "tau2.2")
rownames(tau2.coefficients)=c("")
print(tau2.coefficients)
cat("Between-study correlation:",fill=TRUE)
rhob=data.frame(object$coefficients[5])
colnames(rhob)=c("rhob")
rownames(rhob)=c("")
print(rhob)
cat("Covariance matrix:",fill=TRUE)
print(object$vcov)
cat("\n")
}
if(method=="nn.cl"){
cat("Fixed-effects coefficients:",fill=TRUE)
beta.coefficients=data.frame(cbind(object$coefficients[1],object$coefficients[3]))
colnames(beta.coefficients)=c("beta1", "beta2")
rownames(beta.coefficients)=c("")
print(beta.coefficients)
cat("Between-study variances:",fill=TRUE)
tau2.coefficients=data.frame(cbind(object$coefficients[2],object$coefficients[4]))
colnames(tau2.coefficients)=c("tau1.2", "tau2.2")
rownames(tau2.coefficients)=c("")
print(tau2.coefficients)
cat("Covariance matrix:",fill=TRUE)
print(object$vcov)
cat("\n")
}
if(method=="nn.mom"){
cat("Fixed-effects coefficients:",fill=TRUE)
beta.coefficients=data.frame(cbind(object$coefficients[1],object$coefficients[2]))
colnames(beta.coefficients)=c("beta1", "beta2")
rownames(beta.coefficients)=c("")
print(beta.coefficients)
cat("Covariance matrix:",fill=TRUE)
print(object$vcov)
cat("\n")
}
if(method=="nn.rs"){
cat("Fixed-effects coefficients:",fill=TRUE)
beta.coefficients=data.frame(cbind(object$coefficients[1],object$coefficients[3]))
colnames(beta.coefficients)=c("beta1", "beta2")
rownames(beta.coefficients)=c("")
print(beta.coefficients)
cat("Between-study variances:",fill=TRUE)
tau2.coefficients=data.frame(cbind(object$coefficients[2],object$coefficients[4]))
colnames(tau2.coefficients)=c("tau1.2", "tau2.2")
rownames(tau2.coefficients)=c("")
print(tau2.coefficients)
cat("Between-study correlation:",fill=TRUE)
rhos=data.frame(object$coefficients[5])
colnames(rhos)=c("rhos")
rownames(rhos)=c("")
print(rhos)
cat("Covariance matrix:",fill=TRUE)
print(object$vcov)
cat("\n")
}
if(method=="bb.cl"){
cat("Log odds ratio:", object$logOR, fill=TRUE)
cat("Ccoffidence interval for odds ratio:",object$OR_CI,fill=TRUE)
cat("Standard error for log odds ratio:",object$se,fill=TRUE)
cat("Hessian matrix in log scale:",fill=TRUE)
print(object$hessian.log)
cat("Convergence:",object$conv, fill=TRUE)
cat("MLE",fill=TRUE)
mle=data.frame(t(object$mle[c(1:4)]))
colnames(mle)=c("a1", "b1","a2", "b2")
rownames(mle)=c("")
print(mle)
cat("\n")
}
if(method=="bn.cl"){
cat("Coefficients:", fill=TRUE)
print(object$coefficients)
cat("Covariance matrix:",fill=TRUE)
print(object$vcov)
cat("\n")
}
if(method=="tb.cl"){
cat("Coefficients:", fill=TRUE)
coefficients=t(object$coefficients)
rownames(coefficients)=""
print(coefficients)
cat("Covariance matrix:",fill=TRUE)
print(object$vcov)
cat("\n")
}
if(method=="tn.cl"){
cat("Coefficients:", fill=TRUE)
coefficients=t(object$coefficients)
rownames(coefficients)=""
print(coefficients)
cat("Covariance matrix:",fill=TRUE)
print(object$vcov)
cat("\n")
}
}
if (!inherits(object, "mmeta"))
stop("Use only with 'mmeta' objects.\n")
result <- summary_mmeta(object)
invisible(result)
}
| /scratch/gouwar.j/cran-all/cranData/xmeta/R/summary.mmeta.R |
summary.msset <- function(object,...) {
summary_msset <- function(object) {
type <- object$type
k <- object$k
method <- object$method
cat("Outcome:",type,fill=TRUE)
if (method=="nn.cl") {
cat("Method: score test for detecting small study effects when the within-study correlations are unknown",fill=TRUE)
cat("Number of outcomes:",k,"\n")
}
## print the object
if(method=="nn.cl"){
cat("Test statistics (msset):",object$msset.TS, fill=TRUE)
cat("P value:",object$msset.pv, fill=TRUE)
cat("\n")
}
}
if (!inherits(object, "msset"))
stop("Use only with 'msset' objects.\n")
result <- summary_msset(object)
invisible(result)
}
| /scratch/gouwar.j/cran-all/cranData/xmeta/R/summary.msset.R |
#' Register S4 classes
#'
#' @description
#' Classes are exported so they can be re-used within S4 classes, see [methods::setOldClass()].
#'
#' * `xml_document`: a complete document.
#' * `xml_nodeset`: a _set_ of nodes within a document.
#' * `xml_missing`: a missing object, e.g. for an empty result set.
#' * `xml_node`: a single node in a document.
#'
#' @importFrom methods setOldClass
#' @keywords internal
#' @rdname oldclass
#' @name xml_document-class
#' @exportClass xml_document
setOldClass("xml_document")
#' @name xml_missing-class
#' @exportClass xml_missing
#' @rdname oldclass
setOldClass("xml_missing")
#' @name xml_node-class
#' @exportClass xml_node
#' @rdname oldclass
setOldClass("xml_node")
#' @name xml_nodeset-class
#' @exportClass xml_nodeset
#' @rdname oldclass
setOldClass("xml_nodeset")
| /scratch/gouwar.j/cran-all/cranData/xml2/R/S4.R |
#' Coerce xml nodes to a list.
#'
#' This turns an XML document (or node or nodeset) into the equivalent R
#' list. Note that this is `as_list()`, not `as.list()`:
#' `lapply()` automatically calls `as.list()` on its inputs, so
#' we can't override the default.
#'
#' `as_list` currently only handles the four most common types of
#' children that an element might have:
#'
#' \itemize{
#' \item Other elements, converted to lists.
#' \item Attributes, stored as R attributes. Attributes that have special meanings in R
#' ([class()], [comment()], [dim()],
#' [dimnames()], [names()], [row.names()] and
#' [tsp()]) are escaped with '.'
#' \item Text, stored as a character vector.
#' }
#'
#' @inheritParams xml_name
#' @param ... Needed for compatibility with generic. Unused.
#' @export
#' @examples
#' as_list(read_xml("<foo> a <b /><c><![CDATA[<d></d>]]></c></foo>"))
#' as_list(read_xml("<foo> <bar><baz /></bar> </foo>"))
#' as_list(read_xml("<foo id = 'a'></foo>"))
#' as_list(read_xml("<foo><bar id='a'/><bar id='b'/></foo>"))
as_list <- function(x, ns = character(), ...) {
UseMethod("as_list")
}
#' @export
as_list.xml_missing <- function(x, ns = character(), ...) {
list()
}
#' @export
as_list.xml_document <- function(x, ns = character(), ...) {
if (!inherits(x, "xml_node")) {
return(list())
}
out <- list(NextMethod())
names(out) <- xml_name(x)
out
}
#' @export
as_list.xml_node <- function(x, ns = character(), ...) {
contents <- xml_contents(x)
if (length(contents) == 0) {
# Base case - contents
type <- xml_type(x)
if (type %in% c("text", "cdata")) {
return(xml_text(x))
}
if (type != "element" && type != "document") {
return(paste("[", type, "]"))
}
out <- list()
} else {
out <- lapply(seq_along(contents), function(i) as_list(contents[[i]], ns = ns))
nms <- ifelse(xml_type(contents) == "element", xml_name(contents, ns = ns), "")
if (any(nms != "")) {
names(out) <- nms
}
}
# Add xml attributes as R attributes
attributes(out) <- c(list(names = names(out)), xml_to_r_attrs(xml_attrs(x, ns = ns)))
out
}
#' @export
as_list.xml_nodeset <- function(x, ns = character(), ...) {
lapply(seq_along(x), function(i) as_list(x[[i]], ns = ns))
}
special_attributes <- c("class", "comment", "dim", "dimnames", "names", "row.names", "tsp")
xml_to_r_attrs <- function(x) {
if (length(x) == 0) {
return(NULL)
}
# escape special names
special <- names(x) %in% special_attributes
names(x)[special] <- paste0(".", names(x)[special])
as.list(x)
}
r_attrs_to_xml <- function(x) {
if (length(x) == 0) {
return(NULL)
}
# Drop R special attributes
x <- x[!names(x) %in% special_attributes]
# Rename any xml attributes needed
special <- names(x) %in% paste0(".", special_attributes)
names(x)[special] <- sub("^\\.", "", names(x)[special])
x
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/as_list.R |
#' Coerce a R list to xml nodes.
#'
#' This turns an R list into the equivalent XML document. Not all R lists will
#' produce valid XML, in particular there can only be one root node and all
#' child nodes need to be named (or empty) lists. R attributes become XML
#' attributes and R names become XML node names.
#'
#' @inheritParams as_list
#' @include as_list.R xml_parse.R
#' @export
#' @examples
# empty lists generate empty nodes
#' as_xml_document(list(x = list()))
#'
#' # Nesting multiple nodes
#' as_xml_document(list(foo = list(bar = list(baz = list()))))
#'
#' # attributes are stored as R attributes
#' as_xml_document(list(foo = structure(list(), id = "a")))
#' as_xml_document(list(foo = list(
#' bar = structure(list(), id = "a"),
#' bar = structure(list(), id = "b")
#' )))
as_xml_document <- function(x, ...) {
UseMethod("as_xml_document")
}
#' @export
as_xml_document.character <- read_xml.character
#' @export
as_xml_document.raw <- read_xml.raw
#' @export
as_xml_document.connection <- read_xml.connection
#' @export
as_xml_document.response <- read_xml.response
#' @export
as_xml_document.list <- function(x, ...) {
if (length(x) > 1) {
abort("Root nodes must be of length 1")
}
add_node <- function(x, parent, tag = NULL) {
if (is.atomic(x)) {
return(.Call(node_new_text, parent$node, as.character(x)))
}
if (!is.null(tag)) {
parent <- xml_add_child(parent, tag)
attr <- r_attrs_to_xml(attributes(x))
for (i in seq_along(attr)) {
xml_set_attr(parent, names(attr)[[i]], attr[[i]])
}
}
for (i in seq_along(x)) {
add_node(x[[i]], parent, names(x)[[i]])
}
}
doc <- xml_new_document()
add_node(x, doc)
xml_root(doc)
}
#' @export
as_xml_document.xml_node <- function(x, ...) {
xml_new_root(.value = x, ..., .copy = TRUE)
}
#' @export
as_xml_document.xml_nodeset <- function(x, root, ...) {
doc <- xml_new_root(.value = root, ..., .copy = TRUE)
for (i in seq_along(x)) {
xml_add_child(doc, x[[i]], .copy = TRUE)
}
doc
}
#' @export
as_xml_document.xml_document <- function(x, ...) {
x
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/as_xml_document.R |
#' @useDynLib xml2, .registration = TRUE
NULL
#' Construct a cdata node
#' @param content The CDATA content, does not include `<![CDATA[`
#' @examples
#' x <- xml_new_root("root")
#' xml_add_child(x, xml_cdata("<d/>"))
#' as.character(x)
#' @export
xml_cdata <- function(content) {
class(content) <- "xml_cdata"
content
}
#' Construct a comment node
#' @param content The comment content
#' @examples
#' x <- xml_new_document()
#' r <- xml_add_child(x, "root")
#' xml_add_child(r, xml_comment("Hello!"))
#' as.character(x)
#' @export
xml_comment <- function(content) {
class(content) <- "xml_comment"
content
}
#' Construct a document type definition
#'
#' This is used to create simple document type definitions. If you need to
#' create a more complicated definition with internal subsets it is recommended
#' to parse a string directly with `read_xml()`.
#' @param name The name of the declaration
#' @param external_id The external ID of the declaration
#' @param system_id The system ID of the declaration
#' @examples
#' r <- xml_new_root(
#' xml_dtd(
#' "html",
#' "-//W3C//DTD XHTML 1.0 Transitional//EN",
#' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
#' )
#' )
#'
#' # Use read_xml directly for more complicated DTD
#' d <- read_xml(
#' '<!DOCTYPE doc [
#' <!ELEMENT doc (#PCDATA)>
#' <!ENTITY foo " test ">
#' ]>
#' <doc>This is a valid document &foo; !</doc>'
#' )
#' @export
xml_dtd <- function(name = "", external_id = "", system_id = "") {
out <- list(name = name, external_id = external_id, system_id = system_id)
class(out) <- "xml_dtd"
out
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/classes.R |
#' @export
format.xml_node <- function(x, ...) {
attrs <- xml_attrs(x)
paste("<",
paste(
c(
xml_name(x),
format_attributes(attrs)
),
collapse = " "
),
">",
sep = ""
)
}
format_attributes <- function(x) {
if (length(x) == 0) {
character(0)
} else {
paste(names(x), quote_str(x), sep = "=")
}
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/format.R |
# Standalone file: do not edit by hand
# Source: <https://github.com/r-lib/rlang/blob/main/R/standalone-obj-type.R>
# ----------------------------------------------------------------------
#
# ---
# repo: r-lib/rlang
# file: standalone-obj-type.R
# last-updated: 2023-05-01
# license: https://unlicense.org
# imports: rlang (>= 1.1.0)
# ---
#
# ## Changelog
#
# 2023-05-01:
# - `obj_type_friendly()` now only displays the first class of S3 objects.
#
# 2023-03-30:
# - `stop_input_type()` now handles `I()` input literally in `arg`.
#
# 2022-10-04:
# - `obj_type_friendly(value = TRUE)` now shows numeric scalars
# literally.
# - `stop_friendly_type()` now takes `show_value`, passed to
# `obj_type_friendly()` as the `value` argument.
#
# 2022-10-03:
# - Added `allow_na` and `allow_null` arguments.
# - `NULL` is now backticked.
# - Better friendly type for infinities and `NaN`.
#
# 2022-09-16:
# - Unprefixed usage of rlang functions with `rlang::` to
# avoid onLoad issues when called from rlang (#1482).
#
# 2022-08-11:
# - Prefixed usage of rlang functions with `rlang::`.
#
# 2022-06-22:
# - `friendly_type_of()` is now `obj_type_friendly()`.
# - Added `obj_type_oo()`.
#
# 2021-12-20:
# - Added support for scalar values and empty vectors.
# - Added `stop_input_type()`
#
# 2021-06-30:
# - Added support for missing arguments.
#
# 2021-04-19:
# - Added support for matrices and arrays (#141).
# - Added documentation.
# - Added changelog.
#
# nocov start
#' Return English-friendly type
#' @param x Any R object.
#' @param value Whether to describe the value of `x`. Special values
#' like `NA` or `""` are always described.
#' @param length Whether to mention the length of vectors and lists.
#' @return A string describing the type. Starts with an indefinite
#' article, e.g. "an integer vector".
#' @noRd
obj_type_friendly <- function(x, value = TRUE) {
if (is_missing(x)) {
return("absent")
}
if (is.object(x)) {
if (inherits(x, "quosure")) {
type <- "quosure"
} else {
type <- class(x)[[1L]]
}
return(sprintf("a <%s> object", type))
}
if (!is_vector(x)) {
return(.rlang_as_friendly_type(typeof(x)))
}
n_dim <- length(dim(x))
if (!n_dim) {
if (!is_list(x) && length(x) == 1) {
if (is_na(x)) {
return(switch(
typeof(x),
logical = "`NA`",
integer = "an integer `NA`",
double =
if (is.nan(x)) {
"`NaN`"
} else {
"a numeric `NA`"
},
complex = "a complex `NA`",
character = "a character `NA`",
.rlang_stop_unexpected_typeof(x)
))
}
show_infinites <- function(x) {
if (x > 0) {
"`Inf`"
} else {
"`-Inf`"
}
}
str_encode <- function(x, width = 30, ...) {
if (nchar(x) > width) {
x <- substr(x, 1, width - 3)
x <- paste0(x, "...")
}
encodeString(x, ...)
}
if (value) {
if (is.numeric(x) && is.infinite(x)) {
return(show_infinites(x))
}
if (is.numeric(x) || is.complex(x)) {
number <- as.character(round(x, 2))
what <- if (is.complex(x)) "the complex number" else "the number"
return(paste(what, number))
}
return(switch(
typeof(x),
logical = if (x) "`TRUE`" else "`FALSE`",
character = {
what <- if (nzchar(x)) "the string" else "the empty string"
paste(what, str_encode(x, quote = "\""))
},
raw = paste("the raw value", as.character(x)),
.rlang_stop_unexpected_typeof(x)
))
}
return(switch(
typeof(x),
logical = "a logical value",
integer = "an integer",
double = if (is.infinite(x)) show_infinites(x) else "a number",
complex = "a complex number",
character = if (nzchar(x)) "a string" else "\"\"",
raw = "a raw value",
.rlang_stop_unexpected_typeof(x)
))
}
if (length(x) == 0) {
return(switch(
typeof(x),
logical = "an empty logical vector",
integer = "an empty integer vector",
double = "an empty numeric vector",
complex = "an empty complex vector",
character = "an empty character vector",
raw = "an empty raw vector",
list = "an empty list",
.rlang_stop_unexpected_typeof(x)
))
}
}
vec_type_friendly(x)
}
vec_type_friendly <- function(x, length = FALSE) {
if (!is_vector(x)) {
abort("`x` must be a vector.")
}
type <- typeof(x)
n_dim <- length(dim(x))
add_length <- function(type) {
if (length && !n_dim) {
paste0(type, sprintf(" of length %s", length(x)))
} else {
type
}
}
if (type == "list") {
if (n_dim < 2) {
return(add_length("a list"))
} else if (is.data.frame(x)) {
return("a data frame")
} else if (n_dim == 2) {
return("a list matrix")
} else {
return("a list array")
}
}
type <- switch(
type,
logical = "a logical %s",
integer = "an integer %s",
numeric = ,
double = "a double %s",
complex = "a complex %s",
character = "a character %s",
raw = "a raw %s",
type = paste0("a ", type, " %s")
)
if (n_dim < 2) {
kind <- "vector"
} else if (n_dim == 2) {
kind <- "matrix"
} else {
kind <- "array"
}
out <- sprintf(type, kind)
if (n_dim >= 2) {
out
} else {
add_length(out)
}
}
.rlang_as_friendly_type <- function(type) {
switch(
type,
list = "a list",
NULL = "`NULL`",
environment = "an environment",
externalptr = "a pointer",
weakref = "a weak reference",
S4 = "an S4 object",
name = ,
symbol = "a symbol",
language = "a call",
pairlist = "a pairlist node",
expression = "an expression vector",
char = "an internal string",
promise = "an internal promise",
... = "an internal dots object",
any = "an internal `any` object",
bytecode = "an internal bytecode object",
primitive = ,
builtin = ,
special = "a primitive function",
closure = "a function",
type
)
}
.rlang_stop_unexpected_typeof <- function(x, call = caller_env()) {
abort(
sprintf("Unexpected type <%s>.", typeof(x)),
call = call
)
}
#' Return OO type
#' @param x Any R object.
#' @return One of `"bare"` (for non-OO objects), `"S3"`, `"S4"`,
#' `"R6"`, or `"R7"`.
#' @noRd
obj_type_oo <- function(x) {
if (!is.object(x)) {
return("bare")
}
class <- inherits(x, c("R6", "R7_object"), which = TRUE)
if (class[[1]]) {
"R6"
} else if (class[[2]]) {
"R7"
} else if (isS4(x)) {
"S4"
} else {
"S3"
}
}
#' @param x The object type which does not conform to `what`. Its
#' `obj_type_friendly()` is taken and mentioned in the error message.
#' @param what The friendly expected type as a string. Can be a
#' character vector of expected types, in which case the error
#' message mentions all of them in an "or" enumeration.
#' @param show_value Passed to `value` argument of `obj_type_friendly()`.
#' @param ... Arguments passed to [abort()].
#' @inheritParams args_error_context
#' @noRd
stop_input_type <- function(x,
what,
...,
allow_na = FALSE,
allow_null = FALSE,
show_value = TRUE,
arg = caller_arg(x),
call = caller_env()) {
# From standalone-cli.R
cli <- env_get_list(
nms = c("format_arg", "format_code"),
last = topenv(),
default = function(x) sprintf("`%s`", x),
inherit = TRUE
)
if (allow_na) {
what <- c(what, cli$format_code("NA"))
}
if (allow_null) {
what <- c(what, cli$format_code("NULL"))
}
if (length(what)) {
what <- oxford_comma(what)
}
if (inherits(arg, "AsIs")) {
format_arg <- identity
} else {
format_arg <- cli$format_arg
}
message <- sprintf(
"%s must be %s, not %s.",
format_arg(arg),
what,
obj_type_friendly(x, value = show_value)
)
abort(message, ..., call = call, arg = arg)
}
oxford_comma <- function(chr, sep = ", ", final = "or") {
n <- length(chr)
if (n < 2) {
return(chr)
}
head <- chr[seq_len(n - 1)]
last <- chr[n]
head <- paste(head, collapse = sep)
# Write a or b. But a, b, or c.
if (n > 2) {
paste0(head, sep, final, " ", last)
} else {
paste0(head, " ", final, " ", last)
}
}
# nocov end
| /scratch/gouwar.j/cran-all/cranData/xml2/R/import-standalone-obj-type.R |
# Standalone file: do not edit by hand
# Source: <https://github.com/r-lib/rlang/blob/main/R/standalone-purrr.R>
# ----------------------------------------------------------------------
#
# ---
# repo: r-lib/rlang
# file: standalone-purrr.R
# last-updated: 2023-02-23
# license: https://unlicense.org
# imports: rlang
# ---
#
# This file provides a minimal shim to provide a purrr-like API on top of
# base R functions. They are not drop-in replacements but allow a similar style
# of programming.
#
# ## Changelog
#
# 2023-02-23:
# * Added `list_c()`
#
# 2022-06-07:
# * `transpose()` is now more consistent with purrr when inner names
# are not congruent (#1346).
#
# 2021-12-15:
# * `transpose()` now supports empty lists.
#
# 2021-05-21:
# * Fixed "object `x` not found" error in `imap()` (@mgirlich)
#
# 2020-04-14:
# * Removed `pluck*()` functions
# * Removed `*_cpl()` functions
# * Used `as_function()` to allow use of `~`
# * Used `.` prefix for helpers
#
# nocov start
map <- function(.x, .f, ...) {
.f <- as_function(.f, env = global_env())
lapply(.x, .f, ...)
}
walk <- function(.x, .f, ...) {
map(.x, .f, ...)
invisible(.x)
}
map_lgl <- function(.x, .f, ...) {
.rlang_purrr_map_mold(.x, .f, logical(1), ...)
}
map_int <- function(.x, .f, ...) {
.rlang_purrr_map_mold(.x, .f, integer(1), ...)
}
map_dbl <- function(.x, .f, ...) {
.rlang_purrr_map_mold(.x, .f, double(1), ...)
}
map_chr <- function(.x, .f, ...) {
.rlang_purrr_map_mold(.x, .f, character(1), ...)
}
.rlang_purrr_map_mold <- function(.x, .f, .mold, ...) {
.f <- as_function(.f, env = global_env())
out <- vapply(.x, .f, .mold, ..., USE.NAMES = FALSE)
names(out) <- names(.x)
out
}
map2 <- function(.x, .y, .f, ...) {
.f <- as_function(.f, env = global_env())
out <- mapply(.f, .x, .y, MoreArgs = list(...), SIMPLIFY = FALSE)
if (length(out) == length(.x)) {
set_names(out, names(.x))
} else {
set_names(out, NULL)
}
}
map2_lgl <- function(.x, .y, .f, ...) {
as.vector(map2(.x, .y, .f, ...), "logical")
}
map2_int <- function(.x, .y, .f, ...) {
as.vector(map2(.x, .y, .f, ...), "integer")
}
map2_dbl <- function(.x, .y, .f, ...) {
as.vector(map2(.x, .y, .f, ...), "double")
}
map2_chr <- function(.x, .y, .f, ...) {
as.vector(map2(.x, .y, .f, ...), "character")
}
imap <- function(.x, .f, ...) {
map2(.x, names(.x) %||% seq_along(.x), .f, ...)
}
pmap <- function(.l, .f, ...) {
.f <- as.function(.f)
args <- .rlang_purrr_args_recycle(.l)
do.call("mapply", c(
FUN = list(quote(.f)),
args, MoreArgs = quote(list(...)),
SIMPLIFY = FALSE, USE.NAMES = FALSE
))
}
.rlang_purrr_args_recycle <- function(args) {
lengths <- map_int(args, length)
n <- max(lengths)
stopifnot(all(lengths == 1L | lengths == n))
to_recycle <- lengths == 1L
args[to_recycle] <- map(args[to_recycle], function(x) rep.int(x, n))
args
}
keep <- function(.x, .f, ...) {
.x[.rlang_purrr_probe(.x, .f, ...)]
}
discard <- function(.x, .p, ...) {
sel <- .rlang_purrr_probe(.x, .p, ...)
.x[is.na(sel) | !sel]
}
map_if <- function(.x, .p, .f, ...) {
matches <- .rlang_purrr_probe(.x, .p)
.x[matches] <- map(.x[matches], .f, ...)
.x
}
.rlang_purrr_probe <- function(.x, .p, ...) {
if (is_logical(.p)) {
stopifnot(length(.p) == length(.x))
.p
} else {
.p <- as_function(.p, env = global_env())
map_lgl(.x, .p, ...)
}
}
compact <- function(.x) {
Filter(length, .x)
}
transpose <- function(.l) {
if (!length(.l)) {
return(.l)
}
inner_names <- names(.l[[1]])
if (is.null(inner_names)) {
fields <- seq_along(.l[[1]])
} else {
fields <- set_names(inner_names)
.l <- map(.l, function(x) {
if (is.null(names(x))) {
set_names(x, inner_names)
} else {
x
}
})
}
# This way missing fields are subsetted as `NULL` instead of causing
# an error
.l <- map(.l, as.list)
map(fields, function(i) {
map(.l, .subset2, i)
})
}
every <- function(.x, .p, ...) {
.p <- as_function(.p, env = global_env())
for (i in seq_along(.x)) {
if (!rlang::is_true(.p(.x[[i]], ...))) return(FALSE)
}
TRUE
}
some <- function(.x, .p, ...) {
.p <- as_function(.p, env = global_env())
for (i in seq_along(.x)) {
if (rlang::is_true(.p(.x[[i]], ...))) return(TRUE)
}
FALSE
}
negate <- function(.p) {
.p <- as_function(.p, env = global_env())
function(...) !.p(...)
}
reduce <- function(.x, .f, ..., .init) {
f <- function(x, y) .f(x, y, ...)
Reduce(f, .x, init = .init)
}
reduce_right <- function(.x, .f, ..., .init) {
f <- function(x, y) .f(y, x, ...)
Reduce(f, .x, init = .init, right = TRUE)
}
accumulate <- function(.x, .f, ..., .init) {
f <- function(x, y) .f(x, y, ...)
Reduce(f, .x, init = .init, accumulate = TRUE)
}
accumulate_right <- function(.x, .f, ..., .init) {
f <- function(x, y) .f(y, x, ...)
Reduce(f, .x, init = .init, right = TRUE, accumulate = TRUE)
}
detect <- function(.x, .f, ..., .right = FALSE, .p = is_true) {
.p <- as_function(.p, env = global_env())
.f <- as_function(.f, env = global_env())
for (i in .rlang_purrr_index(.x, .right)) {
if (.p(.f(.x[[i]], ...))) {
return(.x[[i]])
}
}
NULL
}
detect_index <- function(.x, .f, ..., .right = FALSE, .p = is_true) {
.p <- as_function(.p, env = global_env())
.f <- as_function(.f, env = global_env())
for (i in .rlang_purrr_index(.x, .right)) {
if (.p(.f(.x[[i]], ...))) {
return(i)
}
}
0L
}
.rlang_purrr_index <- function(x, right = FALSE) {
idx <- seq_along(x)
if (right) {
idx <- rev(idx)
}
idx
}
list_c <- function(x) {
inject(c(!!!x))
}
# nocov end
| /scratch/gouwar.j/cran-all/cranData/xml2/R/import-standalone-purrr.R |
# Standalone file: do not edit by hand
# Source: <https://github.com/r-lib/rlang/blob/main/R/standalone-types-check.R>
# ----------------------------------------------------------------------
#
# ---
# repo: r-lib/rlang
# file: standalone-types-check.R
# last-updated: 2023-03-13
# license: https://unlicense.org
# dependencies: standalone-obj-type.R
# imports: rlang (>= 1.1.0)
# ---
#
# ## Changelog
#
# 2023-03-13:
# - Improved error messages of number checkers (@teunbrand)
# - Added `allow_infinite` argument to `check_number_whole()` (@mgirlich).
# - Added `check_data_frame()` (@mgirlich).
#
# 2023-03-07:
# - Added dependency on rlang (>= 1.1.0).
#
# 2023-02-15:
# - Added `check_logical()`.
#
# - `check_bool()`, `check_number_whole()`, and
# `check_number_decimal()` are now implemented in C.
#
# - For efficiency, `check_number_whole()` and
# `check_number_decimal()` now take a `NULL` default for `min` and
# `max`. This makes it possible to bypass unnecessary type-checking
# and comparisons in the default case of no bounds checks.
#
# 2022-10-07:
# - `check_number_whole()` and `_decimal()` no longer treat
# non-numeric types such as factors or dates as numbers. Numeric
# types are detected with `is.numeric()`.
#
# 2022-10-04:
# - Added `check_name()` that forbids the empty string.
# `check_string()` allows the empty string by default.
#
# 2022-09-28:
# - Removed `what` arguments.
# - Added `allow_na` and `allow_null` arguments.
# - Added `allow_decimal` and `allow_infinite` arguments.
# - Improved errors with absent arguments.
#
#
# 2022-09-16:
# - Unprefixed usage of rlang functions with `rlang::` to
# avoid onLoad issues when called from rlang (#1482).
#
# 2022-08-11:
# - Added changelog.
#
# nocov start
# Scalars -----------------------------------------------------------------
.standalone_types_check_dot_call <- .Call
check_bool <- function(x,
...,
allow_na = FALSE,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x) && .standalone_types_check_dot_call(ffi_standalone_is_bool_1.0.7, x, allow_na, allow_null)) {
return(invisible(NULL))
}
stop_input_type(
x,
c("`TRUE`", "`FALSE`"),
...,
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_string <- function(x,
...,
allow_empty = TRUE,
allow_na = FALSE,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
is_string <- .rlang_check_is_string(
x,
allow_empty = allow_empty,
allow_na = allow_na,
allow_null = allow_null
)
if (is_string) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a single string",
...,
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}
.rlang_check_is_string <- function(x,
allow_empty,
allow_na,
allow_null) {
if (is_string(x)) {
if (allow_empty || !is_string(x, "")) {
return(TRUE)
}
}
if (allow_null && is_null(x)) {
return(TRUE)
}
if (allow_na && (identical(x, NA) || identical(x, na_chr))) {
return(TRUE)
}
FALSE
}
check_name <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
is_string <- .rlang_check_is_string(
x,
allow_empty = FALSE,
allow_na = FALSE,
allow_null = allow_null
)
if (is_string) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a valid name",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}
IS_NUMBER_true <- 0
IS_NUMBER_false <- 1
IS_NUMBER_oob <- 2
check_number_decimal <- function(x,
...,
min = NULL,
max = NULL,
allow_infinite = TRUE,
allow_na = FALSE,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (missing(x)) {
exit_code <- IS_NUMBER_false
} else if (0 == (exit_code <- .standalone_types_check_dot_call(
ffi_standalone_check_number_1.0.7,
x,
allow_decimal = TRUE,
min,
max,
allow_infinite,
allow_na,
allow_null
))) {
return(invisible(NULL))
}
.stop_not_number(
x,
...,
exit_code = exit_code,
allow_decimal = TRUE,
min = min,
max = max,
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_number_whole <- function(x,
...,
min = NULL,
max = NULL,
allow_infinite = FALSE,
allow_na = FALSE,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (missing(x)) {
exit_code <- IS_NUMBER_false
} else if (0 == (exit_code <- .standalone_types_check_dot_call(
ffi_standalone_check_number_1.0.7,
x,
allow_decimal = FALSE,
min,
max,
allow_infinite,
allow_na,
allow_null
))) {
return(invisible(NULL))
}
.stop_not_number(
x,
...,
exit_code = exit_code,
allow_decimal = FALSE,
min = min,
max = max,
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}
.stop_not_number <- function(x,
...,
exit_code,
allow_decimal,
min,
max,
allow_na,
allow_null,
arg,
call) {
if (allow_decimal) {
what <- "a number"
} else {
what <- "a whole number"
}
if (exit_code == IS_NUMBER_oob) {
min <- min %||% -Inf
max <- max %||% Inf
if (min > -Inf && max < Inf) {
what <- sprintf("%s between %s and %s", what, min, max)
} else if (x < min) {
what <- sprintf("%s larger than or equal to %s", what, min)
} else if (x > max) {
what <- sprintf("%s smaller than or equal to %s", what, max)
} else {
abort("Unexpected state in OOB check", .internal = TRUE)
}
}
stop_input_type(
x,
what,
...,
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_symbol <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_symbol(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a symbol",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_arg <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_symbol(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"an argument name",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_call <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_call(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a defused call",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_environment <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_environment(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"an environment",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_function <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_function(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a function",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_closure <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_closure(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"an R function",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_formula <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_formula(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a formula",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}
# Vectors -----------------------------------------------------------------
check_character <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_character(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a character vector",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_logical <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_logical(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a logical vector",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_data_frame <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is.data.frame(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a data frame",
...,
allow_null = allow_null,
arg = arg,
call = call
)
}
# nocov end
| /scratch/gouwar.j/cran-all/cranData/xml2/R/import-standalone-types-check.R |
.onLoad <- function(lib, pkg) {
.Call(init_libxml2)
}
libxml2_version <- function() {
as.numeric_version(.Call(libxml2_version_))
}
xml_parse_options <- function() {
.Call(xml_parse_options_)
}
xml_save_options <- function() {
.Call(xml_save_options_)
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/init.R |
nodeset_apply <- function(x, fun, ...) UseMethod("nodeset_apply")
#' @export
nodeset_apply.xml_missing <- function(x, fun, ...) {
xml_nodeset()
}
#' @export
nodeset_apply.xml_nodeset <- function(x, fun, ...) {
if (length(x) == 0) {
return(xml_nodeset())
}
is_missing <- is.na(x)
res <- list(length(x))
res[is_missing] <- list(xml_missing())
if (any(!is_missing)) {
res[!is_missing] <- lapply(x[!is_missing], function(x) fun(x$node, ...))
}
make_nodeset(res, x[[1]]$doc)
}
#' @export
nodeset_apply.xml_node <- function(x, fun, ...) {
nodes <- fun(x$node, ...)
xml_nodeset(lapply(nodes, xml_node, doc = x$doc))
}
#' @export
nodeset_apply.xml_document <- function(x, fun, ...) {
if (inherits(x, "xml_node")) {
NextMethod()
} else {
xml_nodeset()
}
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/nodeset_apply.R |
path_to_connection <- function(path, check = c("file", "dir")) {
check <- match.arg(check)
if (!is.character(path) || length(path) != 1L) {
return(path)
}
if (is_url(path)) {
if (requireNamespace("curl", quietly = TRUE)) {
return(curl::curl(path))
} else {
return(url(path))
}
}
if (check == "file") {
path <- check_path(path)
} else {
path <- file.path(check_path(dirname(path)), basename(path))
}
switch(tools::file_ext(path),
gz = gzfile(path, ""),
bz2 = bzfile(path, ""),
xz = xzfile(path, ""),
zip = zipfile(path, ""),
path
)
}
is_url <- function(path) {
grepl("^(http|ftp)s?://", path)
}
check_path <- function(path, call = caller_env()) {
if (file.exists(path)) {
return(normalizePath(path, "/", mustWork = FALSE))
}
msg <- "{.file {path}} does not exist"
if (!is_absolute_path(path)) {
msg <- paste0(msg, " in current working directory ({.path {getwd()}})")
}
msg <- paste0(msg, ".")
cli::cli_abort(msg, call = call)
}
is_absolute_path <- function(path) {
grepl("^(/|[A-Za-z]:|\\\\|~)", path)
}
zipfile <- function(path, open = "r") {
files <- utils::unzip(path, list = TRUE)
file <- files$Name[[1]]
if (nrow(files) > 1) {
message("Multiple files in zip: reading '", file, "'")
}
unz(path, file, open = open)
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/paths.R |
`%||%` <- function(a, b) if (is.null(a)) b else a
is_named <- function(x) {
all(has_names(x))
}
has_names <- function(x) {
nms <- names(x)
if (is.null(nms)) {
rep(FALSE, length(x))
} else {
!(is.na(nms) | nms == "")
}
}
# non smart quote version of sQuote
quote_str <- function(x, quote = "\"") {
if (!length(x)) {
return(character(0))
}
paste0(quote, x, quote)
}
is_installed <- function(pkg) {
requireNamespace(pkg, quietly = TRUE)
}
# Format the C bitwise flags for display in Rd. The input object is a named
# integer vector with a 'descriptions' character vector attribute that
# corresponds to each flag.
describe_options <- function(x) {
paste0(
"\\describe{\n",
paste0(" \\item{", names(x), "}{", attr(x, "descriptions"), "}", collapse = "\n"),
"\n}"
)
}
s_quote <- function(x) paste0("'", x, "'")
# Similar to match.arg, but returns character() with NULL or empty input and
# errors if any of the inputs are not found (fixing
# https://bugs.r-project.org/bugzilla3/show_bug.cgi?id=16659)
parse_options <- function(arg, options) {
if (is.numeric(arg)) {
return(as.integer(arg))
}
if (is.null(arg) || !any(nzchar(arg))) {
return(0L)
}
# set duplicates.ok = TRUE so any duplicates are counted differently than
# non-matches, then take only unique results
i <- pmatch(arg, names(options), duplicates.ok = TRUE)
if (any(is.na(i))) {
stop(
sprintf(
"`options` %s is not a valid option, should be one of %s",
s_quote(arg[is.na(i)][1L]),
paste(s_quote(names(options)), collapse = ", ")
),
call. = FALSE
)
}
sum(options[unique(i)])
}
#' Get path to a xml2 example
#'
#' xml2 comes bundled with a number of sample files in its \sQuote{inst/extdata}
#' directory. This function makes them easy to access.
#' @param path Name of file. If `NULL`, the example files will be listed.
#' @export
xml2_example <- function(path = NULL) {
if (is.null(path)) {
dir(system.file("extdata", package = "xml2"))
} else {
system.file("extdata", path, package = "xml2", mustWork = TRUE)
}
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/utils.R |
#' @keywords internal
"_PACKAGE"
## usethis namespace: start
#' @import rlang
## usethis namespace: end
NULL
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml2-package.R |
#' Retrieve an attribute.
#'
#' `xml_attrs()` retrieves all attributes values as a named character
#' vector, `xml_attrs() <-` or `xml_set_attrs()` sets all attribute
#' values. `xml_attr()` retrieves the value of single attribute and
#' `xml_attr() <-` or `xml_set_attr()` modifies its value. If the
#' attribute doesn't exist, it will return `default`, which defaults to
#' `NA`. `xml_has_attr()` tests if an attribute is present.
#'
#' @inheritParams xml_name
#' @param attr Name of attribute to extract.
#' @param default Default value to use when attribute is not present.
#' @return `xml_attr()` returns a character vector. `NA` is used
#' to represent of attributes that aren't defined.
#'
#' `xml_has_attr()` returns a logical vector.
#'
#' `xml_attrs()` returns a named character vector if `x` x is single
#' node, or a list of character vectors if given a nodeset
#' @export
#' @examples
#' x <- read_xml("<root id='1'><child id ='a' /><child id='b' d='b'/></root>")
#' xml_attr(x, "id")
#' xml_attr(x, "apple")
#' xml_attrs(x)
#'
#' kids <- xml_children(x)
#' kids
#' xml_attr(kids, "id")
#' xml_has_attr(kids, "id")
#' xml_attrs(kids)
#'
#' # Missing attributes give missing values
#' xml_attr(xml_children(x), "d")
#' xml_has_attr(xml_children(x), "d")
#'
#' # If the document has a namespace, use the ns argument and
#' # qualified attribute names
#' x <- read_xml('
#' <root xmlns:b="http://bar.com" xmlns:f="http://foo.com">
#' <doc b:id="b" f:id="f" id="" />
#' </root>
#' ')
#' doc <- xml_children(x)[[1]]
#' ns <- xml_ns(x)
#'
#' xml_attrs(doc)
#' xml_attrs(doc, ns)
#'
#' # If you don't supply a ns spec, you get the first matching attribute
#' xml_attr(doc, "id")
#' xml_attr(doc, "b:id", ns)
#' xml_attr(doc, "id", ns)
#'
#' # Can set a single attribute with `xml_attr() <-` or `xml_set_attr()`
#' xml_attr(doc, "id") <- "one"
#' xml_set_attr(doc, "id", "two")
#'
#' # Or set multiple attributes with `xml_attrs()` or `xml_set_attrs()`
#' xml_attrs(doc) <- c("b:id" = "one", "f:id" = "two", "id" = "three")
#' xml_set_attrs(doc, c("b:id" = "one", "f:id" = "two", "id" = "three"))
xml_attr <- function(x, attr, ns = character(), default = NA_character_) {
.Call(node_attr, x, attr, as.character(default), ns)
}
#' @export
#' @rdname xml_attr
xml_has_attr <- function(x, attr, ns = character()) {
!is.na(xml_attr(x, attr, ns = ns))
}
#' @export
#' @rdname xml_attr
xml_attrs <- function(x, ns = character()) {
.Call(node_attrs, x, nsMap = ns)
}
#' @param value character vector of new value.
#' @rdname xml_attr
#' @export
`xml_attr<-` <- function(x, attr, ns = character(), value) {
UseMethod("xml_attr<-")
}
#' @export
`xml_attr<-.xml_node` <- function(x, attr, ns = character(), value) {
if (is.null(value)) {
.Call(node_remove_attr, x$node, attr, ns)
} else {
value <- as.character(value)
.Call(node_set_attr, x$node, attr, value, ns)
}
x
}
#' @export
`xml_attr<-.xml_nodeset` <- function(x, attr, ns = character(), value) {
if (length(x) == 0) {
return(x)
}
if (length(value) == 0) {
value <- list(value)
}
mapply(`xml_attr<-`, x, attr = attr, value = value, SIMPLIFY = FALSE, MoreArgs = list(ns = ns))
x
}
#' @export
`xml_attr<-.xml_missing` <- function(x, attr, ns = character(), value) {
x
}
#' @rdname xml_attr
#' @export
xml_set_attr <- function(x, attr, value, ns = character()) {
UseMethod("xml_set_attr")
}
# This function definition is used for all methods, we need to rearrange the `ns`
# argument to be at the end of the set function
set_attr_fun <- function(x, attr, value, ns = character()) {
xml_attr(x = x, attr = attr, ns = ns) <- value
}
#' @export
xml_set_attr.xml_node <- set_attr_fun
#' @export
xml_set_attr.xml_nodeset <- set_attr_fun
#' @export
xml_set_attr.xml_missing <- set_attr_fun
#' @rdname xml_attr
#' @export
`xml_attrs<-` <- function(x, ns = character(), value) {
UseMethod("xml_attrs<-")
}
#' @export
`xml_attrs<-.xml_node` <- function(x, ns = character(), value) {
if (!is_named(value)) {
cli::cli_abort("{.arg value} must be a named character vector or `NULL`")
}
attrs <- names(value)
# as.character removes all attributes (including names)
value <- stats::setNames(as.character(value), attrs)
current_attrs <- names(xml_attrs(x, ns = ns))
existing <- intersect(current_attrs, attrs)
new <- setdiff(attrs, current_attrs)
removed <- setdiff(current_attrs, attrs)
# replace existing attributes and add new ones
Map(function(attr, val) {
xml_attr(x, attr, ns) <- val
}, attr = c(existing, new), value[c(existing, new)])
# Remove attributes which no longer exist
Map(function(attr) {
xml_attr(x, attr, ns) <- NULL
}, attr = removed)
x
}
#' @export
`xml_attrs<-.xml_nodeset` <- function(x, ns = character(), value) {
if (length(x) == 0) {
return(x)
}
if (!is.list(ns)) {
ns <- list(ns)
}
if (!is.list(value)) {
value <- list(value)
}
if (!all(vapply(value, is_named, logical(1)))) {
cli::cli_abort("{.arg {value}} must be a list of named character vectors.")
}
Map(`xml_attrs<-`, x, ns, value)
x
}
#' @export
`xml_attrs<-.xml_missing` <- function(x, ns = character(), value) {
x
}
#' @rdname xml_attr
#' @export
xml_set_attrs <- function(x, value, ns = character()) {
UseMethod("xml_set_attrs")
}
# This function definition is used for all methods, we need to rearrange the `ns`
# argument to be at the end of the set function
set_attrs_fun <- function(x, value, ns = character()) {
xml_attrs(x = x, ns = ns) <- value
}
#' @export
xml_set_attrs.xml_node <- set_attrs_fun
#' @export
xml_set_attrs.xml_nodeset <- set_attrs_fun
#' @export
xml_set_attrs.xml_missing <- set_attrs_fun
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_attr.R |
#' Navigate around the family tree.
#'
#' `xml_children` returns only elements, `xml_contents` returns
#' all nodes. `xml_length` returns the number of children.
#' `xml_parent` returns the parent node, `xml_parents`
#' returns all parents up to the root. `xml_siblings` returns all nodes
#' at the same level. `xml_child` makes it easy to specify a specific
#' child to return.
#'
#' @inheritParams xml_name
#' @param only_elements For `xml_length`, should it count all children,
#' or just children that are elements (the default)?
#' @param search For `xml_child`, either the child number to return (by
#' position), or the name of the child node to return. If there are multiple
#' child nodes with the same name, the first will be returned
#' @return A node or nodeset (possibly empty). Results are always de-duplicated.
#' @export
#' @examples
#' x <- read_xml("<foo> <bar><boo /></bar> <baz/> </foo>")
#' xml_children(x)
#' xml_children(xml_children(x))
#' xml_siblings(xml_children(x)[[1]])
#'
#' # Note the each unique node only appears once in the output
#' xml_parent(xml_children(x))
#'
#' # Mixed content
#' x <- read_xml("<foo> a <b/> c <d>e</d> f</foo>")
#' # Childen gets the elements, contents gets all node types
#' xml_children(x)
#' xml_contents(x)
#'
#' xml_length(x)
#' xml_length(x, only_elements = FALSE)
#'
#' # xml_child makes it easier to select specific children
#' xml_child(x)
#' xml_child(x, 2)
#' xml_child(x, "baz")
xml_children <- function(x) {
nodeset_apply(x, function(x) .Call(node_children, x, TRUE))
}
#' @export
#' @rdname xml_children
xml_child <- function(x, search = 1, ns = xml_ns(x)) {
if (length(search) != 1) {
cli::cli_abort("{.arg {search}} must be of length 1.")
}
if (is.numeric(search)) {
xml_children(x)[[search]]
} else if (is.character(search)) {
xml_find_first(x, xpath = paste0("./", search), ns = ns)
} else {
cli::cli_abort("{.arg search} must be `numeric` or `character`.")
}
}
#' @export
#' @rdname xml_children
xml_contents <- function(x) {
nodeset_apply(x, function(x) .Call(node_children, x, FALSE))
}
#' @export
#' @rdname xml_children
xml_parents <- function(x) {
nodeset_apply(x, function(x) .Call(node_parents, x))
}
#' @export
#' @rdname xml_children
xml_siblings <- function(x) {
nodeset_apply(x, function(x) .Call(node_siblings, x, TRUE))
}
#' @export
#' @rdname xml_children
xml_parent <- function(x) {
UseMethod("xml_parent")
}
#' @export
xml_parent.xml_missing <- function(x) {
xml_missing()
}
#' @export
xml_parent.xml_node <- function(x) {
xml_node(.Call(node_parent, x$node), x$doc)
}
#' @export
xml_parent.xml_nodeset <- function(x) {
nodeset_apply(x, function(x) .Call(node_parent, x))
}
#' @export
#' @rdname xml_children
xml_length <- function(x, only_elements = TRUE) {
.Call(node_length, x, only_elements)
}
#' @export
#' @rdname xml_children
xml_root <- function(x) {
stopifnot(inherits(x, c("xml_node", "xml_document", "xml_nodeset")))
if (inherits(x, "xml_nodeset")) {
if (length(x) == 0) {
return(NULL)
} else {
return(xml_root(x[[1]]))
}
}
if (!.Call(doc_has_root, x$doc)) {
xml_missing()
} else {
xml_document(x$doc)
}
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_children.R |
xml_document <- function(doc) {
if (.Call(doc_has_root, doc)) {
x <- xml_node(.Call(doc_root, doc), doc)
class(x) <- c("xml_document", class(x))
x
} else {
out <- list(doc = doc)
class(out) <- "xml_document"
out
}
}
doc_type <- function(x) {
if (is.null(x$doc)) {
return("xml")
}
if (.Call(doc_is_html, x$doc)) {
"html"
} else {
"xml"
}
}
#' @export
print.xml_document <- function(x, width = getOption("width"), max_n = 20, ...) {
doc <- xml_document(x$doc)
cat("{", doc_type(x), "_document}\n", sep = "")
if (inherits(doc, "xml_node")) {
cat(format(doc), "\n", sep = "")
show_nodes(xml_children(doc), width = width, max_n = max_n)
}
}
#' @export
as.character.xml_document <- function(x, ..., options = "format", encoding = "UTF-8") {
options <- parse_options(options, xml_save_options())
.Call(doc_write_character, x$doc, encoding, options)
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_document.R |
#' Find nodes that match an xpath expression.
#'
#' Xpath is like regular expressions for trees - it's worth learning if
#' you're trying to extract nodes from arbitrary locations in a document.
#' Use `xml_find_all` to find all matches - if there's no match you'll
#' get an empty result. Use `xml_find_first` to find a specific match -
#' if there's no match you'll get an `xml_missing` node.
#'
#' @section Deprecated functions:
#' `xml_find_one()` has been deprecated. Instead use
#' `xml_find_first()`.
#' @param xpath A string containing an xpath (1.0) expression.
#' @inheritParams xml_name
#' @param ... Further arguments passed to or from other methods.
#' @return `xml_find_all` returns a nodeset if applied to a node, and a nodeset
#' or a list of nodesets if applied to a nodeset. If there are no matches,
#' the nodeset(s) will be empty. Within each nodeset, the result will always
#' be unique; repeated nodes are automatically de-duplicated.
#'
#' `xml_find_first` returns a node if applied to a node, and a nodeset
#' if applied to a nodeset. The output is *always* the same size as
#' the input. If there are no matches, `xml_find_first` will return a
#' missing node; if there are multiple matches, it will return the first
#' only.
#'
#' `xml_find_num`, `xml_find_chr`, `xml_find_lgl` return
#' numeric, character and logical results respectively.
#' @export
#' @seealso [xml_ns_strip()] to remove the default namespaces
#' @examples
#' x <- read_xml("<foo><bar><baz/></bar><baz/></foo>")
#' xml_find_all(x, ".//baz")
#' xml_path(xml_find_all(x, ".//baz"))
#'
#' # Note the difference between .// and //
#' # // finds anywhere in the document (ignoring the current node)
#' # .// finds anywhere beneath the current node
#' (bar <- xml_find_all(x, ".//bar"))
#' xml_find_all(bar, ".//baz")
#' xml_find_all(bar, "//baz")
#'
#' # Find all vs find one -----------------------------------------------------
#' x <- read_xml("<body>
#' <p>Some <b>text</b>.</p>
#' <p>Some <b>other</b> <b>text</b>.</p>
#' <p>No bold here!</p>
#' </body>")
#' para <- xml_find_all(x, ".//p")
#'
#' # By default, if you apply xml_find_all to a nodeset, it finds all matches,
#' # de-duplicates them, and returns as a single nodeset. This means you
#' # never know how many results you'll get
#' xml_find_all(para, ".//b")
#'
#' # If you set flatten to FALSE, though, xml_find_all will return a list of
#' # nodesets, where each nodeset contains the matches for the corresponding
#' # node in the original nodeset.
#' xml_find_all(para, ".//b", flatten = FALSE)
#'
#' # xml_find_first only returns the first match per input node. If there are 0
#' # matches it will return a missing node
#' xml_find_first(para, ".//b")
#' xml_text(xml_find_first(para, ".//b"))
#'
#' # Namespaces ---------------------------------------------------------------
#' # If the document uses namespaces, you'll need use xml_ns to form
#' # a unique mapping between full namespace url and a short prefix
#' x <- read_xml('
#' <root xmlns:f = "http://foo.com" xmlns:g = "http://bar.com">
#' <f:doc><g:baz /></f:doc>
#' <f:doc><g:baz /></f:doc>
#' </root>
#' ')
#' xml_find_all(x, ".//f:doc")
#' xml_find_all(x, ".//f:doc", xml_ns(x))
xml_find_all <- function(x, xpath, ns = xml_ns(x), ...) {
UseMethod("xml_find_all")
}
#' @export
xml_find_all.xml_missing <- function(x, xpath, ns = xml_ns(x), ...) {
xml_nodeset()
}
#' @export
xml_find_all.xml_node <- function(x, xpath, ns = xml_ns(x), ...) {
nodes <- .Call(xpath_search, x$node, x$doc, xpath, ns, Inf)
xml_nodeset(nodes)
}
#' @param flatten A logical indicating whether to return a single, flattened
#' nodeset or a list of nodesets.
#' @export
#' @rdname xml_find_all
xml_find_all.xml_nodeset <- function(x, xpath, ns = xml_ns(x), flatten = TRUE, ...) {
if (length(x) == 0) {
return(xml_nodeset())
}
res <- lapply(x, function(x) .Call(xpath_search, x$node, x$doc, xpath, ns, Inf))
if (isTRUE(flatten)) {
return(xml_nodeset(unlist(recursive = FALSE, res)))
}
res[] <- lapply(res, xml_nodeset)
res
}
#' @export
#' @rdname xml_find_all
xml_find_first <- function(x, xpath, ns = xml_ns(x)) {
UseMethod("xml_find_first")
}
#' @export
xml_find_first.xml_missing <- function(x, xpath, ns = xml_ns(x)) {
xml_missing()
}
#' @export
xml_find_first.xml_node <- function(x, xpath, ns = xml_ns(x)) {
res <- .Call(xpath_search, x$node, x$doc, xpath, ns, 1)
if (length(res) == 1) {
res[[1]]
} else {
res
}
}
#' @export
xml_find_first.xml_nodeset <- function(x, xpath, ns = xml_ns(x)) {
if (length(x) == 0) {
return(xml_nodeset())
}
xml_nodeset(
lapply(
x,
function(x) {
xml_find_first(x, xpath = xpath, ns = ns)
}
),
deduplicate = FALSE
)
}
#' @export
#' @rdname xml_find_all
xml_find_num <- function(x, xpath, ns = xml_ns(x)) {
UseMethod("xml_find_num")
}
#' @export
xml_find_num.xml_node <- function(x, xpath, ns = xml_ns(x)) {
res <- .Call(xpath_search, x$node, x$doc, xpath, ns, Inf)
if (is.numeric(res) && is.nan(res)) {
return(res)
}
check_number_decimal(res, arg = I(paste0("Element at path `", xpath, "`")))
res
}
#' @export
xml_find_num.xml_nodeset <- function(x, xpath, ns = xml_ns(x)) {
if (length(x) == 0) {
return(numeric())
}
vapply(x, function(x) xml_find_num(x, xpath = xpath, ns = ns), numeric(1))
}
#' @export
xml_find_num.xml_missing <- function(x, xpath, ns = xml_ns(x)) {
numeric(0)
}
#' @export
#' @rdname xml_find_all
xml_find_int <- function(x, xpath, ns = xml_ns(x)) {
UseMethod("xml_find_int")
}
#' @export
xml_find_int.xml_node <- function(x, xpath, ns = xml_ns(x)) {
res <- .Call(xpath_search, x$node, x$doc, xpath, ns, Inf)
check_number_whole(res, arg = I(paste0("Element at path `", xpath, "`")))
as.integer(res)
}
#' @export
xml_find_int.xml_nodeset <- function(x, xpath, ns = xml_ns(x)) {
if (length(x) == 0) {
return(integer())
}
vapply(x, function(x) xml_find_int(x, xpath = xpath, ns = ns), integer(1))
}
#' @export
xml_find_int.xml_missing <- function(x, xpath, ns = xml_ns(x)) {
integer(0)
}
#' @export
#' @rdname xml_find_all
xml_find_chr <- function(x, xpath, ns = xml_ns(x)) {
UseMethod("xml_find_chr")
}
#' @export
xml_find_chr.xml_node <- function(x, xpath, ns = xml_ns(x)) {
res <- .Call(xpath_search, x$node, x$doc, xpath, ns, Inf)
check_string(res, arg = I(paste0("Element at path `", xpath, "`")))
res
}
#' @export
xml_find_chr.xml_nodeset <- function(x, xpath, ns = xml_ns(x)) {
if (length(x) == 0) {
return(character())
}
vapply(x, function(x) xml_find_chr(x, xpath = xpath, ns = ns), character(1))
}
#' @export
xml_find_chr.xml_missing <- function(x, xpath, ns = xml_ns(x)) {
character(0)
}
#' @export
#' @rdname xml_find_all
xml_find_lgl <- function(x, xpath, ns = xml_ns(x)) {
UseMethod("xml_find_lgl")
}
#' @export
xml_find_lgl.xml_node <- function(x, xpath, ns = xml_ns(x)) {
res <- .Call(xpath_search, x$node, x$doc, xpath, ns, Inf)
check_bool(res, arg = I(paste0("Element at path `", xpath, "`")))
res
}
#' @export
xml_find_lgl.xml_nodeset <- function(x, xpath, ns = xml_ns(x)) {
if (length(x) == 0) {
return(logical())
}
vapply(x, function(x) xml_find_lgl(x, xpath = xpath, ns = ns), logical(1))
}
#' @export
xml_find_lgl.xml_missing <- function(x, xpath, ns = xml_ns(x)) {
logical(0)
}
# Deprecated functions ----------------------------------------------------
#' @rdname xml_find_all
#' @usage NULL
#' @export
xml_find_one <- function(x, xpath, ns = xml_ns(x)) {
.Deprecated("xml_find_first")
UseMethod("xml_find_first")
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_find.R |
#' Construct an missing xml object
#' @export
#' @keywords internal
xml_missing <- function() {
out <- list()
class(out) <- "xml_missing"
out
}
format.xml_missing <- function(x, ...) {
"<NA>"
}
#' @export
print.xml_missing <- function(x, width = getOption("width"), max_n = 20, ...) {
cat("{xml_missing}\n")
cat(format(x), "\n", sep = "")
}
#' @export
as.character.xml_missing <- function(x, ...) {
NA_character_
}
# These mimic the behavior of NA[[1]], NA[[2]], NA[1], NA[2]
#' @export
`[.xml_missing` <- function(x, i, ...) x
#' @export
`[[.xml_missing` <- function(x, i, ...) if (i == 1L) x else abort("subscript out of bounds")
#' @export
is.na.xml_missing <- function(x) {
TRUE
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_missing.R |
#' Modify a tree by inserting, replacing or removing nodes
#'
#' `xml_add_sibling()` and `xml_add_child()` are used to insert a node
#' as a sibling or a child. `xml_add_parent()` adds a new parent in
#' between the input node and the current parent. `xml_replace()`
#' replaces an existing node with a new node. `xml_remove()` removes a
#' node from the tree.
#'
#' @details Care needs to be taken when using `xml_remove()`,
#' @param .x a document, node or nodeset.
#' @param .copy whether to copy the `.value` before replacing. If this is `FALSE`
#' then the node will be moved from it's current location.
#' @param .where to add the new node, for `xml_add_child` the position
#' after which to add, use `0` for the first child. For
#' `xml_add_sibling` either \sQuote{"before"} or \sQuote{"after"}
#' indicating if the new node should be before or after `.x`.
#' @param ... If named attributes or namespaces to set on the node, if unnamed
#' text to assign to the node.
#' @param .value node to insert.
#' @param free When removing the node also free the memory used for that node.
#' Note if you use this option you cannot use any existing objects pointing to
#' the node or its children, it is likely to crash R or return garbage.
#' @export
xml_replace <- function(.x, .value, ..., .copy = TRUE) {
UseMethod("xml_replace")
}
#' @export
xml_replace.xml_node <- function(.x, .value, ..., .copy = TRUE) {
node <- create_node(.value, .parent = .x, .copy = .copy, ...)
.x$node <- .Call(node_replace, .x$node, node$node)
node
}
#' @export
xml_replace.xml_nodeset <- function(.x, .value, ..., .copy = TRUE) {
if (length(.x) == 0) {
return(.x)
}
# Need to wrap this in a list if a bare xml_node so it is recycled properly
if (inherits(.value, "xml_node")) {
.value <- list(.value)
}
Map(xml_replace, .x, .value, ..., .copy = .copy)
}
#' @export
xml_replace.xml_missing <- function(.x, .value, ..., .copy = TRUE) {
.x
}
#' @rdname xml_replace
#' @export
xml_add_sibling <- function(.x, .value, ..., .where = c("after", "before"), .copy = TRUE) {
UseMethod("xml_add_sibling")
}
#' @export
xml_add_sibling.xml_node <- function(.x, .value, ..., .where = c("after", "before"), .copy = inherits(.value, "xml_node")) {
.where <- match.arg(.where)
node <- create_node(.value, .parent = .x, .copy = .copy, ...)
.x$node <- switch(.where,
before = .Call(node_prepend_sibling, .x$node, node$node),
after = .Call(node_append_sibling, .x$node, node$node)
)
invisible(.x)
}
#' @export
xml_add_sibling.xml_nodeset <- function(.x, .value, ..., .where = c("after", "before"), .copy = TRUE) {
if (length(.x) == 0) {
return(.x)
}
.where <- match.arg(.where)
# Need to wrap this in a list if a bare xml_node so it is recycled properly
if (inherits(.value, "xml_node")) {
.value <- list(.value)
}
invisible(Map(xml_add_sibling, rev(.x), rev(.value), ..., .where = .where, .copy = .copy))
}
#' @export
xml_add_sibling.xml_missing <- function(.x, .value, ..., .where = c("after", "before"), .copy = TRUE) {
.x
}
# Helper function used in the xml_add* methods
create_node <- function(.value, ..., .parent, .copy) {
if (inherits(.value, "xml_node")) {
if (isTRUE(.copy)) {
.value$node <- .Call(node_copy, .value$node)
}
return(.value)
}
if (inherits(.value, "xml_cdata")) {
return(xml_node(.Call(node_cdata_new, .parent$doc, .value), doc = .parent$doc))
}
if (inherits(.value, "xml_comment")) {
return(xml_node(.Call(node_comment_new, .value), doc = .parent$doc))
}
if (inherits(.value, "xml_dtd")) {
.Call(node_new_dtd, .parent$doc, .value$name, .value$external_id, .value$system_id)
return()
}
check_character(.value)
parts <- strsplit(.value, ":")[[1]]
if (length(parts) == 2 && !is.null(.parent$node)) {
namespace <- .Call(ns_lookup, .parent$doc, .parent$node, parts[[1]])
node <- list(node = .Call(node_new_ns, parts[[2]], namespace), doc = .parent$doc)
} else {
node <- list(node = .Call(node_new, .value), doc = .parent$doc)
}
class(node) <- "xml_node"
args <- list(...)
named <- has_names(args)
xml_attrs(node) <- args[named]
xml_text(node) <- paste(args[!named], collapse = "")
node
}
#' @rdname xml_replace
#' @export
xml_add_child <- function(.x, .value, ..., .where = length(xml_children(.x)), .copy = TRUE) {
UseMethod("xml_add_child")
}
#' @export
xml_add_child.xml_node <- function(.x, .value, ..., .where = length(xml_children(.x)), .copy = inherits(.value, "xml_node")) {
node <- create_node(.value, .parent = .x, .copy = .copy, ...)
if (.where == 0L) {
if (.Call(node_has_children, .x$node, TRUE)) {
.Call(node_prepend_child, .x$node, node$node)
} else {
.Call(node_append_child, .x$node, node$node)
}
} else {
num_children <- length(xml_children(.x))
if (.where >= num_children) {
.Call(node_append_child, .x$node, node$node)
} else {
.Call(node_append_sibling, xml_child(.x, search = .where)$node, node$node)
}
}
invisible(node)
}
#' @export
xml_add_child.xml_document <- function(.x, .value, ..., .where = length(xml_children(.x)), .copy = inherits(.value, "xml_node")) {
if (inherits(.x, "xml_node")) {
NextMethod("xml_add_child")
} else {
node <- create_node(.value, .parent = .x, .copy = .copy, ...)
if (!is.null(node)) {
if (!.Call(doc_has_root, .x$doc)) {
.Call(doc_set_root, .x$doc, node$node)
}
.Call(node_append_child, .Call(doc_root, .x$doc), node$node)
}
invisible(xml_document(.x$doc))
}
}
#' @export
xml_add_child.xml_nodeset <- function(.x, .value, ..., .where = length(xml_children(.x)), .copy = TRUE) {
if (length(.x) == 0) {
return(.x)
}
# Need to wrap this in a list if a bare xml_node so it is recycled properly
if (inherits(.value, "xml_node")) {
.value <- list(.value)
}
res <- Map(xml_add_child, .x, .value, ..., .where = .where, .copy = .copy)
invisible(make_nodeset(res, res[[1]]$doc))
}
#' @export
xml_add_child.xml_missing <- function(.x, .value, ..., .copy = TRUE) {
.x
}
#' @rdname xml_replace
#' @export
xml_add_parent <- function(.x, .value, ...) {
UseMethod("xml_add_parent")
}
#' @export
xml_add_parent.xml_node <- function(.x, .value, ...) {
new_parent <- xml_replace(.x, .value = .value, ..., .copy = FALSE)
node <- xml_add_child(new_parent, .value = .x, .copy = FALSE)
invisible(node)
}
#' @export
xml_add_parent.xml_nodeset <- function(.x, .value, ...) {
if (length(.x) == 0) {
return(.x)
}
# Need to wrap this in a list if a bare xml_node so it is recycled properly
if (inherits(.value, "xml_node")) {
.value <- list(.value)
}
res <- Map(xml_add_parent, .x, .value, ...)
invisible(make_nodeset(res, res[[1]]$doc))
}
#' @export
xml_add_parent.xml_missing <- function(.x, .value, ..., .copy = TRUE) {
invisible(.x)
}
#' @rdname xml_replace
#' @export
xml_remove <- function(.x, free = FALSE) {
UseMethod("xml_remove")
}
#' @export
xml_remove.xml_node <- function(.x, free = FALSE) {
.Call(node_remove, .x$node, free)
invisible(.x)
}
#' @export
xml_remove.xml_nodeset <- function(.x, free = FALSE) {
if (length(.x) == 0) {
return(invisible(.x))
}
invisible(Map(xml_remove, rev(.x), free = free))
}
#' @export
xml_remove.xml_missing <- function(.x, free = FALSE) {
invisible(.x)
}
#' Set the node's namespace
#'
#' The namespace to be set must be already defined in one of the node's
#' ancestors.
#' @param .x a node
#' @param prefix The namespace prefix to use
#' @param uri The namespace URI to use
#' @return the node (invisibly)
#' @export
xml_set_namespace <- function(.x, prefix = "", uri = "") {
stopifnot(inherits(.x, "xml_node"))
if (nzchar(uri)) {
.Call(node_set_namespace_uri, .x$doc, .x$node, uri)
} else {
.Call(node_set_namespace_prefix, .x$doc, .x$node, prefix)
}
invisible(.x)
}
#' Create a new document, possibly with a root node
#'
#' `xml_new_document` creates only a new document without a root node. In
#' most cases you should instead use `xml_new_root`, which creates a new
#' document and assigns the root node in one step.
#' @param version The version number of the document.
#' @param encoding The character encoding to use in the document. The default
#' encoding is \sQuote{UTF-8}. Available encodings are specified at
#' <http://xmlsoft.org/html/libxml-encoding.html#xmlCharEncoding>.
#' @return A `xml_document` object.
#' @export
# TODO: jimhester 2016-12-16 Deprecate this in the future?
xml_new_document <- function(version = "1.0", encoding = "UTF-8") {
doc <- .Call(doc_new, version, encoding)
out <- list(doc = doc)
class(out) <- "xml_document"
out
}
#' @param .version The version number of the document, passed to `xml_new_document(version)`.
#' @param .encoding The encoding of the document, passed to `xml_new_document(encoding)`.
#' @inheritParams xml_add_child
#' @rdname xml_new_document
#' @export
xml_new_root <- function(.value, ..., .copy = inherits(.value, "xml_node"), .version = "1.0", .encoding = "UTF-8") {
xml_add_child(xml_new_document(version = .version, encoding = .encoding), .value = .value, ... = ..., .copy = .copy)
}
#' Strip the default namespaces from a document
#'
#' @inheritParams xml_name
#' @examples
#' x <- read_xml(
#' "<foo xmlns = 'http://foo.com'>
#' <baz/>
#' <bar xmlns = 'http://bar.com'>
#' <baz/>
#' </bar>
#' </foo>"
#' )
#' # Need to specify the default namespaces to find the baz nodes
#' xml_find_all(x, "//d1:baz")
#' xml_find_all(x, "//d2:baz")
#'
#' # After stripping the default namespaces you can find both baz nodes directly
#' xml_ns_strip(x)
#' xml_find_all(x, "//baz")
#' @export
xml_ns_strip <- function(x) {
# //namespace::*[name()=''] finds all the namespace definition nodes with no
# prefix (default namespaces).
# What we actually want is the element node the definitions are contained in
# so return the parent (/parent::*)
namespace_element_nodes <- xml_find_all(x, "//namespace::*[name()='']/parent::*")
xml_attr(namespace_element_nodes, "xmlns") <- NULL
invisible(x)
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_modify.R |
#' The (tag) name of an xml element.
#'
#' @param x A document, node, or node set.
#' @param ns Optionally, a named vector giving prefix-url pairs, as produced
#' by [xml_ns()]. If provided, all names will be explicitly
#' qualified with the ns prefix, i.e. if the element `bar` is defined
#' in namespace `foo`, it will be called `foo:bar`. (And
#' similarly for attributes). Default namespaces must be given an explicit
#' name. The ns is ignored when using [xml_name<-()] and
#' [xml_set_name()].
#' @return A character vector.
#' @export
#' @examples
#' x <- read_xml("<bar>123</bar>")
#' xml_name(x)
#'
#' y <- read_xml("<bar><baz>1</baz>abc<foo /></bar>")
#' z <- xml_children(y)
#' xml_name(xml_children(y))
xml_name <- function(x, ns = character()) {
.Call(node_name, x, ns)
}
#' Modify the (tag) name of an element
#'
#' @param value a character vector with replacement name.
#' @rdname xml_name
#' @export
`xml_name<-` <- function(x, ns = character(), value) {
UseMethod("xml_name<-")
}
#' @export
`xml_name<-.xml_node` <- function(x, ns = character(), value) {
.Call(node_set_name, x$node, value)
x
}
#' @export
`xml_name<-.xml_nodeset` <- function(x, ns = character(), value) {
if (length(x) == 0) {
return(x)
}
if (!is.list(ns)) {
ns <- list(ns)
}
Map(`xml_name<-`, x, ns, value)
x
}
#' @export
`xml_name<-.xml_missing` <- function(x, ns = character(), value) {
x
}
set_name <- function(x, value, ns = character()) {
xml_name(x = x, ns = ns) <- value
x
}
#' @rdname xml_name
#' @export
xml_set_name <- function(x, value, ns = character()) {
UseMethod("xml_set_name")
}
#' @export
xml_set_name.xml_node <- set_name
#' @export
xml_set_name.xml_nodeset <- set_name
#' @export
xml_set_name.xml_missing <- set_name
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_name.R |
#' XML namespaces.
#'
#' `xml_ns` extracts all namespaces from a document, matching each
#' unique namespace url with the prefix it was first associated with. Default
#' namespaces are named `d1`, `d2` etc. Use `xml_ns_rename`
#' to change the prefixes. Once you have a namespace object, you can pass it to
#' other functions to work with fully qualified names instead of local names.
#'
#' @export
#' @inheritParams xml_name
#' @param old,... An existing xml_namespace object followed by name-value
#' (old prefix-new prefix) pairs to replace.
#' @return A character vector with class `xml_namespace` so the
#' default display is a little nicer.
#' @examples
#' x <- read_xml('
#' <root>
#' <doc1 xmlns = "http://foo.com"><baz /></doc1>
#' <doc2 xmlns = "http://bar.com"><baz /></doc2>
#' </root>
#' ')
#' xml_ns(x)
#'
#' # When there are default namespaces, it's a good idea to rename
#' # them to give informative names:
#' ns <- xml_ns_rename(xml_ns(x), d1 = "foo", d2 = "bar")
#' ns
#'
#' # Now we can pass ns to other xml function to use fully qualified names
#' baz <- xml_children(xml_children(x))
#' xml_name(baz)
#' xml_name(baz, ns)
#'
#' xml_find_all(x, "//baz")
#' xml_find_all(x, "//foo:baz", ns)
#'
#' str(as_list(x))
#' str(as_list(x, ns))
xml_ns <- function(x) {
UseMethod("xml_ns")
}
#' @export
xml_ns.xml_document <- function(x) {
if (length(x) == 0) {
return(character())
}
stopifnot(inherits(x, "xml_document"))
doc <- x$doc
x <- .Call(doc_namespaces, doc)
# Number default namespaces
is_default <- names(x) == ""
names(x)[is_default] <- paste0("d", seq_len(sum(is_default)))
# Make prefixes unique
names(x) <- make.unique(names(x), "")
class(x) <- "xml_namespace"
x
}
#' @export
xml_ns.xml_node <- function(x) {
xml_ns(xml_root(x))
}
#' @export
xml_ns.xml_nodeset <- function(x) {
if (length(x) == 0) {
return(character())
}
xml_ns(x[[1]])
}
#' @export
xml_ns.xml_missing <- function(x) {
character()
}
#' @export
print.xml_namespace <- function(x, ...) {
prefix <- format(names(x))
cat(paste0(prefix, " <-> ", x, collapse = "\n"), "\n", sep = "")
}
#' @export
#' @rdname xml_ns
xml_ns_rename <- function(old, ...) {
new <- c(...)
m <- match(names(new), names(old))
if (any(is.na(m))) {
missing <- paste(names(new)[is.na(m)], collapse = ", ")
cli::cli_abort("Some prefixes [{missing}] don't already exist.")
}
names(old)[m] <- new
old
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_namespaces.R |
# node -------------------------------------------------------------------------
xml_node <- function(node = NULL, doc = NULL) {
if (inherits(node, "xml_node")) {
node
} else {
out <- list(node = node, doc = doc)
class(out) <- "xml_node"
out
}
}
#' @export
as.character.xml_node <- function(x, ..., options = "format", encoding = "UTF-8") {
options <- parse_options(options, xml_save_options())
.Call(node_write_character, x$node, encoding, options)
}
#' @export
print.xml_node <- function(x, width = getOption("width"), max_n = 20, ...) {
cat("{", doc_type(x), "_node}\n", sep = "")
cat(format(x), "\n", sep = "")
show_nodes(xml_children(x), width = width, max_n = max_n)
}
#' @export
is.na.xml_node <- function(x) {
FALSE
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_node.R |
xml_nodeset <- function(nodes = list(), deduplicate = TRUE) {
if (isTRUE(deduplicate)) {
nodes <- nodes[!.Call(nodes_duplicated, nodes)]
}
class(nodes) <- "xml_nodeset"
nodes
}
#' @param nodes A list (possible nested) of external pointers to nodes
#' @return a nodeset
#' @noRd
make_nodeset <- function(nodes, doc) {
nodes <- unlist(nodes, recursive = FALSE)
xml_nodeset(lapply(nodes, xml_node, doc = doc))
}
#' @export
print.xml_nodeset <- function(x, width = getOption("width"), max_n = 20, ...) {
n <- length(x)
cat("{", doc_type(x), "_nodeset (", n, ")}\n", sep = "")
if (n > 0) {
show_nodes(x, width = width, max_n = max_n)
}
}
#' @export
as.character.xml_nodeset <- function(x, ...) {
vapply(x, as.character, FUN.VALUE = character(1))
}
#' @export
`[.xml_nodeset` <- function(x, i, ...) {
if (length(x) == 0) {
return(x)
}
xml_nodeset(NextMethod())
}
#' Wrapper for encodeString() that takes width into consideration
#'
#' encodeString() is relatively expensive to run (see #366), so
#' avoid doing so to very wide inputs by first trimming inputs
#' to approximately the correct width, then encoding. A second
#' round of truncation occurs after encoding to account for
#' any newly-inserted characters bumping an input too wide.
#' @noRd
encode_with_width <- function(x, width) {
truncate_raw <- nchar(x) > width
x[truncate_raw] <- substr(x[truncate_raw], 1L, width - 3L)
x <- encodeString(x)
truncate_encoded <- truncate_raw | nchar(x) > width
x[truncate_encoded] <- paste(substr(x[truncate_encoded], 1L, width - 3L), "...")
x
}
show_nodes <- function(x, width = getOption("width"), max_n = 20) {
stopifnot(inherits(x, "xml_nodeset"))
n <- length(x)
if (n == 0) {
return()
}
trunc <- n > max_n
if (trunc) {
n <- max_n
x <- x[seq_len(n)]
}
label <- format(paste0("[", seq_len(n), "]"), justify = "right")
contents <- vapply(x, as.character, FUN.VALUE = character(1L))
desc <- encode_with_width(paste(label, contents), width)
cat(desc, sep = "\n")
if (trunc) {
cat("...\n")
}
invisible()
}
#' @export
is.na.xml_nodeset <- function(x) {
vapply(x, is.na, logical(1))
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_nodeset.R |
#' Read HTML or XML.
#'
#' @section Setting the "user agent" header:
#'
#' When performing web scraping tasks it is both good practice --- and often required ---
#' to set the [user agent](https://en.wikipedia.org/wiki/User_agent) request header
#' to a specific value. Sometimes this value is assigned to emulate a browser in order
#' to have content render in a certain way (e.g. `Mozilla/5.0 (Windows NT 5.1; rv:52.0)
#' Gecko/20100101 Firefox/52.0` to emulate more recent Windows browsers). Most often,
#' this value should be set to provide the web resource owner information on who you are
#' and the intent of your actions like this Google scraping bot user agent identifier:
#' `Googlebot/2.1 (+http://www.google.com/bot.html)`.
#'
#' You can set the HTTP user agent for URL-based requests using [httr::set_config()] and [httr::user_agent()]:
#'
#' `httr::set_config(httr::user_agent("me@@example.com; +https://example.com/info.html"))`
#'
#' [httr::set_config()] changes the configuration globally,
#' [httr::with_config()] can be used to change configuration temporarily.
#'
#' @param x A string, a connection, or a raw vector.
#'
#' A string can be either a path, a url or literal xml. Urls will
#' be converted into connections either using `base::url` or, if
#' installed, `curl::curl`. Local paths ending in `.gz`,
#' `.bz2`, `.xz`, `.zip` will be automatically uncompressed.
#'
#' If a connection, the complete connection is read into a raw vector before
#' being parsed.
#' @param encoding Specify a default encoding for the document. Unless
#' otherwise specified XML documents are assumed to be in UTF-8 or
#' UTF-16. If the document is not UTF-8/16, and lacks an explicit
#' encoding directive, this allows you to supply a default.
#' @param ... Additional arguments passed on to methods.
#' @param as_html Optionally parse an xml file as if it's html.
#' @param base_url When loading from a connection, raw vector or literal
#' html/xml, this allows you to specify a base url for the document. Base
#' urls are used to turn relative urls into absolute urls.
#' @param n If `file` is a connection, the number of bytes to read per
#' iteration. Defaults to 64kb.
#' @param verbose When reading from a slow connection, this prints some
#' output on every iteration so you know its working.
#' @param options Set parsing options for the libxml2 parser. Zero or more of
#' \Sexpr[results=rd]{xml2:::describe_options(xml2:::xml_parse_options())}
#' @return An XML document. HTML is normalised to valid XML - this may not
#' be exactly the same transformation performed by the browser, but it's
#' a reasonable approximation.
#' @export
#' @examples
#' # Literal xml/html is useful for small examples
#' read_xml("<foo><bar /></foo>")
#' read_html("<html><title>Hi<title></html>")
#' read_html("<html><title>Hi")
#'
#' # From a local path
#' read_html(system.file("extdata", "r-project.html", package = "xml2"))
#'
#' \dontrun{
#' # From a url
#' cd <- read_xml(xml2_example("cd_catalog.xml"))
#' me <- read_html("http://had.co.nz")
#' }
read_xml <- function(x, encoding = "", ..., as_html = FALSE, options = "NOBLANKS") {
UseMethod("read_xml")
}
#' @export
#' @rdname read_xml
read_html <- function(x,
encoding = "",
...,
options = c("RECOVER", "NOERROR", "NOBLANKS")) {
UseMethod("read_html")
}
#' @export
read_html.default <- function(x,
encoding = "",
...,
options = c("RECOVER", "NOERROR", "NOBLANKS")) {
options <- parse_options(options, xml_parse_options())
suppressWarnings(read_xml(x, encoding = encoding, ..., as_html = TRUE, options = options))
}
#' @export
read_html.response <- function(x,
encoding = "",
options = c("RECOVER", "NOERROR", "NOBLANKS"),
...) {
check_installed("httr")
options <- parse_options(options, xml_parse_options())
httr::stop_for_status(x)
content <- httr::content(x, as = "raw")
xml2::read_html(content, encoding = encoding, options = options, ...)
}
#' @export
#' @rdname read_xml
read_xml.character <- function(x,
encoding = "",
...,
as_html = FALSE,
options = "NOBLANKS") {
check_string(x)
options <- parse_options(options, xml_parse_options())
if (grepl("<|>", x)) {
read_xml.raw(charToRaw(enc2utf8(x)), "UTF-8", ..., as_html = as_html, options = options)
} else {
con <- path_to_connection(x)
if (inherits(con, "connection")) {
read_xml.connection(con,
encoding = encoding, ..., as_html = as_html,
base_url = x, options = options
)
} else {
doc <- .Call(doc_parse_file, con,
encoding = encoding, as_html = as_html,
options = options
)
xml_document(doc)
}
}
}
#' @export
#' @rdname read_xml
read_xml.raw <- function(x,
encoding = "",
base_url = "",
...,
as_html = FALSE,
options = "NOBLANKS") {
options <- parse_options(options, xml_parse_options())
doc <- .Call(doc_parse_raw, x, encoding, base_url, as_html, options)
xml_document(doc)
}
#' @export
#' @rdname read_xml
read_xml.connection <- function(x,
encoding = "",
n = 64 * 1024,
verbose = FALSE,
...,
base_url = "",
as_html = FALSE,
options = "NOBLANKS") {
options <- parse_options(options, xml_parse_options())
if (!isOpen(x)) {
open(x, "rb")
on.exit(close(x))
}
raw <- .Call(read_connection_, x, n)
read_xml.raw(raw,
encoding = encoding, base_url = base_url, as_html =
as_html, options = options
)
}
#' @export
read_xml.response <- function(x,
encoding = "",
base_url = "",
...,
as_html = FALSE,
options = "NOBLANKS") {
check_installed("httr")
options <- parse_options(options, xml_parse_options())
httr::stop_for_status(x)
content <- httr::content(x, as = "raw")
xml2::read_xml(content,
encoding = encoding, base_url = if (nzchar(base_url)) base_url else x$url,
as_html = as_html, option = options, ...
)
}
#' Download a HTML or XML file
#'
#' Libcurl implementation of `C_download` (the "internal" download method)
#' with added support for https, ftps, gzip, etc. Default behavior is identical
#' to [download.file()], but request can be fully configured by passing
#' a custom [curl::handle()].
#' @inherit curl::curl_download
#' @param file A character string with the name where the downloaded file is
#' saved.
#' @seealso [curl_download][curl::curl_download]
#' @export
#' @examples
#' \dontrun{
#' download_html("http://tidyverse.org/index.html")
#' }
download_xml <- function(url,
file = basename(url),
quiet = TRUE,
mode = "wb",
handle = curl::new_handle()) {
check_installed("curl", "to use `download_xml()`.")
curl::curl_download(url, file, quiet = quiet, mode = mode, handle = handle)
invisible(file)
}
#' @export
#' @rdname download_xml
download_html <- download_xml
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_parse.R |
#' Retrieve the xpath to a node
#'
#' This is useful when you want to figure out where nodes matching an
#' xpath expression live in a document.
#'
#' @inheritParams xml_name
#' @return A character vector.
#' @export
#' @examples
#' x <- read_xml("<foo><bar><baz /></bar><baz /></foo>")
#' xml_path(xml_find_all(x, ".//baz"))
xml_path <- function(x) {
.Call(node_path, x)
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_path.R |
#' Validate XML schema
#'
#' Validate an XML document against an XML 1.0 schema.
#'
#' @inheritParams xml_name
#' @return TRUE or FALSE
#' @export
#' @param schema an XML document containing the schema
#' @examples # Example from https://msdn.microsoft.com/en-us/library/ms256129(v=vs.110).aspx
#' doc <- read_xml(system.file("extdata/order-doc.xml", package = "xml2"))
#' schema <- read_xml(system.file("extdata/order-schema.xml", package = "xml2"))
#' xml_validate(doc, schema)
xml_validate <- function(x, schema) {
UseMethod("xml_validate")
}
#' @export
xml_validate.xml_document <- function(x, schema) {
stopifnot(inherits(schema, "xml_document"))
.Call(doc_validate, x$doc, schema$doc)
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_schema.R |
#' Serializing XML objects to connections.
#'
#' @inheritParams base::serialize
#' @param ... Additional arguments passed to [read_xml()].
#' @inherit base::serialize return
#' @examples
#' library(xml2)
#' x <- read_xml("<a>
#' <b><c>123</c></b>
#' <b><c>456</c></b>
#' </a>")
#'
#' b <- xml_find_all(x, "//b")
#' out <- xml_serialize(b, NULL)
#' xml_unserialize(out)
#' @export
xml_serialize <- function(object, connection, ...) UseMethod("xml_serialize")
#' @export
xml_serialize.xml_document <- function(object, connection, ...) {
if (is.character(connection)) {
connection <- file(connection, "w", raw = TRUE)
on.exit(close(connection))
}
serialize(structure(as.character(object, ...), doc_type = doc_type(object), class = "xml_serialized_document"), connection)
}
#' @export
xml_serialize.xml_node <- function(object, connection, ...) {
if (is.character(connection)) {
connection <- file(connection, "w", raw = TRUE)
on.exit(close(connection))
}
x <- as_xml_document(object)
serialize(structure(as.character(x, ...), class = "xml_serialized_node"), connection)
}
#' @export
xml_serialize.xml_nodeset <- function(object, connection, ...) {
if (is.character(connection)) {
connection <- file(connection, "w", raw = TRUE)
on.exit(close(connection))
}
x <- as_xml_document(object, "root")
serialize(structure(as.character(x, ...), class = "xml_serialized_nodeset"), connection)
}
#' @rdname xml_serialize
#' @export
xml_unserialize <- function(connection, ...) {
if (is.character(connection)) {
connection <- file(connection, "r", raw = TRUE)
on.exit(close(connection))
}
object <- unserialize(connection)
if (inherits(object, "xml_serialized_nodeset")) {
x <- read_xml(unclass(object), ...)
# Select only the direct children of the root
res <- xml_find_all(x, "/*/node()")
} else if (inherits(object, "xml_serialized_node")) {
x <- read_xml(unclass(object), ...)
# Select only the root
res <- xml_find_first(x, "/node()")
} else if (inherits(object, "xml_serialized_document")) {
read_xml_int <- function(object, as_html = FALSE, ...) {
if (missing(as_html)) {
as_html <- identical(attr(object, "doc_type", exact = TRUE), "html")
}
read_xml(unclass(object), as_html = as_html, ...)
}
res <- read_xml_int(unclass(object), ...)
} else {
abort("Not a serialized xml2 object")
}
res
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_serialize.R |
#' Show the structure of an html/xml document.
#'
#' Show the structure of an html/xml document without displaying any of
#' the values. This is useful if you want to get a high level view of the
#' way a document is organised. Compared to `xml_structure`,
#' `html_structure` prints the id and class attributes.
#'
#' @param x HTML/XML document (or part there of)
#' @param indent Number of spaces to ident
#' @inheritParams base::cat
#' @export
#' @examples
#' xml_structure(read_xml("<a><b><c/><c/></b><d/></a>"))
#'
#' rproj <- read_html(system.file("extdata", "r-project.html", package = "xml2"))
#' xml_structure(rproj)
#' xml_structure(xml_find_all(rproj, ".//p"))
#'
#' h <- read_html("<body><p id = 'a'></p><p class = 'c d'></p></body>")
#' html_structure(h)
xml_structure <- function(x, indent = 2, file = "") {
cat(file = file)
tree_structure(x, indent = indent, html = FALSE, file = file)
}
#' @export
#' @rdname xml_structure
html_structure <- function(x, indent = 2, file = "") {
cat(file = file)
tree_structure(x, indent = indent, html = TRUE, file = file)
}
tree_structure <- function(x, indent = 2, html = FALSE, file = "") {
UseMethod("tree_structure")
}
#' @export
tree_structure.xml_missing <- function(x, indent = 2, html = FALSE, file = "") {
NA_character_
}
#' @export
tree_structure.xml_nodeset <- function(x, indent = 2, html = FALSE, file = "") {
for (i in seq_along(x)) {
cat("[[", i, "]]\n", sep = "", file = file, append = TRUE)
print_xml_structure(x[[i]], indent = indent, html = html, file = file)
cat("\n", file = file, append = TRUE)
}
invisible()
}
#' @export
tree_structure.xml_node <- function(x, indent = 2, html = FALSE, file = "") {
print_xml_structure(x, indent = indent, html = html, file = file)
invisible()
}
print_xml_structure <- function(x, prefix = 0, indent = 2, html = FALSE, file = "") {
padding <- paste(rep(" ", prefix), collapse = "")
type <- xml_type(x)
if (type == "element") {
attr <- xml_attrs(x)
if (html) {
html_attrs <- list()
if ("id" %in% names(attr)) {
html_attrs$id <- paste0("#", attr[["id"]])
attr <- attr[setdiff(names(attr), "id")]
}
if ("class" %in% names(attr)) {
html_attrs$class <- paste0(".", gsub(" ", ".", attr[["class"]]))
attr <- attr[setdiff(names(attr), "class")]
}
attr_str <- paste(unlist(html_attrs), collapse = " ")
} else {
attr_str <- ""
}
if (length(attr) > 0) {
attr_str <- paste0(attr_str, " [", paste0(names(attr), collapse = ", "), "]")
}
node <- paste0("<", xml_name(x), attr_str, ">")
cat(padding, node, "\n", sep = "", file = file, append = TRUE)
lapply(
xml_contents(x),
print_xml_structure,
prefix = prefix + indent,
indent = indent,
html = html,
file = file
)
} else {
cat(padding, "{", type, "}\n", sep = "", file = file, append = TRUE)
}
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_structure.R |
#' Extract or modify the text
#'
#' `xml_text` returns a character vector, `xml_double` returns a
#' numeric vector, `xml_integer` returns an integer vector.
#' @inheritParams xml_name
#' @param trim If `TRUE` will trim leading and trailing spaces.
#' @return A character vector, the same length as x.
#' @examples
#' x <- read_xml("<p>This is some text. This is <b>bold!</b></p>")
#' xml_text(x)
#' xml_text(xml_children(x))
#'
#' x <- read_xml("<x>This is some text. <x>This is some nested text.</x></x>")
#' xml_text(x)
#' xml_text(xml_find_all(x, "//x"))
#'
#' x <- read_xml("<p> Some text </p>")
#' xml_text(x, trim = TRUE)
#'
#' # xml_double() and xml_integer() are useful for extracting numeric attributes
#' x <- read_xml("<plot><point x='1' y='2' /><point x='2' y='1' /></plot>")
#' xml_integer(xml_find_all(x, "//@x"))
#' @export
xml_text <- function(x, trim = FALSE) {
res <- .Call(node_text, x)
if (isTRUE(trim)) {
res <- trim_text(res)
}
res
}
trim_text <- function(x) {
x <- sub("^[[:space:]\u00a0]+", "", x)
sub("[[:space:]\u00a0]+$", "", x)
}
#' @rdname xml_text
#' @param value character vector with replacement text.
#' @export
`xml_text<-` <- function(x, value) {
UseMethod("xml_text<-")
}
#' @export
`xml_text<-.xml_nodeset` <- function(x, value) {
if (length(x) == 0) {
return(x)
}
# We need to do the modification in reverse order as the modification can
# potentially delete nodes
Map(`xml_text<-`, rev(x), rev(value))
# what to return here, setting the text could invalidate some nodes in
# the nodeset having pointers to free'd memory.
x
}
#' @export
`xml_text<-.xml_node` <- function(x, value) {
if (xml_type(x) != "text") {
text_child <- xml_find_first(x, ".//text()[1]", ns = character())
if (inherits(text_child, "xml_missing")) {
.Call(node_append_content, x$node, value)
} else {
.Call(node_set_content, text_child$node, value)
}
} else {
.Call(node_set_content, x$node, value)
}
x
}
#' @export
`xml_text<-.xml_missing` <- function(x, value) {
NA_character_
}
#' @export
#' @rdname xml_text
`xml_set_text` <- `xml_text<-`
#' @rdname xml_text
#' @export
xml_double <- function(x) {
as.numeric(xml_text(x))
}
#' @rdname xml_text
#' @export
xml_integer <- function(x) {
as.integer(xml_text(x))
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_text.R |
#' Determine the type of a node.
#'
#' @inheritParams xml_name
#' @export
#' @examples
#' x <- read_xml("<foo> a <b /> <![CDATA[ blah]]></foo>")
#' xml_type(x)
#' xml_type(xml_contents(x))
xml_type <- function(x) {
types <- .Call(node_type, x)
xmlElementType[types]
}
xmlElementType <- c(
"element",
"attribute",
"text",
"cdata",
"entity_ref",
"entity",
"pi",
"comment",
"document",
"document_type",
"document_frag",
"notation",
"html_document",
"dtd",
"element_decl",
"attribute_decl",
"entity_decl",
"namespace_decl",
"xinclude_start",
"xinclude_end",
"docb_document"
)
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_type.R |
#' The URL of an XML document
#'
#' This is useful for interpreting relative urls with [url_relative()].
#'
#' @param x A node or document.
#' @return A character vector of length 1. Returns `NA` if the name is
#' not set.
#' @export
#' @examples
#' catalog <- read_xml(xml2_example("cd_catalog.xml"))
#' xml_url(catalog)
#'
#' x <- read_xml("<foo/>")
#' xml_url(x)
xml_url <- function(x) {
UseMethod("xml_url")
}
#' @export
xml_url.xml_missing <- function(x) {
NA_character_
}
#' @export
xml_url.xml_node <- function(x) {
.Call(doc_url, x$doc)
}
#' @export
xml_url.xml_nodeset <- function(x) {
vapply(x, function(x) .Call(doc_url, x), character(1))
}
#' Convert between relative and absolute urls.
#'
#' @param x A character vector of urls relative to that base
#' @param base A string giving a base url.
#' @return A character vector of urls
#' @seealso \code{\link{xml_url}} to retrieve the URL associated with a document
#' @export
#' @examples
#' url_absolute(c(".", "..", "/", "/x"), "http://hadley.nz/a/b/c/d")
#'
#' url_relative("http://hadley.nz/a/c", "http://hadley.nz")
#' url_relative("http://hadley.nz/a/c", "http://hadley.nz/")
#' url_relative("http://hadley.nz/a/c", "http://hadley.nz/a/b")
#' url_relative("http://hadley.nz/a/c", "http://hadley.nz/a/b/")
#' @export
url_absolute <- function(x, base) {
.Call(url_absolute_, x, base)
}
#' @rdname url_absolute
#' @export
url_relative <- function(x, base) {
.Call(url_relative_, x, base)
}
#' Escape and unescape urls.
#'
#' @param x A character vector of urls.
#' @param reserved A string containing additional characters to avoid escaping.
#' @export
#' @examples
#' url_escape("a b c")
#' url_escape("a b c", "")
#'
#' url_unescape("a%20b%2fc")
#' url_unescape("%C2%B5")
url_escape <- function(x, reserved = "") {
.Call(url_escape_, x, reserved)
}
#' @rdname url_escape
#' @export
url_unescape <- function(x) {
.Call(url_unescape_, x)
}
#' Parse a url into its component pieces.
#'
#' @param x A character vector of urls.
#' @return A dataframe with one row for each element of \code{x} and
#' columns: scheme, server, port, user, path, query, fragment.
#' @export
#' @examples
#' url_parse("http://had.co.nz/")
#' url_parse("http://had.co.nz:1234/")
#' url_parse("http://had.co.nz:1234/?a=1&b=2")
#' url_parse("http://had.co.nz:1234/?a=1&b=2#def")
url_parse <- function(x) {
.Call(url_parse_, x)
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_url.R |
#' Write XML or HTML to disk.
#'
#' This writes out both XML and normalised HTML. The default behavior will
#' output the same format which was read. If you want to force output pass
#' `option = "as_xml"` or `option = "as_html"` respectively.
#'
#' @param x A document or node to write to disk. It's not possible to
#' save nodesets containing more than one node.
#' @param file Path to file or connection to write to.
#' @param encoding The character encoding to use in the document. The default
#' encoding is \sQuote{UTF-8}. Available encodings are specified at
#' <http://xmlsoft.org/html/libxml-encoding.html#xmlCharEncoding>.
#' @param options default: \sQuote{format}. Zero or more of
#' \Sexpr[results=rd]{xml2:::describe_options(xml2:::xml_save_options())}
#' @param ... additional arguments passed to methods.
#' @export
#' @examples
#' h <- read_html("<p>Hi!</p>")
#'
#' tmp <- tempfile(fileext = ".xml")
#' write_xml(h, tmp, options = "format")
#' readLines(tmp)
#'
#' # write formatted HTML output
#' write_html(h, tmp, options = "format")
#' readLines(tmp)
write_xml <- function(x, file, ...) {
UseMethod("write_xml")
}
#' @export
write_xml.xml_missing <- function(x, file, ...) {
abort("Missing data cannot be written")
}
#' @rdname write_xml
#' @export
write_xml.xml_document <- function(x, file, ..., options = "format", encoding = "UTF-8") {
options <- parse_options(options, xml_save_options())
file <- path_to_connection(file, check = "dir")
if (inherits(file, "connection")) {
if (!isOpen(file)) {
open(file, "wb")
on.exit(close(file))
}
.Call(doc_write_connection, x$doc, file, encoding, options)
} else {
check_string(file)
.Call(doc_write_file, x$doc, file, encoding, options)
}
invisible()
}
#' @export
write_xml.xml_nodeset <- function(x, file, ..., options = "format", encoding = "UTF-8") {
if (length(x) != 1) {
abort("Can only save length 1 node sets")
}
options <- parse_options(options, xml_save_options())
file <- path_to_connection(file, check = "dir")
if (inherits(file, "connection")) {
if (!isOpen(file)) {
open(file, "wb")
on.exit(close(file))
}
.Call(node_write_connection, x[[1]]$node, file, encoding, options)
} else {
check_string(file)
.Call(node_write_file, x[[1]]$node, file, encoding, options)
}
invisible()
}
#' @export
write_xml.xml_node <- function(x, file, ..., options = "format", encoding = "UTF-8") {
options <- parse_options(options, xml_save_options())
file <- path_to_connection(file, check = "dir")
if (inherits(file, "connection")) {
if (!isOpen(file)) {
open(file, "wb")
on.exit(close(file))
}
.Call(node_write_connection, x$node, file, encoding, options)
} else {
check_string(file)
.Call(node_write_file, x$node, file, encoding, options)
}
invisible()
}
#' @export
#' @rdname write_xml
write_html <- function(x, file, ...) {
UseMethod("write_html")
}
#' @export
write_html.xml_missing <- function(x, file, ...) {
abort("Missing data cannot be written")
}
#' @rdname write_xml
#' @export
write_html.xml_document <- write_xml.xml_document
#' @export
write_html.xml_nodeset <- write_xml.xml_nodeset
#' @export
write_html.xml_node <- write_xml.xml_node
| /scratch/gouwar.j/cran-all/cranData/xml2/R/xml_write.R |
.onUnload <- function(libpath) {
gc() # trigger finalisers
library.dynam.unload("xml2", libpath)
}
| /scratch/gouwar.j/cran-all/cranData/xml2/R/zzz.R |
## ----echo = FALSE, message = FALSE--------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(xml2)
library(magrittr)
## -----------------------------------------------------------------------------
x <- read_xml("<p>This is some <b>text</b>. This is more.</p>")
xml_text(x)
xml_text(x) <- "This is some other text."
xml_text(x)
# You can avoid this by explicitly selecting the text node.
x <- read_xml("<p>This is some text. This is <b>bold!</b></p>")
text_only <- xml_find_all(x, "//text()")
xml_text(text_only) <- c("This is some other text. ", "Still bold!")
xml_text(x)
xml_structure(x)
## -----------------------------------------------------------------------------
x <- read_xml("<a href='invalid!'>xml2</a>")
xml_attr(x, "href")
xml_attr(x, "href") <- "https://github.com/r-lib/xml2"
xml_attr(x, "href")
xml_attrs(x) <- c(id = "xml2", href = "https://github.com/r-lib/xml2")
xml_attrs(x)
x
xml_attrs(x) <- NULL
x
# Namespaces are added with as a xmlns or xmlns:prefix attribute
xml_attr(x, "xmlns") <- "http://foo"
x
xml_attr(x, "xmlns:bar") <- "http://bar"
x
## -----------------------------------------------------------------------------
x <- read_xml("<a><b/></a>")
x
xml_name(x)
xml_name(x) <- "c"
x
## -----------------------------------------------------------------------------
x <- read_xml("<parent><child>1</child><child>2<child>3</child></child></parent>")
children <- xml_children(x)
t1 <- children[[1]]
t2 <- children[[2]]
t3 <- xml_children(children[[2]])[[1]]
xml_replace(t1, t3)
x
## -----------------------------------------------------------------------------
x <- read_xml("<parent><child>1</child><child>2<child>3</child></child></parent>")
children <- xml_children(x)
t1 <- children[[1]]
t2 <- children[[2]]
t3 <- xml_children(children[[2]])[[1]]
xml_add_sibling(t1, t3)
x
xml_add_sibling(t3, t1, where = "before")
x
## -----------------------------------------------------------------------------
x <- read_xml("<parent><child>1</child><child>2<child>3</child></child></parent>")
children <- xml_children(x)
t1 <- children[[1]]
t2 <- children[[2]]
t3 <- xml_children(children[[2]])[[1]]
xml_add_child(t1, t3)
x
xml_add_child(t1, read_xml("<test/>"))
x
## -----------------------------------------------------------------------------
x <- read_xml("<foo><bar><baz/></bar></foo>")
x1 <- x %>%
xml_children() %>%
.[[1]]
x2 <- x1 %>%
xml_children() %>%
.[[1]]
xml_remove(x1)
rm(x1)
gc()
x2
## -----------------------------------------------------------------------------
x <- read_xml("<a><b /><b><b /></b></a>")
bees <- xml_find_all(x, "//b")
xml_remove(xml_child(x), free = TRUE)
# bees[[1]] is no longer valid!!!
rm(bees)
gc()
## -----------------------------------------------------------------------------
d <- xml_new_root("sld",
"xmlns" = "http://www.opengis.net/sld",
"xmlns:ogc" = "http://www.opengis.net/ogc",
"xmlns:se" = "http://www.opengis.net//se",
version = "1.1.0"
) %>%
xml_add_child("layer") %>%
xml_add_child("se:Name", "My Layer") %>%
xml_root()
d
| /scratch/gouwar.j/cran-all/cranData/xml2/inst/doc/modification.R |
---
title: "Node Modification"
author: "Jim Hester"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Node Modification}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, echo = FALSE, message = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(xml2)
library(magrittr)
```
# Modifying Existing XML
Modifying existing XML can be done in xml2 by using the replacement functions
of the accessors. They all have methods for both individual `xml_node` objects
as well as `xml_nodeset` objects. If a vector of values is provided it is
applied piecewise over the nodeset, otherwise the value is recycled.
## Text Modification ##
Text modification only happens on text nodes. If a given node has more than one
text node only the first will be affected. If you want to modify additional
text nodes you need to select them explicitly with `/text()`.
```{r}
x <- read_xml("<p>This is some <b>text</b>. This is more.</p>")
xml_text(x)
xml_text(x) <- "This is some other text."
xml_text(x)
# You can avoid this by explicitly selecting the text node.
x <- read_xml("<p>This is some text. This is <b>bold!</b></p>")
text_only <- xml_find_all(x, "//text()")
xml_text(text_only) <- c("This is some other text. ", "Still bold!")
xml_text(x)
xml_structure(x)
```
## Attribute and Namespace Definition Modification ##
Attributes and namespace definitions are modified one at a time with
`xml_attr()` or all at once with `xml_attrs()`. In both cases using `NULL` as
the value will remove the attribute completely.
```{r}
x <- read_xml("<a href='invalid!'>xml2</a>")
xml_attr(x, "href")
xml_attr(x, "href") <- "https://github.com/r-lib/xml2"
xml_attr(x, "href")
xml_attrs(x) <- c(id = "xml2", href = "https://github.com/r-lib/xml2")
xml_attrs(x)
x
xml_attrs(x) <- NULL
x
# Namespaces are added with as a xmlns or xmlns:prefix attribute
xml_attr(x, "xmlns") <- "http://foo"
x
xml_attr(x, "xmlns:bar") <- "http://bar"
x
```
## Name Modification ##
Node names are modified with `xml_name()`.
```{r}
x <- read_xml("<a><b/></a>")
x
xml_name(x)
xml_name(x) <- "c"
x
```
# Node modification #
All of these functions have a `.copy` argument. If this is set to `FALSE` they
will remove the new node from its location before inserting it into the new
location. Otherwise they make a copy of the node before insertion.
## Replacing existing nodes ##
```{r}
x <- read_xml("<parent><child>1</child><child>2<child>3</child></child></parent>")
children <- xml_children(x)
t1 <- children[[1]]
t2 <- children[[2]]
t3 <- xml_children(children[[2]])[[1]]
xml_replace(t1, t3)
x
```
## Add a sibling ##
```{r}
x <- read_xml("<parent><child>1</child><child>2<child>3</child></child></parent>")
children <- xml_children(x)
t1 <- children[[1]]
t2 <- children[[2]]
t3 <- xml_children(children[[2]])[[1]]
xml_add_sibling(t1, t3)
x
xml_add_sibling(t3, t1, where = "before")
x
```
## Add a child ##
```{r}
x <- read_xml("<parent><child>1</child><child>2<child>3</child></child></parent>")
children <- xml_children(x)
t1 <- children[[1]]
t2 <- children[[2]]
t3 <- xml_children(children[[2]])[[1]]
xml_add_child(t1, t3)
x
xml_add_child(t1, read_xml("<test/>"))
x
```
## Removing nodes ##
The `xml_remove()` can be used to remove a node (and its children) from a
tree. The default behavior is to unlink the node from the tree, but does _not_
free the memory for the node, so R objects pointing to the node are still
valid.
This allows code like the following to work without crashing R
```{r}
x <- read_xml("<foo><bar><baz/></bar></foo>")
x1 <- x %>%
xml_children() %>%
.[[1]]
x2 <- x1 %>%
xml_children() %>%
.[[1]]
xml_remove(x1)
rm(x1)
gc()
x2
```
If you are not planning on referencing these nodes again this memory is wasted.
Calling `xml_remove(free = TRUE)` will remove the nodes _and_ free the memory
used to store them. **Note** In this case _any_ node which previously pointed
to the node or its children will instead be pointing to free memory and may
cause R to crash. xml2 can't figure this out for you, so it's your
responsibility to remove any objects which are no longer valid.
In particular `xml_find_*()` results are easy to overlook, for example
```{r}
x <- read_xml("<a><b /><b><b /></b></a>")
bees <- xml_find_all(x, "//b")
xml_remove(xml_child(x), free = TRUE)
# bees[[1]] is no longer valid!!!
rm(bees)
gc()
```
## Namespaces ##
We want to construct a document with the following namespace layout. (From
<https://stackoverflow.com/questions/32939229/creating-xml-in-r-with-namespaces/32941524#32941524>).
```xml
<?xml version = "1.0" encoding="UTF-8"?>
<sld xmlns="http://www.opengis.net/sld"
xmlns:ogc="http://www.opengis.net/ogc"
xmlns:se="http://www.opengis.net/se"
version="1.1.0" >
<layer>
<se:Name>My Layer</se:Name>
</layer>
</sld>
```
```{r}
d <- xml_new_root("sld",
"xmlns" = "http://www.opengis.net/sld",
"xmlns:ogc" = "http://www.opengis.net/ogc",
"xmlns:se" = "http://www.opengis.net//se",
version = "1.1.0"
) %>%
xml_add_child("layer") %>%
xml_add_child("se:Name", "My Layer") %>%
xml_root()
d
```
| /scratch/gouwar.j/cran-all/cranData/xml2/inst/doc/modification.Rmd |
# Build against static libraries from rwinlib
VERSION <- commandArgs(TRUE)
if(!file.exists(sprintf("../windows/libxml2-%s/include/libxml2/libxml/parser.h", VERSION))){
if(getRversion() < "3.3.0") setInternet2()
download.file(sprintf("https://github.com/rwinlib/libxml2/archive/v%s.zip", VERSION), "lib.zip", quiet = TRUE)
dir.create("../windows", showWarnings = FALSE)
unzip("lib.zip", exdir = "../windows")
unlink("lib.zip")
}
| /scratch/gouwar.j/cran-all/cranData/xml2/tools/winlibs.R |
---
title: "Node Modification"
author: "Jim Hester"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Node Modification}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, echo = FALSE, message = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(xml2)
library(magrittr)
```
# Modifying Existing XML
Modifying existing XML can be done in xml2 by using the replacement functions
of the accessors. They all have methods for both individual `xml_node` objects
as well as `xml_nodeset` objects. If a vector of values is provided it is
applied piecewise over the nodeset, otherwise the value is recycled.
## Text Modification ##
Text modification only happens on text nodes. If a given node has more than one
text node only the first will be affected. If you want to modify additional
text nodes you need to select them explicitly with `/text()`.
```{r}
x <- read_xml("<p>This is some <b>text</b>. This is more.</p>")
xml_text(x)
xml_text(x) <- "This is some other text."
xml_text(x)
# You can avoid this by explicitly selecting the text node.
x <- read_xml("<p>This is some text. This is <b>bold!</b></p>")
text_only <- xml_find_all(x, "//text()")
xml_text(text_only) <- c("This is some other text. ", "Still bold!")
xml_text(x)
xml_structure(x)
```
## Attribute and Namespace Definition Modification ##
Attributes and namespace definitions are modified one at a time with
`xml_attr()` or all at once with `xml_attrs()`. In both cases using `NULL` as
the value will remove the attribute completely.
```{r}
x <- read_xml("<a href='invalid!'>xml2</a>")
xml_attr(x, "href")
xml_attr(x, "href") <- "https://github.com/r-lib/xml2"
xml_attr(x, "href")
xml_attrs(x) <- c(id = "xml2", href = "https://github.com/r-lib/xml2")
xml_attrs(x)
x
xml_attrs(x) <- NULL
x
# Namespaces are added with as a xmlns or xmlns:prefix attribute
xml_attr(x, "xmlns") <- "http://foo"
x
xml_attr(x, "xmlns:bar") <- "http://bar"
x
```
## Name Modification ##
Node names are modified with `xml_name()`.
```{r}
x <- read_xml("<a><b/></a>")
x
xml_name(x)
xml_name(x) <- "c"
x
```
# Node modification #
All of these functions have a `.copy` argument. If this is set to `FALSE` they
will remove the new node from its location before inserting it into the new
location. Otherwise they make a copy of the node before insertion.
## Replacing existing nodes ##
```{r}
x <- read_xml("<parent><child>1</child><child>2<child>3</child></child></parent>")
children <- xml_children(x)
t1 <- children[[1]]
t2 <- children[[2]]
t3 <- xml_children(children[[2]])[[1]]
xml_replace(t1, t3)
x
```
## Add a sibling ##
```{r}
x <- read_xml("<parent><child>1</child><child>2<child>3</child></child></parent>")
children <- xml_children(x)
t1 <- children[[1]]
t2 <- children[[2]]
t3 <- xml_children(children[[2]])[[1]]
xml_add_sibling(t1, t3)
x
xml_add_sibling(t3, t1, where = "before")
x
```
## Add a child ##
```{r}
x <- read_xml("<parent><child>1</child><child>2<child>3</child></child></parent>")
children <- xml_children(x)
t1 <- children[[1]]
t2 <- children[[2]]
t3 <- xml_children(children[[2]])[[1]]
xml_add_child(t1, t3)
x
xml_add_child(t1, read_xml("<test/>"))
x
```
## Removing nodes ##
The `xml_remove()` can be used to remove a node (and its children) from a
tree. The default behavior is to unlink the node from the tree, but does _not_
free the memory for the node, so R objects pointing to the node are still
valid.
This allows code like the following to work without crashing R
```{r}
x <- read_xml("<foo><bar><baz/></bar></foo>")
x1 <- x %>%
xml_children() %>%
.[[1]]
x2 <- x1 %>%
xml_children() %>%
.[[1]]
xml_remove(x1)
rm(x1)
gc()
x2
```
If you are not planning on referencing these nodes again this memory is wasted.
Calling `xml_remove(free = TRUE)` will remove the nodes _and_ free the memory
used to store them. **Note** In this case _any_ node which previously pointed
to the node or its children will instead be pointing to free memory and may
cause R to crash. xml2 can't figure this out for you, so it's your
responsibility to remove any objects which are no longer valid.
In particular `xml_find_*()` results are easy to overlook, for example
```{r}
x <- read_xml("<a><b /><b><b /></b></a>")
bees <- xml_find_all(x, "//b")
xml_remove(xml_child(x), free = TRUE)
# bees[[1]] is no longer valid!!!
rm(bees)
gc()
```
## Namespaces ##
We want to construct a document with the following namespace layout. (From
<https://stackoverflow.com/questions/32939229/creating-xml-in-r-with-namespaces/32941524#32941524>).
```xml
<?xml version = "1.0" encoding="UTF-8"?>
<sld xmlns="http://www.opengis.net/sld"
xmlns:ogc="http://www.opengis.net/ogc"
xmlns:se="http://www.opengis.net/se"
version="1.1.0" >
<layer>
<se:Name>My Layer</se:Name>
</layer>
</sld>
```
```{r}
d <- xml_new_root("sld",
"xmlns" = "http://www.opengis.net/sld",
"xmlns:ogc" = "http://www.opengis.net/ogc",
"xmlns:se" = "http://www.opengis.net//se",
version = "1.1.0"
) %>%
xml_add_child("layer") %>%
xml_add_child("se:Name", "My Layer") %>%
xml_root()
d
```
| /scratch/gouwar.j/cran-all/cranData/xml2/vignettes/modification.Rmd |
#' @title Package 'xml2relational'
#'
#' @description Transforming a hierarchical XML document into a relational data
#' model.
#'
#' @section What is \code{xml2relational}:
#' The \code{xml2relational} package is
#' designed to 'flatten' XML documents with nested objects into relational
#' dataframes. \code{xml2relational} takes an XML file as input and converts
#' it into a set of dataframes (tables). The tables are linked among each
#' other with foreign keys and can be exported as CSV or ready-to-use SQL code
#' (\code{CREATE TABLE} for the data model, \code{INSERT INTO} for the data).
#'
#'
#' @section How to use \code{xml2relational}:
#' \itemize{ \item First, use
#' \code{\link{toRelational}()} to read in an XML file and to convert into a
#' relational data model. \item This will give you a list of dataframes, one
#' for each table in the relational data model. Tables are linked by foreign
#' keys. You can specify the naming convention for the tables' primary and
#' foreign keys as arguments in \code{\link{toRelational}()}. \item You can
#' now export the data structures of the tables (or a selection of tables)
#' using \code{\link{getCreateSQL}()}. It support multiple SQL dialects, and
#' you also provide syntax and data type information for additional SQL
#' dialects. \item You can also export the data as SQL \code{INSERT}
#' statements with the \code{\link{getInsertSQL}()}. If you only want to
#' export the data as CSV use \code{\link{savetofiles}()} to save the
#' dataframes produced by \code{\link{toRelational}()} as comma-separated
#' files.
#' }
#'@name xml2relational
NULL
get.df <- function(l, table.name) {
if(table.name %in% names(l)) {
return(which(names(l)==table.name))
}
else return(NULL)
}
# check.all: Unique ID accross all tables or only in relation to current table?
# table.name: Table for which ID is generated
create.id <- function(l, table.name, check.all = TRUE, prefix.primary = "ID_", keys.dim = 6) {
id <- NULL
df.index <- get.df(l, table.name)
if(df.index) {
repeat {
id <- round(stats::runif(1, 1, 10^keys.dim-1),0)
if(check.all == TRUE) to.check <- names(l)
else to.check <- table.name
found <- FALSE
for(i in 1:NROW(to.check)){
if(id %in% l[[which(names(l)==to.check[i])]][, paste0(prefix.primary, to.check[i])]) found <- TRUE
}
if(found == FALSE) break
}
}
return(id)
}
serial.df <- function(l, elem.df, df.name, record, prefix.primary, prefix.foreign) {
serial <- c()
elem.df <- data.frame(lapply(elem.df, as.character), stringsAsFactors = FALSE)
for(i in 1:NCOL(elem.df)) {
if(stringr::str_sub(names(elem.df)[i], 1, nchar(prefix.foreign)) == prefix.foreign) {
table.name <- stringr::str_replace(names(elem.df)[i], prefix.foreign, "")
df.sub <- l[[get.df(l, table.name)]]
if(is.null(df.sub)) {
return(NA)
}
else {
if(!is.na(elem.df[record, i])) {
serial <- append(serial, tidyr::replace_na(
serial.df(l, df.sub, table.name, which(df.sub[, paste0(prefix.primary, table.name)] == elem.df[record, i]), prefix.primary, prefix.foreign),"0"))
}
}
}
else {
if(stringr::str_sub(names(elem.df)[i], 1, nchar(prefix.primary)) != prefix.primary) {
serial <- append(serial, tidyr::replace_na(elem.df[record, i], "0"))
names(serial)[NROW(serial)] <- paste0(df.name, "@", names(elem.df)[i])
}
}
}
if(NROW(serial) > 0) {
return(tidyr::replace_na(serial[order(names(serial))],"0"))
}
else return(NA)
}
serial.xml <- function(obj) {
serial <- c()
chdr <- xml2::xml_children(obj)
if(length(chdr) > 0) {
for(i in 1:length(chdr)) {
if(length(xml2::xml_children(chdr[i])) > 0) serial <- append(serial, serial.xml(chdr[i]))
else {
ctn <- as.character(xml2::xml_contents(chdr[i]))
if(identical(ctn, character(0))) ctn <- NA
serial <- append(serial, tidyr::replace_na(ctn, "0"))
names(serial)[NROW(serial)] <- paste0(xml2::xml_name(obj), "@", xml2::xml_name(chdr[i]))
}
}
}
return(serial[order(names(serial))])
}
find.object <- function(l, obj, prefix.primary, prefix.foreign) {
ex <- NULL
elem <- get.df(l, xml2::xml_name(obj))
if(is.null(elem)) ex <- NULL
else {
elem.df <- l[[elem]]
for(i in 1:NROW(elem.df)) {
res.df <- serial.df(l, elem.df, xml2::xml_name(obj), i, prefix.primary, prefix.foreign)
res.xml <- serial.xml(obj)
if(NROW(res.df) == NROW(res.xml)) {
if(sum(tidyr::replace_na(res.df, "0") == tidyr::replace_na(res.xml, "0")) - NROW(res.df) == 0) {
ex <- elem.df[i,paste0(prefix.primary,xml2::xml_name(obj))]
break
}
}
}
}
return(ex)
}
# Mögliche Parameter: Prefix für IDs, IDs unique über alle Tabellen (check.all), Länge der Primärschlüssel
parseXMLNode <- function(parent, envir, first = FALSE, prefix.primary, prefix.foreign, keys.unique, keys.dim) {
if(first == TRUE) {
xml2relational <- new.env(parent = baseenv())
rlang::env_bind(xml2relational, ldf=list())
parseXMLNode(parent, xml2relational, FALSE, prefix.primary, prefix.foreign, keys.unique, keys.dim)
}
else {
obj.name <- xml2::xml_name(parent)
chdr <- xml2::xml_children(parent)
# Does parent have children, i.e. is parent an object?
if(length(chdr) > 0) {
elem <- get.df(envir$ldf, obj.name)
# Is there no dataframe for the parent?
if(is.null(elem)) {
# Create new dataframe
envir$ldf[[length(envir$ldf)+1]] <- data.frame()
names(envir$ldf)[length(envir$ldf)] <- obj.name
# Create record in dataframe
id.name <- paste0(prefix.primary, obj.name)
envir$ldf[[length(envir$ldf)]][1,id.name] <- 0
id.value <- create.id(envir$ldf, obj.name, keys.unique, prefix.primary)
envir$ldf[[length(envir$ldf)]][1,id.name] <- id.value
for(i in 1:length(chdr)) {
if(length(xml2::xml_children(chdr[i])) > 0) envir$ldf[[get.df(envir$ldf, obj.name)]][1, paste0(prefix.foreign, xml2::xml_name(chdr[i]))] <- parseXMLNode(chdr[i], envir, FALSE, prefix.primary, prefix.foreign, keys.unique, keys.dim)$value
else envir$ldf[[get.df(envir$ldf, obj.name)]][1, xml2::xml_name(chdr[i])] <- parseXMLNode(chdr[i], envir, FALSE, prefix.primary, prefix.foreign, keys.unique, keys.dim)$value
}
return(list(ldf=envir$ldf, value=id.value))
}
# dataframe for the object exists already
else {
res <- find.object(envir$ldf, parent, prefix.primary, prefix.foreign)
elem <- get.df(envir$ldf, obj.name)
# Is parent not yet captured in dataframe?
if(is.null(res)) {
id.name <- paste0(prefix.primary, obj.name)
id.value <- create.id(envir$ldf, obj.name, TRUE, prefix.primary, keys.dim)
new.index <- NROW(envir$ldf[[elem]]) + 1
envir$ldf[[elem]][new.index,id.name] <- id.value
for(i in 1:length(chdr)) {
if(length(xml2::xml_children(chdr[i])) > 0) envir$ldf[[get.df(envir$ldf, obj.name)]][new.index, paste0(prefix.foreign, xml2::xml_name(chdr[i]))] <- parseXMLNode(chdr[i], envir, FALSE, prefix.primary, prefix.foreign, keys.unique, keys.dim)$value
else envir$ldf[[get.df(envir$ldf, obj.name)]][new.index, xml2::xml_name(chdr[i])] <- parseXMLNode(chdr[i], envir, FALSE, prefix.primary, prefix.foreign, keys.unique, keys.dim)$value
}
return(list(ldf=envir$ldf, value=id.value))
}
# Return ID of existing parent entry in dataframe
else return(list(ldf=envir$ldf, value=res))
}
}
# parent is not an object
else {
res <- as.character(xml2::xml_contents(parent))
if(length(res) > 0) return(list(ldf=envir$ldf, value=res))
else return(list(ldf=envir$ldf, value=NA))
}
}
}
#' @title Converting an XML document into a relational data model
#'
#' @description Imports an XML document and converts it into a set of
#' dataframes each of which represents one table in the data model.
#'
#' @param file The XML document to be processed.
#' @param prefix.primary A prefix for the tables' primary keys (unique numeric
#' identifier for a data record/row in the table) . Default is \code{"ID_"}.
#' The primary key field name will consist of the prefix and the table name.
#' @param prefix.foreign A prefix for the tables' foreign keys (). Default is
#' \code{"FKID_"}. The rest of the foreign key field name will consist of the
#' prefix and the table name.
#' @param keys.unique Defines if the primary keys must be unique across all
#' tables of the data model or only within the table of which it is the
#' primary key. Default is \code{TRUE} (unique across all tables).
#' @param keys.dim Size of the 'key space' reserved for primary keys. Argument
#' is a power of ten. Default is \code{6} which means the namespace for
#' primary keys extends from \code{1} to \code{1 million}.
#'
#'
#' @details \code{toRelational()} converts the hierarchical XML structure into a
#' flat tabular structure with one dataframe for each table in the data model.
#' \code{toRelational()} determines automatically which XML elements need to
#' be stored in a separate table. The relationship between the nested objects
#' in the XML data is recreated in the dataframes with combinations of foreign
#' and primary keys. The foreign keys refer to the primary keys that
#' \code{toRelational()} creates automatically when adding XML elements to a
#' table.
#' \tabular{llll}{ Column \tab Type \tab Description \tab Example \cr
#' \code{Style} \tab \code{character} \tab Name of the SQL flavor. \tab
#' \code{"MySQL"} \cr \code{NormalField} \tab \code{character} \tab Template
#' string for a normal, nullable field. \tab \code{"\%FIELDNAME\% \%DATATYPE\%"}
#' \cr \code{NormalFieldNotNull} \tab \code{character} \tab Template string
#' for non-nullable field. \tab \code{"\%FIELDNAME\% \%DATATYPE\% NOT NULL"} \cr
#' \code{PrimaryKey} \tab \code{character} \tab Template string for the
#' definition of a primary key. \tab \code{"PRIMARY KEY (\%FIELDNAME\%)"} \cr
#' \code{ForeignKey} \tab \code{character} \tab Template string for the
#' definition of a foreign key. \tab \code{"FOREIGN KEY (\%FIELDNAME\%) REFERENCES
#' \%REFTABLE\%(\%REFPRIMARYKEY\%)"} \cr \code{PrimaryKeyDefSeparate} \tab
#' \code{logical} \tab Indicates if primary key needs additional definition
#' like a any other field. \tab \code{TRUE} \cr \code{ForeignKeyDefSeparate}
#' \tab \code{logical} \tab Indicates if foreign key needs additional
#' definition like a any other field. \tab \code{TRUE} \cr \code{Int} \tab
#' \tab \code{character} \tab Name of integer data type. \code{"INT"} \cr
#' \code{Int.MaxSize} \tab \code{numeric} \tab Size limit of integer data
#' type. \tab \code{4294967295} \cr \code{BigInt} \tab \code{character} \tab
#' Name of data type for integers larger than the size limit of the normal
#' integer data type. \tab \code{"BIGINT"} \cr \code{Decimal} \tab
#' \code{character} \tab Name of data type for floating point numbers. \tab
#' \code{"DECIMAL"} \cr \code{VarChar} \tab \code{character} \tab Name of
#' data type for variable-size character fields. \tab \code{"VARCHAR"} \cr
#' \code{VarChar.MaxSize} \tab \code{numeric} \tab Size limit of variable-size
#' character data type.\tab \code{65535} \cr \code{Text} \tab \code{character}
#' \tab Name of data type for string data larger than the size limit of the
#' variable-size character data type. \tab \code{"TEXT"} \cr \code{Date}
#' \tab \code{character} \tab Name of data type date data. \tab \code{"DATE"}
#' \cr \code{Time} \tab \code{character} \tab Name of data type time data \tab
#' \code{"TIME"} \cr \code{Date} \tab \code{character} \tab Name of data
#' type for combined date and time data. \tab \code{"TIMESTAMP"} \cr }
#'
#' In the template strings you can use the following placeholders, as you also
#' see from the MySQL example in the table: \enumerate{ \item
#' \code{\%FIELDNAME\%}: Name of the field to be defined. \item
#' \code{\%DATATYPE\%}: Datatype of the field to be defined. \item
#' \code{\%REFTABLE\%}: Table referenced by a foreign key. \item
#' \code{\%REFPRIMARYKEY\%}: Name of the primary key field of the table
#' referenced by a foreign key. } When you use your own defintion of an SQL
#' flavor, then \code{sql.style} must be a one-row dataframe providing the
#' fields described in the table above.
#'
#' You can use the \code{datatype.func} argument to provide your own function
#' to determine how the data type of a field is derived from the values in
#' that field. In this case, the values of the columns \code{Int},
#' \code{Int.MaxSize}, \code{VarChar}, \code{VarChar.MaxSize}, \code{Decimal}
#' and \code{Text} in the \code{sql.style} dataframe are ignored. They are
#' used by the built-in mechanism to determine data types. Providing your own
#' function allows you to determine data types in a more differentiated way,
#' if you like. The function that is provided needs to take a vectors of
#' values as its argument and needs to provide the SQL data type of these
#' values as a one-element character vector.
#'
#'
#' @return A list of standard R dataframes, one for each table of the data model. The
#' tables are named for the elements in the XML document.
#'
#'
#' @examples
#'
#' # Find path to custmers.xml example file in package directory
#' path <- system.file("", "customers.xml", package = "xml2relational")
#' db <- toRelational(path)
#'
#' @family xml2relational
#'
#'
#' @export
toRelational <- function(file, prefix.primary = "ID_", prefix.foreign = "FKID_", keys.unique = TRUE, keys.dim = 6) {
x <- xml2::read_xml(file)
p <- xml2::xml_root(x)
return(parseXMLNode(p, NULL, TRUE, prefix.primary, prefix.foreign, keys.unique, keys.dim)$ldf)
}
check.datetimeformats <- function(vec, funcs, return.convertfunc = FALSE, tz = "UTC") {
conv <- list()
for(i in 1:length(funcs)) {
conv[[length(conv)+1]] <- suppressWarnings(funcs[[i]](vec, tz=tz))
}
if(return.convertfunc) {
if(max(unlist(lapply(conv, function(x){sum(!is.na(x))}))) == NROW(vec[!is.na(vec)])) {
return(funcs[unlist(lapply(conv, function(x){sum(!is.na(x))})) == NROW(vec[!is.na(vec)])][[1]])
}
else {
return(NULL)
}
}
else {
return(max(unlist(lapply(conv, function(x){sum(!is.na(x))}))))
}
}
convertible.datetime <- function(vec, return.convertfunc = FALSE, tz = "UTC") {
res <- ""
vec <- as.character(vec)
has.time <- sum(stringr::str_detect(vec, ":"), na.rm=TRUE) == NROW(vec[!is.na(vec)])
funcs <- list(lubridate::ymd_hms, lubridate::ymd_hm, lubridate::ymd_h, lubridate::dmy_hms, lubridate::dmy_hm, lubridate::dmy_h, lubridate::mdy_hms, lubridate::mdy_hm, lubridate::mdy_h)
if(has.time & check.datetimeformats(vec, funcs, FALSE, tz) == NROW(vec[!is.na(vec)])) {
if(return.convertfunc) res <- check.datetimeformats(vec, funcs, TRUE, tz)
else res <- "DateTime"
}
else {
funcs <- list(lubridate::ymd, lubridate::dmy, lubridate::mdy)
if(check.datetimeformats(vec, funcs, FALSE, tz) == NROW(vec[!is.na(vec)])) {
if(return.convertfunc) res <- check.datetimeformats(vec, funcs, TRUE, tz)
else res <- "Date"
}
else {
funcs <- list(lubridate::hms, lubridate::hm, lubridate::ms)
if(has.time & check.datetimeformats(vec, funcs, FALSE, tz) == NROW(vec[!is.na(vec)])) {
if(return.convertfunc) res <- check.datetimeformats(vec, funcs, TRUE, tz)
else res <- "Time"
}
}
}
return(res)
}
convertible.num <- function(vec) {
vec[vec == ""] <- NA
return(sum(is.na(vec)) == sum(is.na(suppressWarnings(as.numeric(vec)))))
}
convertible.double <- function(vec) {
vec <- vec[!is.na(vec)]
return(!(sum((as.numeric(vec) %% 1 == 0)) == NROW(vec)))
}
convertible.enum <- function(vec, max.ratio = 0.25) {
vec <- vec[!is.na(vec)]
if(NROW(vec) > 0) return(NROW(unique(vec))/NROW(vec) <= max.ratio)
else return(FALSE)
}
is.nullable <- function(vec) {
return(sum(is.na(vec)) > 0)
}
infer.datatype <- function(vec, bib, sql.style, tz = "UTC") {
convert.dt <- convertible.datetime(vec, FALSE, tz)
if(convert.dt != "") {
return(as.character(bib[bib$Style == sql.style, convert.dt]))
}
else {
if(convertible.num(vec)) {
# numeric
if(!convertible.double(vec)) {
# integer
vec <- vec[!is.na(vec)]
max.limit <- bib[bib$Style == sql.style, "Int.MaxSize"]
if(max(vec) <= max.limit-1 & min(vec) >= (-1)*max.limit) return(as.character(bib[bib$Style == sql.style, "Int"]))
else return(as.character(bib[bib$Style == sql.style, "BigInt"]))
}
else {
# floating point number
vec.char <- as.character(vec)
dec.pos <- stringr::str_locate(vec.char, "\\.")[,2]
dec.pos.before <- dec.pos - 1
dec.pos.before[is.na(dec.pos.before)] <- stringr::str_length(vec.char[is.na(dec.pos.before)])
vec.char.before <- stringr::str_sub(vec.char, 1, dec.pos.before)
s <- max(stringr::str_length(stringr::str_sub(vec.char, dec.pos + 1, stringr::str_length(vec.char))), na.rm=TRUE)
p <- max(nchar(vec.char.before)) + s
return(paste0(bib[bib$Style == sql.style, "Decimal"], "(", p, ",", s, ")"))
}
}
else {
max.size <- max(nchar(as.character(vec)), na.rm = TRUE)
if(max.size > bib[bib$Style == sql.style, "VarChar.MaxSize"]) return (as.character(bib[bib$Style == sql.style, "Text"]))
else return(paste0(bib[bib$Style == sql.style, "VarChar"], "(",max.size, ")"))
}
}
}
#' @title Exporting the relational data model and data to a database
#'
#' @description Produces ready-to-run SQL \code{INSERT} statements to import the
#' data transformed with \code{\link{toRelational}()} into a SQL database.
#'
#' @param ldf A \strong{l}ist of \strong{d}ata\strong{f}rames created by
#' \code{\link{toRelational}()} (the data tables transformed from XML to a
#' relational schema).
#' @param sql.style The SQL flavor that the produced \code{CREATE} statements
#' will follow. The supported SQL styles are \code{"MySQL"},
#' \code{"TransactSQL"} and \code{"Oracle"}. You can add your own SQL flavor
#' by providing a dataframe with the required information instead of the name
#' of one of the predefined SQL flavors as value for \code{sql.style}. See the
#' Details section for more information on working with different SQL flavors.
#' @param tables A character vector with the names of the tables for whichs SQL
#' \code{CREATE} statements will be produced. If null (default) \code{CREATE}
#' statements will be produced for all tables in in the relational data model
#' of \code{ldf}.
#' @param prefix.primary The prefix that is used in the relational data model of
#' \code{ldf} to identify primary keys. \code{"ID_"} by default.
#' @param prefix.foreign The prefix that is used in the relational data model of
#' \code{ldf} to identify foreign keys. \code{"FKID_"} by default.
#' @param line.break Line break character that is added to the end of each
#' \code{CREATE} statement (apart from the semicolon that is added
#' automatically). Default is \code{"\n"}.
#' @param datatype.func A function that is used to determine the data type of
#' the table fields. The function must take the field/column from the data
#' table (basically the result of \code{SELCT field FROM table})
#' as its sole argument and return a character vector providing the data type.
#' If null (default), the built-in mechanism will be used to determine the
#' data type.
#' @param one.statement Determines whether all \code{CREATE} statements will be
#' returned as one piece of SQL code (\code{one.statement = TRUE}) or if each
#' \code{CREATE} statement will be stored in a separate element of the return
#' vector.
#'
#' @details
#' If you want to produce SQL \code{CREATE} statements that follow a
#' different SQL dialect than one of the built-in SQL flavors (i.e. MySQL,
#' TransactSQL and Oracle) you can provide the necessary information to
#' \code{getCreateSQL()} via the \code{sql.style} argument. In this case the
#' \code{sql.style} argument needs to be a dataframe with the folling fields:
#' \tabular{llll}{ Column \tab Type \tab Description \tab Example \cr
#' \code{Style} \tab \code{character} \tab Name of the SQL flavor. \tab
#' \code{"MySQL"} \cr \code{NormalField} \tab \code{character} \tab Template
#' string for a normal, nullable field. \tab \code{"\%FIELDNAME\% \%DATATYPE\%"}
#' \cr \code{NormalFieldNotNull} \tab \code{character} \tab Template string
#' for non-nullable field. \tab \code{"\%FIELDNAME\% \%DATATYPE\% NOT NULL"} \cr
#' \code{PrimaryKey} \tab \code{character} \tab Template string for the
#' definition of a primary key. \tab \code{"PRIMARY KEY (\%FIELDNAME\%)"} \cr
#' \code{ForeignKey} \tab \code{character} \tab Template string for the
#' definition of a foreign key. \code{"FOREIGN KEY (\%FIELDNAME\%) REFERENCES
#' \%REFTABLE\%(\%REFPRIMARYKEY\%)"} \cr \code{PrimaryKeyDefSeparate} \tab
#' \code{logical} \tab Indicates if primary key needs additional definition
#' like a any other field. \tab \code{TRUE} \cr \code{ForeignKeyDefSeparate}
#' \tab \code{logical} \tab Indicates if foreign key needs additional
#' definition like a any other field. \tab \code{TRUE} \cr \code{Int} \tab
#' \tab \code{character} \tab Name of integer data type. \code{"INT"} \cr
#' \code{Int.MaxSize} \tab \code{numeric} \tab Size limit of integer data
#' type. \tab \code{4294967295} \cr \code{BigInt} \tab \code{character} \tab
#' Name of data type for integers larger than the size limit of the normal
#' integer data type. \tab \code{"BIGINT"} \cr \code{Decimal} \tab
#' \code{character} \tab Name of data type for floating point numbers. \tab
#' \code{"DECIMAL"} \cr \code{VarChar} \tab \code{character} \tab Name of
#' data type for variable-size character fields. \tab \code{"VARCHAR"} \cr
#' \code{VarChar.MaxSize} \tab \code{numeric} \tab Size limit of variable-size
#' character data type.\tab \code{65535} \cr \code{Text} \tab \code{character}
#' \tab Name of data type for string data larger than the size limit of the
#' variable-size character data type. \tab \code{"TEXT"} \cr \cr \code{Date}
#' \tab \code{character} \tab Name of data type date data. \tab \code{"DATE"}
#' \cr \code{Time} \tab \code{character} \tab Name of data type time data \tab
#' \code{"TIME"} \cr \code{Date} \tab \code{character} \tab Name of data
#' type for combined date and time data. \tab \code{"TIMESTAMP"} \cr }
#'
#' In the template strings you can use the following placeholders, as you also
#' see from the MySQL example in the table: \enumerate{ \item
#' \code{\%FIELDNAME\%}: Name of the field to be defined. \item
#' \code{\%DATATYPE\%}: Datatype of the field to be defined. \item
#' \code{\%REFTABLE\%}: Table referenced by a foreign key. \item
#' \code{\%REFPRIMARYKEY\%}: Name of the primary key field of the table
#' referenced by a foreign key. } When you use your own defintion of an SQL
#' flavor, then \code{sql.style} must be a one-row dataframe providing the
#' fields described in the table above.
#'
#' You can use the \code{datatype.func} argument to provide your own function
#' to determine how the data type of a field is derived from the values in
#' that field. In this case, the values of the columns \code{Int},
#' \code{Int.MaxSize}, \code{VarChar}, \code{VarChar.MaxSize}, \code{Decimal}
#' and \code{Text} in the \code{sql.style} dataframe are ignored. They are
#' used by the built-in mechanism to determine data types. Providing your own
#' function allows you to determine data types in a more differentiated way,
#' if you like. The function that is provided needs to take a vectors of
#' values as its argument and needs to provide the SQL data type of these
#' values as a one-element character vector.
#'
#' @return A character vector with exactly one element (if argument
#' \code{one.statement = TRUE}) or with one element per \code{CREATE}
#' statement.
#'
#' @examples
#' # Find path to custmers.xml example file in package directory
#' path <- system.file("", "customers.xml", package = "xml2relational")
#' db <- toRelational(path)
#'
#' sql.code <- getCreateSQL(db, "TransactSQL", "address")
#'
#' @family xml2relational
#'
#' @export
getCreateSQL <- function(ldf, sql.style = "MySQL", tables = NULL, prefix.primary = "ID_", prefix.foreign = "FKID_", line.break ="\n", datatype.func = NULL, one.statement = FALSE) {
sql.stylebib <- data.frame(list(
Style = c("MySQL", "TransactSQL", "Oracle"),
NormalField = c("%FIELDNAME% %DATATYPE%","%FIELDNAME% %DATATYPE%","%FIELDNAME% %DATATYPE%"),
NormalFieldNotNull = c("%FIELDNAME% %DATATYPE% NOT NULL", "%FIELDNAME% %DATATYPE% NOT NULL", "%FIELDNAME% %DATATYPE% NOT NULL"),
PrimaryKey = c("PRIMARY KEY (%FIELDNAME%)", "%FIELDNAME% %DATATYPE% PRIMARY KEY", "%FIELDNAME% %DATATYPE% PRIMARY KEY"),
ForeignKey = c("FOREIGN KEY (%FIELDNAME%) REFERENCES %REFTABLE%(%REFPRIMARYKEY%)", "%FIELDNAME% %DATATYPE% REFERENCES %REFTABLE%(%REFPRIMARYKEY%)", "%FIELDNAME% %DATATYPE% REFERENCES %REFTABLE%(%REFPRIMARYKEY%)"),
PrimaryKeyDefSeparate = c(TRUE, FALSE, FALSE),
ForeignKeyDefSeparate = c(TRUE, FALSE, FALSE),
Int = c("INT", "int", "NUMBER"),
Int.MaxSize = c(2147483648, 2147483648, 1),
BigInt = c("BIGINT", "bigint", "NUMBER"),
Decimal = c("DECIMAL", "decimal", "NUMBER"),
VarChar = c("VARCHAR", "varchar", "VARCHAR2"),
VarChar.MaxSize = c(65535, 8000, 4000),
Text = c("TEXT", "varchar(max)", "LONG"),
Date = c("DATE", "date", "DATE"),
DateTime = c("TIMESTAMP", "datetime2", "TIMESTAMP"),
Time = c("TIME", "TIME", "VARCHAR2(20)")
), stringsAsFactors = FALSE)
if(is.data.frame(sql.style)) {
sql.stylebib <- rbind(sql.stylebib, sql.style)
sql.style = sql.stylebib[1,1]
}
else {
if(!sql.style %in% sql.stylebib[,1]) stop(paste0("'", sql.style, "' is not a valid SQL flavor. Valid flavors are ",
paste0("'", sql.stylebib[,1], "'", collapse = ",")), ".\n")
}
if(is.null(tables)) tabs <- 1:length(ldf)
else {
tabs <- c()
for(i in 1:NROW(tables)) {
if(tables[i] %in% names(ldf)) {
tabs <- append(tabs, get.df(ldf, tables[i]))
}
else warning(paste0("Table '", tables[i], "' does not exist in your data model. Valid tables names are ",
paste0("'", names(ldf), "'", collapse = ",")), ".\n")
}
}
sql.code <- c()
for(i in 1:NROW(tabs)) {
df <- ldf[[get.df(ldf, names(ldf)[tabs[i]])]]
df <- data.frame(lapply(df, as.character), stringsAsFactors = FALSE)
sql.code[i] <- paste0("CREATE TABLE ", names(ldf)[tabs[i]], " (", line.break)
for(f in 1:NCOL(df)) {
if(f != 1) sql.code[i] <- paste0(sql.code[i], ", ")
if(is.null(datatype.func)) datatype <- infer.datatype(df[,f], sql.stylebib, sql.style)
else datatype = datatype.func(df[,f])
field <- names(df)[f]
reftable <- ""
if(field==paste0(prefix.primary, names(ldf)[tabs[i]])) {
# primary
sql.code[i] <- paste0(sql.code[i], sql.stylebib[sql.stylebib$Style==sql.style, "PrimaryKey"])
if(sql.stylebib[sql.stylebib$Style==sql.style, "PrimaryKeyDefSeparate"])
sql.code[i] <- paste0(sql.code[i], line.break, ", ", sql.stylebib[sql.stylebib$Style==sql.style, "NormalField"])
}
else {
if(stringr::str_sub(field, 1, nchar(prefix.foreign)) == prefix.foreign) {
# foreign
reftable <- stringr::str_replace_all(field, prefix.foreign, "")
sql.code[i] <- paste0(sql.code[i], sql.stylebib[sql.stylebib$Style==sql.style, "ForeignKey"])
if(sql.stylebib[sql.stylebib$Style==sql.style, "ForeignKeyDefSeparate"])
sql.code[i] <- paste0(sql.code[i], line.break, ", ", sql.stylebib[sql.stylebib$Style==sql.style, "NormalField"])
}
else {
# normal
if(is.nullable(df[,f])) {
# nullable
sql.code[i] <- paste0(sql.code[i], sql.stylebib[sql.stylebib$Style==sql.style, "NormalField"])
}
else {
# not nullable
sql.code[i] <- paste0(sql.code[i], sql.stylebib[sql.stylebib$Style==sql.style, "NormalFieldNotNull"])
}
}
}
sql.code[i] <- stringr::str_replace_all(sql.code[i], "%FIELDNAME%", field)
sql.code[i] <- stringr::str_replace_all(sql.code[i], "%DATATYPE%", datatype)
sql.code[i] <- stringr::str_replace_all(sql.code[i], "%REFTABLE%", reftable)
sql.code[i] <- stringr::str_replace_all(sql.code[i], "%REFPRIMARYKEY%", paste0(prefix.primary, reftable))
sql.code[i] <- paste0(sql.code[i], line.break)
}
sql.code[i] <- paste0(sql.code[i], ");")
}
if(one.statement) sql.code <- paste0(sql.code, collapse = line.break)
return(sql.code)
}
#' @title Exporting the relational data model and data to a database
#'
#' @description Produces ready-to-run SQL \code{INSERT} statements to import the
#' data transformed with \code{\link{toRelational}()} into a SQL database.
#'
#' @param ldf A \strong{l}ist of \strong{d}ata\strong{f}rames created by
#' \code{\link{toRelational}()} (the data tables transformed from XML to a
#' relational schema).
#' @param table.name Name of the table from the data table list \code{ldf} for
#' which \code{INSERT} statements are to be created.
#' @param line.break Line break character that is added to the end of each
#' \code{INSERT} statement (apart from the semicolon that is added
#' automatically). Default is \code{"\n"}.
#' @param one.statement Determines whether all \code{INSERT} statements will be
#' returned as one piece of SQL code (\code{one.statement = TRUE}) or if each
#' \code{INSERT} statement will be stored in a separate element of the return
#' vector. In the former case the return vector will have just one element, in
#' the latter case as many elements as there are data records to insert.
#' Default is \code{FALSE} (return vector has one element per \code{INSERT}
#' statement.
#' @param tz The code of the timezone used for exporting timestamp data. Default it
#' \code{"UTC"} (Coordinated Universal Time).
#'
#' @return A character vector with exactly one element (if argument
#' \code{one.statement = TRUE}) or with one element per \code{INSERT}
#' statement.
#'
#' @examples
#' # Find path to custmers.xml example file in package directory
#' path <- system.file("", "customers.xml", package = "xml2relational")
#' db <- toRelational(path)
#'
#' sql.code <- getInsertSQL(db, "address")
#'
#' @family xml2relational
#'
#' @export
getInsertSQL <- function(ldf, table.name, line.break = "\n", one.statement = FALSE, tz = "UTC") {
if(!table.name %in% names(ldf)) stop(paste0("Table '", table.name, "' does not exist in your data model. Valid tables names are ",
paste0("'", names(ldf), "'", collapse = ",")), ".\n")
tab <- ldf[[get.df(ldf, table.name)]]
col.delimiter <- c()
cols <- c()
res <- c()
for(f in 1:NCOL(tab)) {
if(convertible.datetime(tab[,f], return.convertfunc = FALSE, tz=tz) != "") tab[,f] <- as.character(convertible.datetime(tab[,f], return.convertfunc = TRUE, tz=tz)(tab[,f]))
if(!convertible.num(tab[,f])) col.delimiter[f] <- "'"
else col.delimiter[f] <- ""
cols <- append(cols, names(tab)[f])
}
cols <- paste0(names(tab), collapse = ", ")
for(i in 1:NROW(tab)) {
vals <- c()
for(f in 1:NCOL(tab)) {
if(!is.na(tab[i,f])) vals <- paste0(vals, ", ", col.delimiter[f], tab[i,f], col.delimiter[f])
else vals <- paste0(vals, ", NULL")
}
vals <- stringr::str_sub(vals, 3, stringr::str_length(vals))
res <- append(res, paste0("INSERT INTO ", table.name, "(", cols, ") VALUES (", vals, ");"))
}
if(one.statement) res <- paste0(res, collapse = line.break)
return(res)
}
#' @title Saving the relational data
#'
#' @description Saves a list of dataframes created from an XML source with
#' \code{\link{toRelational}()} to CSV files, one file per dataframe (i.e.
#' table in the relational data model). File names are identical to the
#' dataframe/table names.
#'
#' @param ldf A \strong{l}ist of \strong{d}ata\strong{f}rames created by
#' \code{\link{toRelational}()} (the data tables transformed from XML to a
#' relational schema).#' @param dir Directory where the files will be stored.
#' Default is the current working directory.
#' @param dir The directory to save the CSV files in. Per default the working directory.
#' @param sep Character symbol to separate fields in the CSV fil, comma by
#' default.
#' @param dec Decimal separator used for numeric fields in the CSV file, point
#' by default.
#'
#' @return No return vaue.
#'
#' @examples
#' # Find path to custmers.xml example file in package directory
#' path <- system.file("", "customers.xml", package = "xml2relational")
#' db <- toRelational(path)
#'
#' savetofiles(db, dir = tempdir())
#'
#'
#' @family xml2relational
#'
#' @export
savetofiles <- function(ldf, dir, sep = ",", dec = ".") {
if(dir != "") {
if(!dir.exists(dir)) stop(paste0("Directory '", dir, "' does not exist."))
}
for(i in 1:length(ldf)) {
tab <- ldf[[i]]
for(f in 1:NCOL(tab)) {
if(convertible.num(tab[,f])) tab[,f] <- as.numeric(tab[,f])
else tab[,f] <- as.character(tab[,f])
}
utils::write.table(tab, file=fs::path(dir, paste0(names(ldf)[i], ".csv")), dec = dec, sep = sep)
}
}
| /scratch/gouwar.j/cran-all/cranData/xml2relational/R/xml2relational.r |
#' @title Package 'xmlconvert'
#'
#' @description Tools for converting XML documents to dataframes and vice versa
#'
#' Functions available:
#' \itemize{
#' \item \code{\link{xml_to_df}()}: Converts an XML document to an R dataframe
#' \item \code{\link{df_to_xml}()}: Converts a dataframe to an XML document
#'}
#'
#'@name xmlconvert
NULL
ifnull <- function(x, alt) {
ifelse(is.null(x), alt, x)
}
url_exists <- function(test.url) {
res<-tryCatch({ invisible(httr::http_status(httr::GET(test.url))) }, error=function(e) { invisible(FALSE) })
if(!is.logical(res)) {
if(res$category == "Success") return(TRUE)
else return(FALSE)
}
else return(FALSE)
}
escape <- function(char) {
if(char %in% c(".","\\", "|", "(", ")", "[", "{", "^", "$", "*", "+", "?")) return(paste0("\\", char))
else return(char)
}
drilldown <- function(node, hierarchy.field.delim, hierarchy.value.sep, no.hierarchy) {
txt <- ""
ch <- xml2::xml_children(node)
if(length(ch) == 0) return(xml2::xml_text(node))
else {
if(!no.hierarchy) {
if(NROW(hierarchy.field.delim) == 1) hierarchy.field.delim <- append(hierarchy.field.delim, hierarchy.field.delim)
txt <- paste0(xml2::xml_find_all(node, paste0(xml2::xml_path(node),"/text()")), collapse = "")
for(i in 1:length(ch)) {
txt <- paste0(txt, hierarchy.field.delim[1], xml2::xml_name(ch[i]), hierarchy.value.sep, drilldown(ch[i], hierarchy.field.delim, hierarchy.value.sep, no.hierarchy), hierarchy.field.delim[2])
}
return(txt)
}
}
}
get_data <- function(rec, fields, only.fields, exclude.fields, field.names, hierarchy.field.delim, hierarchy.value.sep, no.hierarchy) {
if(fields == "tags") {
chd <- xml2::xml_children(rec)
d<-c()
for(i in 1:length(chd)) {
d <- append(d, drilldown(chd[i], hierarchy.field.delim, hierarchy.value.sep, no.hierarchy))
}
if(is.null(field.names)) names(d) <- xml2::xml_name(chd)
else names(d) <- xml2::xml_attr(chd, field.names)
}
else d <- xml2::xml_attrs(rec)
d <- d[!names(d) %in% exclude.fields]
if(!is.null(only.fields)) d <- d[names(d) %in% only.fields]
return(d)
}
#' @title Converting XML to data frames and vice versa
#'
#' @description \code{xml_to_df()} converts XML data to a dataframe. It
#' provides a lot of flexibility with its arguments but can usually be
#' used with just a couple of them to achieve the desired results. See the
#' examples below for simple applications.
#'@param file XML file to be converted. Instead of specifying a file, the XML
#' code can put in directly via the \code{text} argument,
#'@param text XML code to be converted. Instead of providing the XML code, an
#' XML file can be specified with the \code{file} argument.
#'@param first.records Number of records to be converted. If \code{NULL}
#' (default) all records will be converted.
#'@param xml.encoding Encoding of the XML file (optional), e.g. (\code{"UTF-8"})
#'@param records.tags Name (or vector of names) of the tags that represent the
#' data records in the XML (i.e. each record has one element with this tag
#' name). All elements with this tag name will be considered data records.
#' Instead of specifying the tag name, an XPatch expression can be used to
#' identify the data records (see \code{records.xpath})
#'@param records.xpath XPath expression that specifies the XML element to be
#' selected as data records; can be used instead of specifying the data record
#' XML tags directly with the \code{data.records} argument. If both,
#' \code{records.tags} and \code{records.path} are provided, only the XPath
#' expressions determines the tags to be selected.
#'@param fields A character value, either \code{"tags"} or \code{"attributes"}.
#' Specifies whether the fields of each data record are represented as XML tags
#' or as attributes. See \emph{Details} below for more on this topic. Default
#' is \code{"tags"}
#'@param field.names If the data fields are represented by XML elements/tags
#' (i.e. \code{fields = "tags"}) and it is not the tag name that identifies the
#' name of the data field but an attribute of that field tag then the name of
#' the attribute that provides the field name can be specified here. If
#' \code{NULL}, the tag names will be used as field names. See \emph{Details}
#' for more information.
#'@param only.fields Optional vector of tag or attribute names (depending on the
#' \code{fields} argument) of an XML record that will be included in the
#' resulting dataframe. \code{NULL} means all fields found in the data will end
#' up as columns in the dataframe.
#'@param exclude.fields Optional vector of fields that will be excluded from the
#' conversion; fields specified here will not end up as columns in the
#' resulting dataframe
#'@param check.datatypes Logical option that specifies if \code{xml_to_df()}
#' tries to identify the data types of the fields in the XML data. If
#' \code{TRUE} (default), \code{xml_to_df()} tries to identify numeric fields
#' and changes the class of the respective columns in the resulting dataframe
#' accordingly. Use the \code{data.dec} and \code{data.thds} arguments to
#' specify a number format different from the standard US/EN scheme. At this
#' point, there is no data type identification for logical and time/date values
#' available. If \code{check.datatypes} equals \code{FALSE} then all variables
#' in the resulting dataframe will be of class \code{character}
#'@param data.dec A decimal separator used in the identification of numeric data
#' when \code{check.datatypes = TRUE}. Default is dot (\code{.})
#'@param data.thds A thousands separator used in the identification of numeric
#' data when \code{check.datatypes = TRUE}. Default is comma (\code{,})
#'@param stringsAsFactors Logical option specifying if character values will be
#' converted to factors in the resulting data frame. Is only applied if
#' \code{check.datatypes = TRUE} which is the default
#'@param na Value that will be put into the resulting dataframe if the XML data
#' field is \emph{empty}. Default is \code{NA}. If a data record in the XML
#' does not have a specific field at all it is filled with the value provided
#' via the \code{non.exist} argument
#'@param non.exist Value that will be put into the resulting dataframe if a data
#' record in the XML data does not have a specific field at all. Default is the
#' value of the \code{na} (the default of which is \code{NA}). If instead a
#' field is present in the XML data but empty, then it will have the value of
#' the \code{na} argument in the resulting data frame
#'@param no.hierarchy If the fields in the XML data are represented by XML
#' elements/tags (i.e. argument \code{fields = "tags"}) and there is a
#' hierarchical structure below a data field element then this hierarchical
#' structure gets 'flattened', i.e. it will be represented by a single
#' character value. See \emph{Details} for an example
#'@param hierarchy.field.delim One or two-element character vector specifying
#' the tag delimiters used when 'flattening' a hierarchy in the XML data. If
#' only one delimiter is specified then this delimiter will be used for both,
#' the beginning of the tag and the end of the tag. See \emph{Details} for an
#' example
#'@param hierarchy.value.sep Character value that is used as the separator
#' between the tag name and the value of the tag when 'flattening' a hierarchy
#' in the XML data. See \emph{Details} for an example
#'@param no.return Logical option to prevent \code{xml_to_df()} from returning
#' the dataframe it creates; use this if you are only interested in saving the
#' dataframe as Excel or CSV.
#'@param excel.filename Name of an Excel file the resulting dataframe will be
#' exported to. If \code{NULL} (default) there will be no Excel export.
#'@param excel.sheetname Name of the worksheet the resulting dataframe will be
#' exported to when using the Excel export via the \code{excel.filename}
#' argument. If \code{NULL}, \code{xml_to_df()} will figure out a name,
#'@param excel.pw Password that is applied to the Excel workbook when the
#' resulting data.frame is exported via the \code{excel.filename} argument.
#' Default {NULL} means the workbook will not be protected with a password
#'@param csv.filename Name of a CSV file the resulting dataframe will be
#' exported to. If \code{NULL} there will be no CSV export.
#'@param csv.sep Separator used to separate fields in the CSV file when
#' exporting the resulting dataframe via the \code{csv.filename} argument.
#' Default is comma (\code{","})
#'@param csv.dec Decimal separator used when exporting the resulting dataframe
#' via the \code{csv.filename} argument, Default is dot (\code{.})
#'@param csv.encoding Text encoding used when exporting the resulting dataframe
#' via the \code{csv.filename} argument
#'@param ... Additional arguments passed on the \code{write.table()} when
#' exporting the resulting dataframe via the \code{csv.filename} argument,
#' Default is dot (\code{.})
#'@param strip.ns Logical option that can be used to strip the namespaces from
#' the XML data. Default is \code{FALSE}. Try this if parsing of your XML data
#' fails and namespaces are present in your data. Please note: Removing the
#' namespaces from the XML data may increase the time needed for parsing.
#'
#'@return The resulting dataframe. There is no return value if the
#' \code{no.return} argument is set to \code{TRUE}.
#'
#'@details This section provides some more details on how \code{xml_to_df()}
#' works with different ways of representing data fields in the XML (tags
#' versus attributes) and on working with nested XML field structures.\cr\cr
#' \subsection{Two ways of representing the data: Tags and attributes}{ For
#' \code{xml_to_df()} records are always represented by tags (i.e XML
#' elements). Data fields within a record, however, can be represented by
#' either tags or attributes.\cr\cr In the former case the XML would like like
#' this:\cr \code{ <xml>} \cr \code{....<record>} \cr
#' \code{........<field1>Value 1-1</field1>} \cr \code{........<field2>Value
#' 1-2</field2>} \cr \code{....</record>} \cr \code{....<record>} \cr
#' \code{........<field1>Value 2-1</field1>} \cr \code{........<field2>Value
#' 2-2</field2>} \cr \code{....</record>} \cr \code{....</xml>} \cr\cr Here,
#' each data field is represented by its own tag (e.g. \code{field1}). In this
#' case the \code{records.tag} argument would need to be \code{"record"} (or we
#' would specify an XPath expression with \code{records.xpath} that selects
#' these elements) as this is the name of the tags that carry the data records;
#' the \code{fields} argument would need to be \code{"tags"} because the actual
#' data fields are represented by tags nested into the record elements.\cr A
#' variant of this case would be if the fields are represented by tags but the
#' field names are not the tag names but are provided by some attribute of
#' these tags. This is the case in the following example:\cr \code{ <xml>} \cr
#' \code{....<record>} \cr \code{........<data name="field1">Value 1-1</data>}
#' \cr \code{........<data name="field2">Value 1-2</data>} \cr
#' \code{....</record>} \cr \code{....<record>} \cr \code{........<data
#' name="field1">Value 2-1</data>} \cr \code{........<data name"field2">Value
#' 2-2</data>} \cr \code{....</record>} \cr \code{....</xml>} \cr\cr Here, we
#' would use the optional \code{field.names} argument to tell
#' \code{xml_to_df()} with \code{field.names = "name"} that each data tag has
#' an attribute called \code{"name"} that specifies the field name for this
#' data field tag.\cr\cr In contrast to these cases, data fields can also be
#' represented by attributes of the record:\cr \code{<xml>}\cr
#' \code{....<record field1="Value 1-1" field2="Value 1-2" />}\cr
#' \code{....<record field1="Value 2-1" field2="Value 2-2" />}\cr
#' \code{</xml>}\cr Here would need to change the \code{fields} argument to
#' \code{"attributes"}.} \subsection{Working with the nested field values}{
#' When data fields are represented by XML elements / tag then there may nested
#' structures beneath them. If the \code{no.hierarchy} argument is \code{FALSE}
#' (default) this nested structure within a field is recursively analyzed and
#' represented in a single character value for this field. Each nested element
#' is enclosed in the delimiters provided with the \code{hierarchy.field.delim}
#' argument. By default, there is only one such delimiter (and that is
#' \code{"|"}) which is used mark both, the start and the end of an element in
#' the resulting value. However, it is possible to specify to different symbols
#' in order to distinguish start and end of an element. The
#' \code{hierarchy.value.sep} argument is the symbol that separates the name of
#' the argument from its value. Consider the following example:\cr\cr
#' \code{<xml>}\cr \code{....<ship>}\cr \code{........<name>Excelsior<name>}\cr
#' \code{........<lastcaptain>Hikaru Sulu</lastcaptain>}\cr
#' \code{....</ship>}\cr \code{....<ship>}\cr \code{........One proud ship
#' name, many captains}\cr \code{........<name>Enterprise<name>}\cr
#' \code{........<lastcaptain>}\cr \code{............<NCC-1701-A>James Tiberius
#' Kirk</NCC-1701-A>}\cr \code{............<NCC-1701-B>John
#' Harriman</NCC-1701-B>}\cr \code{............<NCC-1701-C>Rachel
#' Garrett</NCC-1701-C>}\cr \code{............<NCC-1701-D>Jean-Luc
#' Picard</NCC-1701-D>}\cr \code{........</lastcaptain>}\cr
#' \code{....</ship>}\cr \code{</xml>}\cr\cr Calling \code{xml_to_df()} with
#' the default values for \code{hierarchy.field.delim} and
#' \code{hierarchy.value.sep} would result in the following value of the
#' \code{lastcapatin} field for the \code{Enterprise} record:\cr \code{One
#' proud name, many captains|NCC-1701-A~James Tiberius Kirk||NCC-1701-B~John
#' Harriman||NCC-1701-C~Rachel Garrett||NCC-1701-D~Jean-Luc Picard|}\cr\cr If
#' we would use \code{hierarchy.field.delim = c("[", "]")} then we would better
#' see the start and of end of each element:\cr \code{One proud name, many
#' captains[NCC-1701-A~James Tiberius Kirk][NCC-1701-B~John
#' Harriman][NCC-1701-C~Rachel Garrett][NCC-1701-D~Jean-Luc Picard]} }
#'
#'
#' @examples
#' # Data used: World population figures from the United Nations Statistics Division
#'
#' # Read in the raw XML; two versions: one with data fields as XML
#' # elements/tags, one with data fields as attributes
#' example.tags <- system.file("worldpopulation_tags.xml", package="xmlconvert")
#' example.attr <- system.file("worldpopulation_attr.xml", package="xmlconvert")
#'
#' # Convert XML data to dataframe
#' worldpop.tags <- xml_to_df(text = example.tags, records.tags = c("record"),
#' fields = "tags", field.names = "name")
#' worldpop.attr <- xml_to_df(text = example.attr, records.tags = c("record"),
#' fields = "attributes")
#'
#'@family xmlconvert
#'
#'@export
xml_to_df <- function(file = NULL, text = NULL, first.records = NULL, xml.encoding = "", records.tags = NULL, records.xpath = NULL,
fields = "tags", field.names = NULL, only.fields = NULL, exclude.fields = NULL,
check.datatypes = TRUE, data.dec = ".", data.thds = ",", stringsAsFactors= FALSE,
na = NA, non.exist = na, no.hierarchy = FALSE, hierarchy.field.delim = "|", hierarchy.value.sep = "~",
no.return = FALSE, excel.filename = NULL, excel.sheetname = NULL, excel.pw = NULL,
csv.filename = NULL, csv.sep = ",", csv.dec = ".", csv.encoding = "", strip.ns = FALSE, ...) {
if(((ifnull(file, "") == "") + (ifnull(text, "") == "")) == 2) stop(
"You need to provide either a file name (argument file) or the XML code itself (argument 'text').")
if(((ifnull(records.tags, "") == "") + (ifnull(records.xpath, "") == "")) == 2) stop(
"You need to provide either a tagQ name (argument 'records.tag') or an xpath expression (argument 'records.xpath') that describes the XML tags which carry the actual data records in your XML file.")
if(ifnull(file, "") != "") {
if(file.exists(file) | url_exists(file)) text <- readr::read_file(file)
else stop(paste0("File or URL '", file, "' could not be opened."))
}
xml <- xml2::read_xml(text, encoding = xml.encoding)
if(strip.ns) xml <- xml2::xml_ns_strip(xml)
xp <- ""
if(!is.null(records.tags)) xp <- paste0("//", records.tags, collapse = " | ")
if(!is.null(records.xpath)) xp <- paste(xp, paste0(records.xpath, collapse = " | "), sep = " | ")
recs <- xml2::xml_find_all(xml, xp)
df <- data.frame()
cols <- c()
if(is.null(first.records)) first.records <- length(recs)
for(i in 1:min(length(recs), first.records)) {
dat <- get_data(recs[[i]], fields, only.fields, exclude.fields, field.names, hierarchy.field.delim, hierarchy.value.sep, no.hierarchy)
dat[is.na(dat)] <- ""
dat[dat == ""] <- na
if(i != 1) {
names.dat <- stringr::str_replace_all(names(dat), " ", "\\.")
new <- names.dat[!names.dat %in% cols]
if(length(new)) {
cols <- append(cols, new)
df[, new] <- non.exist
}
names(dat) <- names.dat
rec.lst <- as.list(dat)
rec.lst[[".data"]] <- df
df <- do.call(tibble::add_row, rec.lst)
df[i, !(names(df) %in% names(dat))] <- non.exist
}
else {
df <- data.frame(as.list(dat), stringsAsFactors = FALSE)
cols <- names(df)
}
}
if(check.datatypes) {
for(i in 1:NCOL(df)) {
num.pattern <- paste0("^[0-9]*", escape(data.dec),"?[0-9]*$|^", escape(data.dec),"?[0-9]*$")
num.check <- stringr::str_trim(stringr::str_replace(df[,i], data.thds, ""))
if(sum(stringr::str_detect(num.check, num.pattern) & stringr::str_replace_na(num.check, "") != "", na.rm=TRUE) == NROW(num.check[stringr::str_replace_na(num.check, "") != ""])) {
df[,i] <- stringr::str_replace(stringr::str_replace(df[,i], escape(data.dec), "."), escape(data.thds), "")
df[,i] <- as.numeric(df[,i])
}
else {
if(stringsAsFactors) df[,i] <- as.factor(df[,i])
}
}
}
# Outputs
if(!is.null(excel.filename)) {
if (requireNamespace("xlsx", quietly = TRUE)) {
if(!is.null(excel.sheetname)) sh <- excel.sheetname
else {
if(!is.null(file)) {
sh <- basename(file)
if(stringr::str_detect(sh, "^.+\\.[:alnum:]{1,4}$")) sh <- stringr::str_match(sh, "^(.+)\\.[:alnum:]{1,4}$")[1,2]
}
else sh <- "xmlconvert results"
}
xlsx::write.xlsx2(df, excel.filename, sh, row.names = FALSE, show.NA=FALSE, password = excel.pw)
}
else {
stop("Please install the 'xlsx' package with 'install.packages(\"xlsx\", dependencies = TRUE) if you want to use the Excel export functionality.", call. = FALSE)
}
}
if(!is.null(csv.filename)) {
utils::write.table(df, csv.filename, sep = csv.sep, dec = csv.dec, fileEncoding = csv.encoding, na = "", ...)
}
if(!no.return) return(df)
}
#' @title Converting XML to data frames and vice versa
#'
#' @description Converts dataframes to XML documents.
#'
#' @param df Dataframe to be converted to XML
#' @param fields A character value, either \code{"tags"} or \code{"attributes"}.
#' Specifies whether the fields of each data record will be represented in the
#' resulting XML document by XML tags or by attributes. See the \emph{Details}
#' section of \code{\link{df_to_xml}()} for more on this topic. Default is
#' \code{"tags"}
#' @param record.tag Name of the tags that will represent the data records in
#' the resulting XML (i.e. each record has one element with this tag name).
#' @param field.names Names of the fields in the XML file. If \code{NULL} then
#' the variable names from the dataframe are used. Field names are corrected
#' automatically to comply with XML naming requirements.
#' @param only.fields Optional vector variable names from the dataframe that
#' will be included in the XML document. If \code{NULL} then all fields from
#' the dataframe are included in the XML document.
#' @param exclude.fields Optional vector of variable names from the dataframe
#' that will not be included in the XML document.
#' @param root.node A character value with the desired name of the root element
#' of the XML document; \code{"root"} by default.
#' @param xml.file Name of a file the XML document it written to. If \code{NULL}
#' no file will be created.
#' @param non.exist Value that will be written into the XML document as field
#' value in case the respective element in the dataframe is \code{NA}. If
#' \code{NULL}, which is the default, no XML tag/attribute (depennding on the
#' \code{fields} argument) will be created for this dataframe element. Using a
#' non-\code{NULL} value for \code{non-exist} allows to make sure that each
#' data record tag in the XML document has exactly the same structure even if
#' some values may be empty (because they are \code{NA} in the original data)
#' @param encoding Encoding of the XML document; default is \code{"UTF-8"}
#' @param no.return Logical option to prevent \code{df_to_xml()} from returning
#' the XML document it creates; use this if you are only interested in saving
#' the XML document to a file using the \code{xml.file} argument.
#'
#' @return The resulting XML document that be edited with the functions from the
#' \pkg{xml2} package. There is no return value if the \code{no.return}
#' argument is set to \code{TRUE}.
#'
#' @examples
#' # Create a dataframe
#' soccer.worldcups <- data.frame(list(year=c(2014, 2010, 2006),
#' location=c("Brazil", "South Africa", "Germany"),
#' goals_scored=c(171, 145, 147),
#' average_goals=c(2.7, 2.3, 2.4),
#' average_attendance=c(57918, 49669,52491)),
#' stringsAsFactors = FALSE)
#'
#' # Convert to XML with the fields (i.e. dataframe variables/columns) stored in XML tags
#' xml <- df_to_xml(soccer.worldcups, fields="tags", record.tag = "worldcup")
#'
#' # Convert to XML with the fields (i.e. dataframe variables/columns) stored in attributes
#' xml <- df_to_xml(soccer.worldcups, fields="tags", record.tag = "worldcup")
#'
#' @family xmlconvert
#'
#' @export
df_to_xml <- function(df, fields = "tags", record.tag = "record", field.names = NULL, only.fields = NULL, exclude.fields = NULL,
root.node = "root", xml.file = NULL, non.exist = NULL, encoding = "UTF-8", no.return = FALSE) {
xml <- xml2::xml_new_root(root.node, encoding = encoding)
if(!is.null(only.fields)) df <- df[, only.fields]
else {
if(!is.null(exclude.fields)) df <- df[, names(df)[!names(df) %in% exclude.fields]]
}
if(is.null(field.names)) field.names <- names(df)
else {
if(length(field.names) != length(names(df))) {
#if(length(names(df)) > 1)
stop(paste0("Number of field names provided through the 'field.names' argument (", length(field.names), ") does not match the number of fields to be exported from the dataframe (", length(names(df)),"). Data fields to be exported are: ", paste0(paste0("'", names(df), "'"), collate=",") ))
#else stop(paste0("Number of field names provided through the 'field.names' argument (", length(field.names), ") does not match the number of fields to be exported from the dataframe (", length(names(df)),"). Data fields to be exported are: ", names(df)))
}
}
field.names <- stringr::str_replace_all(field.names, "[^\\-|[:alnum:]|_|\\.]", "_")
field.names <- stringr::str_replace_all(field.names, "^([^[:lower:]|[:upper:]|_]+)", "_\\1")
for(i in 1:NROW(df)) {
rec <- xml2::xml_add_child(xml, record.tag)
for(f in 1:NCOL(df)) {
if(tolower(fields) == "tags") {
if(!is.na(df[i,f]) | !is.null(non.exist)) {
fld <- xml2::xml_add_child(rec, field.names[f])
xml2::xml_set_text(fld, stringr::str_replace_na(as.character(df[i,f]), ""))
}
}
else {
vals <- as.character(df[i,])
names(vals) <- field.names
xml2::xml_set_attrs(rec, vals)
}
}
}
if(!is.null(xml.file)) xml2::write_xml(xml, xml.file, options = "format")
if(!no.return) return(xml)
}
xml_is_numeric <- function(num) {
return(suppressWarnings(!is.na(as.numeric(num))))
}
xml_convert_types <- function(elem, convert.types, dec, thsd, num.replace, datetime.formats) {
if(convert.types & class(elem) != "list") {
conv <- elem
if(!is.null(datetime.formats)) {
datetime.formats<-datetime.formats[order(nchar(datetime.formats))]
conv.datetime <- NA
for(i in 1:length(datetime.formats)) {
test.datetime <- lubridate::as_date(conv, format=datetime.formats[i])
if(!is.na(test.datetime)) conv.datetime <- test.datetime
}
if(!is.na(conv.datetime)) return(conv.datetime)
}
if(num.replace != "") conv <- stringr::str_replace_all(elem, escape(num.replace), "")
if(thsd != "") conv <- stringr::str_replace_all(conv, escape(thsd), "")
if(dec != "") conv <- stringr::str_replace_all(conv, escape(dec), ".")
conv <- stringr::str_trim(conv, "both")
if(xml_is_numeric(conv)) return(as.numeric(conv))
else return(elem)
}
else return(elem)
}
process_xml_list <- function(elem, convert.types, dec, thsd, num.replace, datetime.formats) {
len <- length(elem)
if(class(elem) == "list") {
if(len == 1) {
if(class(elem[[1]]) == "list") elem <- process_xml_list(elem[[1]], convert.types, dec, thsd, num.replace, datetime.formats)
else return(xml_convert_types(elem[[1]], convert.types, dec, thsd, num.replace, datetime.formats))
}
else {
if(len > 0) {
for(i in 1:len) {
elem[[i]] <- process_xml_list(elem[[i]], convert.types, dec, thsd, num.replace, datetime.formats)
}
}
else return(xml_convert_types(elem, convert.types, dec, thsd, num.replace, datetime.formats))
}
}
return(xml_convert_types(elem, convert.types, dec, thsd, num.replace, datetime.formats))
}
remove_empty_elements <- function(lst) {
for(i in length(lst):1) {
if(length(lst[[i]]) == 0) lst[[i]] <- NULL
else {
if(class(lst[[i]]) == "list") lst[[i]] <- remove_empty_elements(lst[[i]])
}
}
return(lst)
}
#' Converting XML documents to lists
#'
#' @description Converts XML documents to lists. Uses the
#' \code{\link[xml2:as_list]{as_list()}} function from the
#' \code{xml2} package but improves its output. As an effect, numbers, dates
#' and times are converted correctly, unnecessary nested sub-lists with only
#' element are avoided, and empty XML nodes can be removed altogether. This
#' makes the resulting list look cleaner and better structured.
#'
#' @param xml XML document to be converted. Can be read in from a file using
#' \code{xml2}'s \code{read_xml()} function.
#' @param cleanup If \code{TRUE} (default) empty XML nodes (with no sub-nodes or
#' values) will not appear in the list.
#' @param convert.types If \code{TRUE} (default) \code{xml_to_list()} will try
#' to infer the data type of value elements in the XML. If \code{FALSE}, all
#' value elements in the resulting list will be of type \code{character}.
#' @param dec Decimal separator used in numbers.
#' @param thsd Thousands separator used in numbers.
#' @param num.replace An optional string that will be removed before
#' \code{xml_to_list()} tries to convert values to numbers. Can be used, for
#' example, to remove currency symbols or other measurement units from values
#' that are actually numerical.
#' @param datetime.formats A vector of date and/or time formats that will be
#' used to recognize the respective datatypes. Formats will need to be written
#' in the general notation used by \code{\link[base:strftime]{strftime()}} and
#' other standard R functions.
#'
#' @return A \code{list} object representing the XML document.
#' @examples
#' xml <- xml2::read_xml(system.file("customers.xml", package="xmlconvert"))
#' xml.list <- xml_to_list(xml, num.replace="USD", datetime.formats = "%Y-%m-%d")#'
#'
#'@export
xml_to_list <- function(xml, cleanup = TRUE, convert.types = TRUE, dec =".", thsd = ",", num.replace = "", datetime.formats = NULL) {
xml <- xml2::as_list(xml)
lst <- process_xml_list(xml, convert.types, dec, thsd, num.replace, datetime.formats)
if(cleanup) lst <- remove_empty_elements(lst)
return(lst)
}
| /scratch/gouwar.j/cran-all/cranData/xmlconvert/R/xml_convert.r |
#' Parse Data of R Code as an 'XML' Tree
#'
#' Convert the output of 'utils::getParseData()' to an 'XML' tree, that is
#' searchable and easier to manipulate in general.
#'
#' @docType package
#' @name xmlparsedata
NULL
#' Convert R parse data to XML
#'
#' In recent R versions the parser can attach source code location
#' information to the parsed expressions. This information is often
#' useful for static analysis, e.g. code linting. It can be accessed
#' via the \code{\link[utils]{getParseData}} function.
#'
#' \code{xml_parse_data} converts this information to an XML tree.
#' The R parser's token names are preserved in the XML as much as
#' possible, but some of them are not valid XML tag names, so they are
#' renamed, see the \code{\link{xml_parse_token_map}} vector for the
#' mapping.
#'
#' The top XML tag is \code{<exprlist>}, which is a list of
#' expressions, each expression is an \code{<expr>} tag. Each tag
#' has attributes that define the location: \code{line1}, \code{col1},
#' \code{line2}, \code{col2}. These are from the \code{\link{getParseData}}
#' data frame column names.
#'
#' See an example below. See also the README at
#' \url{https://github.com/r-lib/xmlparsedata#readme}
#' for examples on how to search the XML tree with the \code{xml2} package
#' and XPath expressions.
#'
#' Note that `xml_parse_data()` silently drops all control characters
#' (0x01-0x1f) from the input, except horizontal tab (0x09) and newline
#' (0x0a), because they are invalid in XML 1.0.
#'
#' @param pretty Whether to pretty-indent the XML output. It has a small
#' overhead which probably only matters for very large source files.
#' @inheritParams utils::getParseData
#' @return An XML string representing the parse data. See details below.
#'
#' @export
#' @importFrom utils getParseData
#' @seealso \code{\link{xml_parse_token_map}} for the token names.
#' \url{https://github.com/r-lib/xmlparsedata#readme} for more
#' information and use cases.
#' @examples
#' code <- "function(a = 1, b = 2) {\n a + b\n}\n"
#' expr <- parse(text = code, keep.source = TRUE)
#'
#' # The base R way:
#' getParseData(expr)
#'
#' cat(xml_parse_data(expr, pretty = TRUE))
xml_parse_data <- function(x, includeText = NA, pretty = FALSE) {
xml_header <- paste0(
"<?xml version=\"1.0\" encoding=\"UTF-8\" ",
"standalone=\"yes\" ?>\n<exprlist>\n"
)
xml_footer <- "\n</exprlist>\n"
## Maybe it is already a data frame, e.g. when used in lintr
if (is.data.frame(x)) {
pd <- x
} else {
pd <- getParseData(x, includeText = includeText)
}
if (!nrow(pd)) return(paste0(xml_header, xml_footer))
pd <- fix_comments(pd)
if (!is.null(pd$text)) {
pd$text <- enc2utf8(pd$text)
}
## Tags for all nodes, teminal nodes have end tags as well
pd$token <- map_token(pd$token)
## Positions, to make it easy to compare what comes first
maxcol <- max(pd$col1, pd$col2) + 1L
pd$start <- pd$line1 * maxcol + pd$col1
pd$end <- pd$line2 * maxcol + pd$col2
pd$tag <- paste0(
"<", pd$token,
" line1=\"", pd$line1,
"\" col1=\"", pd$col1,
"\" line2=\"", pd$line2,
"\" col2=\"", pd$col2,
"\" start=\"", pd$start,
"\" end=\"", pd$end,
"\">",
if (!is.null(pd$text)) xml_encode(pd$text) else "",
ifelse(pd$terminal, paste0("</", pd$token, ">"), "")
)
## Add an extra terminal tag for each non-terminal one
pd2 <- pd[! pd$terminal, ]
if (nrow(pd2)) {
pd2$terminal <- TRUE
pd2$parent <- -1
pd2$line1 <- pd2$line2
pd2$col1 <- pd2$col2
pd2$line2 <- pd2$line2 - 1L
pd2$col2 <- pd2$col2 - 1L
pd2$tag <- paste0("</", pd2$token, ">")
pd <- rbind(pd, pd2)
}
## Order the nodes properly
## - the terminal nodes from pd2 may be nested inside each other, when
## this happens they will have the same line1, col1, line2, col2 and
## terminal status; and 'start' is used to break ties
ord <- order(pd$line1, pd$col1, -pd$line2, -pd$col2, pd$terminal, -pd$start)
pd <- pd[ord, ]
if (pretty) {
str <- ! pd$terminal
end <- pd$parent == -1
ind <- 2L + cumsum(str * 2L + end * (-2L)) - str * 2L
xml <- paste0(spaces(ind), pd$tag, collapse = "\n")
} else {
xml <- paste(pd$tag, collapse = "\n")
}
paste0(xml_header, xml, xml_footer)
}
fix_comments <- function(pd) {
pd$parent[ pd$parent < 0 ] <- 0
pd
}
map_token <- function(token) {
map <- xml_parse_token_map[token]
ifelse(is.na(map), token, map)
}
#' Map token names of the R parser to token names in
#' \code{\link{xml_parse_data}}
#'
#' Some of the R token names are not valid XML tag names,
#' so \code{\link{xml_parse_data}} needs to replace them to create a
#' valid XML file.
#'
#' @export
#' @seealso \code{\link{xml_parse_data}}
xml_parse_token_map <- c(
"'?'" = "OP-QUESTION",
"'~'" = "OP-TILDE",
"'+'" = "OP-PLUS",
"'-'" = "OP-MINUS",
"'*'" = "OP-STAR",
"'/'" = "OP-SLASH",
"':'" = "OP-COLON",
"'^'" = "OP-CARET",
"'$'" = "OP-DOLLAR",
"'@'" = "OP-AT",
"'('" = "OP-LEFT-PAREN",
"'['" = "OP-LEFT-BRACKET",
"';'" = "OP-SEMICOLON",
"'{'" = "OP-LEFT-BRACE",
"'}'" = "OP-RIGHT-BRACE",
"')'" = "OP-RIGHT-PAREN",
"'!'" = "OP-EXCLAMATION",
"']'" = "OP-RIGHT-BRACKET",
"','" = "OP-COMMA",
"'\\\\'" = "OP-LAMBDA"
)
xml_encode <- function(x) {
x <- gsub("&", "&", x, fixed = TRUE)
x <- gsub("<", "<", x, fixed = TRUE)
x <- gsub(">", ">", x, fixed = TRUE)
# most control characters are not allowed in XML, except tab and nl
x <- gsub("[\x01-\x08\x0b-\x1f]", "", x, useBytes = TRUE)
x
}
| /scratch/gouwar.j/cran-all/cranData/xmlparsedata/R/package.R |
spaces_const <- sapply(1:41-1, function(x) paste(rep(" ", x), collapse = ""))
spaces <- function(x) spaces_const[ pmin(x, 40) + 1 ]
| /scratch/gouwar.j/cran-all/cranData/xmlparsedata/R/utils.R |
#' Reference Class representing a non instantiable class
#' @description An abstract base class with some utility methods
#' @export
AbstractClass <- setRefClass(
Class = "AbstractClass",
methods = list (
initialize = function() {
stop("AbstractClass is an abstract class that can't be initialized.")
},
preventInstatiation = function(self) {
stop(paste(class(self), "is an abstract class that can't be initialized."))
}
)
) | /scratch/gouwar.j/cran-all/cranData/xmlr/R/AbstractClass.R |
#' An abstract reference class representing content that can belong to an Element
#'
#' #' @field m_parent the parent (if any)
#' @export
Content <- setRefClass(
Class = "Content",
contains = "AbstractClass",
fields = "m_parent",
methods = list(
getParent = function() {
m_parent
},
setParent = function(parent) {
m_parent <<- parent
}
)
)
| /scratch/gouwar.j/cran-all/cranData/xmlr/R/Content.R |
#' Reference Class representing an XML document
#' @description
#' The base container for the DOM
#' @details
#' Methods allow access to the root element as well as the
#' DocType and other document-level information.
#' @export Document
#' @exportClass Document
Document <- setRefClass(
Class = "Document",
fields = list(
# @field content This document's content including comments, PIs, a possible DocType, and a root element.
content = "list",
# @field baseURI From where the document was loaded, see https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/core.html#baseURIs-Considerations
m_baseURI = "character"
),
methods = list(
# @param element the root element (optional)
initialize = function(element = NULL) {
if (!is.null(element)) {
content$root <<- element
}
},
setRootElement = function(element) {
content$root <<- element
return(invisible(.self))
},
getRootElement = function() {
return(content$root)
},
getBaseURI = function() {
"return the URI from which this document was loaded"
return(m_baseURI)
},
setBaseURI = function(uri) {
"Sets the effective URI from which this document was loaded"
m_baseURI <<- uri
return(invisible(.self))
},
getDocType = function() {
warning("Document$getDocType() is not implemented")
},
setDocType = function(docType) {
warning("Document$setDocType(docType) not implemented")
},
toString = function() {
if ("root" %in% names(content) & !is.null(content$root)) {
return(paste0(content$root$toString()))
}
message("Attempted toString on a rootless document; There is no root element for this document")
""
},
show = function() {
cat(toString())
}
)
)
#' as.vector for Document classes
#' @describeIn Document as.vector(Document)
#' @param x the object to convert
setMethod('as.vector', "Document",
function(x) {
x$toString()
}
)
#' as.character for Document classes
#' @describeIn Document as.character(Document)
#' @param x the object to convert
setMethod('as.character', "Document",
function(x) {
x$toString()
}
)
| /scratch/gouwar.j/cran-all/cranData/xmlr/R/Document.R |
#' Create a xmlr object tree based on parsing events
DomBuilder <- setRefClass(
Class = "DomBuilder",
fields = c(
"stack",
"doc",
"root"
),
methods = list(
initialize = function(document) {
doc <<- document
},
startDocument = function() {
"Event signalling parsing has begun"
stack <<- Stack$new()
},
endDocument = function() {
"Event signalling parsing has completed"
doc$setRootElement(root)
stack <<- NULL
},
startElement = function(name, attributes) {
"start element event; @param name the element name, @param attributes a named list of attributes"
e <- Element$new(name)
e$setAttributes(attributes)
stack$push(e)
},
endElement = function(name) {
"end element event; @param name the element name"
current <- stack$peek()
if (!stack$isEmpty()) {
e <- stack$pop()
parent <- stack$peek()
if (!is.null(parent)) {
parent$addContent(e)
} else {
root <<- e
}
}
},
text = function(text) {
"text event; @param text the character content of the Text node"
if (nchar(trimws(text)) > 0) {
stack$peek()$setText(text)
}
}
)
) | /scratch/gouwar.j/cran-all/cranData/xmlr/R/DomBuilder.R |
#' @title Element, A reference class representing an XML tag
#' @description
#' An XML element. Methods allow the user to get and manipulate its child
#' elements and content, directly access the element's textual content, and
#' manipulate its attributes.
#'
#' @export Element
#' @exportClass Element
Element <- setRefClass(
Class ="Element",
contains = "Content",
fields = list(
#' @field name The local name of the element
m_name = "character",
#' @field contentList all the children of this element
contentList = "list",
#' @field attributeList a list of all the attributes belonging to this element
attributeList = "list"
),
methods = list(
initialize = function(name = NULL) {
"Element constructor, @param name, The name of the tag (optional)"
if(!is.null(name)) {
m_name <<- name
}
},
addContent = function(content) {
"Appends the child to the end of the content list. return the parent (the calling object)"
idx <- length(contentList) + 1
content$setParent(.self)
contentList[[idx]] <<- content
return(invisible(.self))
},
getContent = function() {
"Returns the full content of the element as a List that may contain objects of type Text, Element, Comment, ProcessingInstruction, CDATA, and EntityRef"
return(contentList)
},
removeContent = function(content) {
"Remove the specified content from this element"
# faster than looping with findContentIndex,
# sapply returns a vector with TRUE or FALSE of each object matching or not matching the content
idx <- sapply(contentList, identical, content)
if (all(!idx)) stop("There is no such content belonging to this Element")
contentList <<- contentList[!idx]
},
removeContentAt = function(index) {
"Remove the content at the given index and return the content that was removed"
if (is.numeric(index)) {
content <- contentList[[index]]
contentList <<- contentList[-index]
return(content)
}
return(NULL)
},
#cloneContent = function() {
# "should return a list containing detached clones of this parent's content list"
# warning("Element", "cloneContent()", "Not implemented")
#},
contentIndex = function(content) {
"Find the position of the content in the contentList or -1 if not found"
for (idx in seq_along(contentList)) {
if(identical(content, contentList[[idx]])) {
return(idx)
}
}
-1
},
hasContent = function() {
"return TRUE if this element has any content, otherwise FALSE"
length(contentList) > 0
},
getName = function() {
"Return the name of this Element"
return(m_name)
},
setName = function(name) {
"Set the name of this Element"
m_name <<- as.character(name)
return(invisible(.self))
},
getAttributes = function() {
"Get the list of attributes"
return(attributeList)
},
getAttribute = function(name) {
"Get an attribute value"
return(attributeList[[name]])
},
setAttribute = function(name, value) {
"Add or replace an attribute, parameters will be converted to characters"
attributeList[[as.character(name)]] <<- as.character(value)
return(invisible(.self))
},
setAttributes = function(attributes) {
"Replace the attributes with this named list, NULL or empty list will remove all attributes, all values will be converted to characters"
if (is.null(attributes)) {
attributeList <<- list()
}
if ("list" != typeof(attributes)) {
stop("Argument to setAttributes must be a list")
}
if (length(names(attributes)) != length(attributes)) {
stop("All attribute values in the list must be named")
}
attributeList <<- lapply(attributes, as.character)
return(invisible(.self))
},
addAttributes = function(attributes) {
"Add the supplied attributes to the attributeList of this Element"
if ("list" != typeof(attributes)) {
stop("Argument to setAttributes must be a list")
}
if (length(names(attributes)) != length(attributes)) {
stop("All attribute values in the list must be named")
}
attributeList <<- append(attributeList, lapply(attributes, as.character))
return(invisible(.self))
},
hasAttributes = function() {
"return TRUE if this element has any attributes, otherwise FALSE"
length(attributeList) > 0
},
setText = function(text) {
"Replace all content with the text supplied"
if ("Text" == class(text)) {
textObj <- text
} else {
textObj <- Text$new(as.character(text))
}
textObj$setParent(.self)
contentList <<- list()
contentList[[text]] <<- textObj
return(invisible(.self))
},
getText = function() {
"Return the text content of this element if any"
texts <- Filter(function(x) "Text" == class(x), contentList)
if (length(texts) > 0) {
return(texts[[1]]$toString())
} else {
return("")
}
},
hasText = function() {
"Return TRUE if this element has a Text node"
texts <- Filter(function(x) "Text" == class(x), contentList)
return( length(texts) > 0)
},
getChildren = function() {
"Get all the child Elements belong to this Element"
Filter(function(x) "Element" == class(x), contentList)
},
hasChildren = function() {
"Return TRUE if this element has any child Element nodes"
length(.self$getChildren()) > 0
},
getChild = function(name) {
"Return the first child element matching the name"
for (content in contentList) {
if ("Element" == class(content) & content$getName() == name) {
return (content)
}
}
},
show = function() {
cat(toString())
},
toString = function(includeContent = TRUE) {
attrString <- ""
if (.self$hasAttributes()) {
attNames <- names(attributeList)
for (i in 1:length(attributeList)) {
attributeString <- paste0(attNames[[i]], "='", attributeList[[i]], "'")
attrString <- paste(attrString, attributeString)
}
}
startElement <- "<"
start <- paste0(startElement, m_name, attrString, ">")
contents <- ""
if (includeContent) {
for (content in contentList) {
contents <- paste0(contents, content$toString())
}
}
end <- paste0("</", m_name, ">")
paste0(start, contents, end)
}
)
)
#' as.vector for Element classes
#' @describeIn Element as.vector(Element)
#' @param x the object to convert
setMethod('as.vector', "Element",
function(x) {
x$toString()
}
)
#' as.character for Element classes
#' @describeIn Element as.character(Element)
#' @param x the object to convert
setMethod('as.character', "Element",
function(x) {
x$toString()
}
) | /scratch/gouwar.j/cran-all/cranData/xmlr/R/Element.R |
#' Parse an xml string and create sax like events
#'
#' @description an XML parser based on an article on creating a quick and dirty xml parser by Steven Brandt:
#' https://www.javaworld.com/article/2077493/java-tip-128--create-a-quick-and-dirty-xml-parser.html
Parser <- setRefClass(
Class = "Parser",
fields = c(
"TEXT",
"ENTITY",
"OPEN_TAG",
"CLOSE_TAG",
"START_TAG",
"ATTRIBUTE_LVALUE",
"ATTRIBUTE_EQUAL",
"ATTRIBUTE_RVALUE",
"QUOTE",
"IN_TAG",
"SINGLE_TAG",
"COMMENT",
"DONE",
"DOCTYPE",
"PRE",
"CDATA"
),
methods = list(
initialize = function() {
TEXT <<- 1
ENTITY <<- 2
OPEN_TAG <<- 3
CLOSE_TAG <<- 4
START_TAG <<- 5
ATTRIBUTE_LVALUE <<- 6
QUOTE <<- 7
IN_TAG <<- 8
ATTRIBUTE_EQUAL <<- 9
ATTRIBUTE_RVALUE <<- 10
DONE <<- 11
SINGLE_TAG <<- 12
COMMENT <<- 13
DOCTYPE <<- 14
PRE <<- 15
CDATA <<- 16
},
parse = function(db, charVector) {
mode <- PRE
st <- Stack$new()
sb <- ""
etag <- ""
depth <- 0
tagName <- NULL
lvalue <- NULL
rvalue <- NULL
line <- 1
col <- 0
eol <- FALSE
attrs <- list()
quotec <- '"'
popMode <- function() {
if (st$isEmpty()) {
return(PRE)
}
st$pop()
}
exc <- function(msg, line, col) {
stop(paste(msg, "near line", line, ", column ", col))
}
db$startDocument()
for (c in charVector) {
# We need to map \r, \r\n, and \n to \n See XML spec section 2.11
if (c == '\n' & eol) {
eol <- FALSE
next
} else if (eol) {
eol <- FALSE
} else if (c == '\n') {
line <- line + 1
col <- 0
} else if (c == '\r') {
eol <- TRUE
c <- '\n'
line <- line + 1
col <- 0
} else {
col <- col + 1
}
if (mode == DONE) {
db$endDocument()
return()
} else if (mode == TEXT) {
# We are between tags collecting text.
if (c == '<') {
st$push(mode)
mode <- START_TAG
if (length(db) > 0) {
db$text(sb)
sb <- ""
}
} else if (c == '&') {
st$push(mode)
mode <- ENTITY
etag <- ""
} else {
sb <- paste0(sb, c)
}
} else if (mode == CLOSE_TAG) {
# we are processing a closing tag: e.g. </foo>
if (c == '>') {
mode <- popMode()
tagName <- sb
sb <- ""
depth <- depth -1
if (depth == 0) mode <- DONE
db$endElement(tagName)
} else {
sb <- paste0(sb, c)
}
} else if (mode == CDATA) {
# we are processing CDATA
if (c == '>' & endsWith(sb, "]]")) {
db$text(substr(sb, 1, nchar(sb)-2))
sb <- ""
mode <- popMode()
} else
sb <- paste0(sb, c)
} else if (mode == COMMENT) {
# we are processing a comment. We are inside the <!-- .... --> looking for the -->.
if (c == '>' & endsWith(sb, "--")) {
sb <- ""
mode <- popMode()
} else
sb <- paste0(sb,c)
} else if (mode == PRE) {
# We are outside the root tag element
if (c == '<') {
mode <- TEXT
st$push(mode)
mode <- START_TAG
}
} else if (mode == DOCTYPE) {
# We are inside one of these <? ... ?>
# or one of these <!DOCTYPE ... >
if (c == '>') {
mode <- popMode()
if (mode == TEXT) mode <- PRE
}
} else if (mode == START_TAG) {
# we have just seen a < and are wondering what we are looking at
# <foo>, </foo>, <!-- ... --->, etc.
mode <- popMode()
if (c == '/') {
st$push(mode)
mode <- CLOSE_TAG
} else if (c == '?') {
mode <- DOCTYPE
} else {
st$push(mode)
mode <- OPEN_TAG
tagName <- NULL
attrs <- list()
sb <- paste0(sb, c)
}
} else if (mode == ENTITY) {
# we are processing an entity, e.g. <, », etc.
if (c == ';') {
mode <- popMode()
cent <- etag
etag <- ""
if (cent == "lt")
sb <- paste0(sb,'<')
else if (cent == "gt")
sb <- paste0(sb,'>')
else if (cent == "amp")
sb <- paste0(sb, '&')
else if (cent == "quot")
sb <- paste0(sb,'"')
else if (cent == "apos")
sb <- paste0(sb, "'")
# Could parse hex entities if we wanted to
# else if(cent.startsWith("#x"))
# sb.append((char)Integer.parseInt(cent.substring(2),16))
else if (startsWith(cent,"#"))
sb <- paste(sb, substr(cent, 2, nchar(cent)))
# Insert custom entity definitions here
else
exc(paste0("Unknown entity: &", cent, ";"), line, col)
} else {
etag <- paste0(etag, c)
}
} else if (mode == SINGLE_TAG) {
# we have just seen something like this:
# <foo a="b"/
# and are looking for the final >.
if (is.null(tagName))
tagName <- sb
if (c != '>')
exc(paste0("Expected > for tag: <" + tagName + "/>"), line, col)
db$startElement(tagName, attrs)
db$endElement(tagName)
if (depth == 0) {
db$endDocument()
return()
}
sb <- ""
attrs <- list()
tagName <- NULL
mode <- popMode()
} else if (mode == OPEN_TAG) {
# we are processing something like this <foo ... >.
# It could still be a <!-- ... --> or something.
if (c == '>') {
if (is.null(tagName)) {
tagName <- sb
}
sb <- ""
depth <- depth +1
db$startElement(tagName, attrs)
tagName <- NULL
attrs <- list()
mode <- popMode()
} else if (c == '/') {
mode <- SINGLE_TAG
} else if (c == '-' & sb == "!-") {
mode <- COMMENT
} else if (c == '[' & sb == "![CDATA") {
mode <- CDATA
sb <- ""
} else if (c == 'E' & sb == "!DOCTYP") {
sb <- ""
mode <- DOCTYPE
} else if (isWhiteSpaceChar(c)) {
tagName <- sb
sb <- ""
mode <- IN_TAG
} else {
sb <- paste0(sb, c)
}
} else if (mode == QUOTE) {
# We are processing the quoted right-hand side of an element's attribute.
if (c == quotec) {
rvalue <- sb
sb <- ""
attrs[[lvalue]] <- rvalue
mode <- IN_TAG
# See section the XML spec, section 3.3.3 on normalization processing.
} else if (c %in% " \r\n\u0009") {
sb <- paste0(sb,' ')
} else if (c == '&') {
st$push(mode)
mode <- ENTITY
etag <- ""
} else {
sb <- paste0(sb,c)
}
} else if (mode == ATTRIBUTE_RVALUE) {
if (c == '"' | c == "'") {
quotec <- c
mode <- QUOTE
} else if (isWhiteSpaceChar(c)) {
# do nothing
} else {
exc("Error in attribute processing", line, col)
}
} else if (mode == ATTRIBUTE_LVALUE) {
if (isWhiteSpaceChar(c)) {
lvalue <- sb
sb <- ""
mode <- ATTRIBUTE_EQUAL
} else if (c == '=') {
lvalue <- sb
sb <- ""
mode <- ATTRIBUTE_RVALUE
} else {
sb <- paste0(sb, c)
}
} else if (mode == ATTRIBUTE_EQUAL) {
if (c == '=') {
mode <- ATTRIBUTE_RVALUE
} else if (isWhiteSpaceChar(c)) {
# do nothing
} else {
exc("Error in attribute processing.", line, col)
}
} else if (mode == IN_TAG) {
if (c == '>') {
mode <- popMode()
db$startElement(tagName, attrs)
depth <- depth +1
tagName <- NULL
attrs <- list()
} else if (c == '/') {
mode <- SINGLE_TAG
} else if (isWhiteSpaceChar(c)) {
#do nothing
} else {
mode <- ATTRIBUTE_LVALUE
sb <- paste0(sb, c)
}
}
} # for loop
if (mode == DONE)
db$endDocument()
else
exc("missing end tag", line, col)
}
)
) | /scratch/gouwar.j/cran-all/cranData/xmlr/R/Parser.R |
#' A general purpose linked stack
#'
#' @export Stack
#' @exportClass Stack
Stack <- setRefClass(
Class="Stack",
fields = list(
#' @field size the size of the stack (number of elements in the stack)
m_size = "integer",
#' @field stackNode an envronment containing the current element and the one under
m_stackNode = "ANY"
),
methods = list(
initialize = function (...) {
m_size <<- 0L
},
isEmpty = function() {
if (m_size == 0) {
return(TRUE)
} else {
return(FALSE)
}
},
createEmptyEnvironment = function() {
emptyenv()
},
createNode = function(val, nextNode = NULL) {
node <- new.env(parent=createEmptyEnvironment())
node$element <- val
node$nextNode <- nextNode
node
},
push = function(val) {
"Add an element to the top of the stack"
if(isEmpty()) {
m_stackNode <<- createNode(val)
} else {
m_stackNode <<- createNode(val, m_stackNode)
}
m_size <<- (m_size + 1L)
},
pop = function() {
"Pull the top element from the stack removing it from the stack"
if(!isEmpty()) {
currentNode <- m_stackNode$element
m_stackNode <<- m_stackNode$nextNode
m_size <<- (m_size - 1L)
return(currentNode)
}
},
peek = function() {
"Get the top element from the stack without changing it"
if(!isEmpty()) {
return(m_stackNode$element)
}
},
size = function() {
"Get the current size of the stack"
m_size
}
)
) | /scratch/gouwar.j/cran-all/cranData/xmlr/R/Stack.R |
#' Reference class representing text content
#' @details
#' An XML character sequence. Provides a modular, parentable method of representing text.
#' @export Text
#' @exportClass Text
Text <- setRefClass(
Class = "Text",
contains = "Content",
fields = list(
value = "character"
),
methods = list(
initialize = function(val) {
value <<- val
},
toString = function() {
return(value)
},
show = function() {
cat(toString())
}
)
)
#' as.vector for Text classes
#' @describeIn Text as.vector(Text)
#' @param x the object to convert
setMethod('as.vector', "Text",
function(x) {
x$toString()
}
)
#' as.character for Text classes
#' @describeIn Text as.character(Text)
#' @param x the object to convert
setMethod('as.character', "Text",
function(x) {
x$toString()
}
) | /scratch/gouwar.j/cran-all/cranData/xmlr/R/Text.R |
#' Common utility functions
#' @describeIn utils Check if the object is a reference class, similar to isS4().
#' @param x the object to check
#' @param clazz the name of the class e.g. "Element" for the Element class.
#' Optional, if omitted it checks that the object is a reference class
#' @return A boolean indicating whether the object \code{x} belongs to the class or not
#' @export
isRc <- function(x, clazz = "refClass") {
is(x, clazz)
}
# internal
notImplemented <- function(className, methodName, ...) {
warning(paste(paste0(className, "$", methodName), "Not implemented,", ...))
}
# internal
whitespace <- c(" ", "\t", "\n", "\r" , "\v", "\f")
# internal
hasWhiteSpace <- function(string) {
if (is.null(string)) return(FALSE)
str <- strsplit(string, "")[[1]]
any(str %in% whitespace)
}
# internal
isWhiteSpaceChar <- function(char) {
if (is.null(char)) return(FALSE)
if (nchar(char, keepNA=TRUE) > 1) return(hasWhiteSpace(char))
char %in% whitespace
} | /scratch/gouwar.j/cran-all/cranData/xmlr/R/utils.R |
#' @title Create a data frame from a xmlr Element
#' @description This is a convenience method to take all the children of the given Element
#' and create a data frame based on the content of each child where each child constitutes a row
#' and the attributes or elements (including text) will constitute the columns.
#' It assumes a homogeneous structure and the column names are takes from the first child
#' @return a data frame
#' @param element the element to convert
#' @export
xmlrToDataFrame <- function(element) {
if (!isRc(element, "Element")) {
stop(paste("element argument is not an Element Reference Class:", class(element)))
}
xmldf <- NULL
for (child in element$getChildren()) {
row <- list()
if (child$hasAttributes()) {
row <- append(row, child$getAttributes())
}
if (child$hasText()) {
row[[child$getName()]] <- child$getText()
}
for (subchild in child$getChildren()) {
if (subchild$hasAttributes()) {
row <- append(row, subchild$getAttributes())
}
if (subchild$hasText()) {
row[[subchild$getName()]] <- subchild$getText()
}
}
if (is.null(xmldf)) {
xmldf <- data.frame(row, stringsAsFactors = FALSE)
} else {
xmldf <- rbind(xmldf, row)
}
}
xmldf
}
| /scratch/gouwar.j/cran-all/cranData/xmlr/R/xmlConverter.R |
#' @title XML import functions
#' @name xmlImporter
#' @return a Document object
NULL
#' @describeIn xmlImporter create a Document from a character string
#' @param xml an xml character string to parse
#' @export
parse.xmlstring <- function(xml) {
"parse an xml string into a document"
doc <- Document$new()
domBuilder <- DomBuilder$new(doc)
parser <- Parser$new()
parser$parse(domBuilder, strsplit(xml, "")[[1]])
return(doc)
}
#' @describeIn xmlImporter create a Document from a xml file
#' @param fileName the name of the xml file to parse
#' @export
parse.xmlfile <- function(fileName) {
# TODO: consider parsing directly from the file stream instead of loading up the content to a string first
#https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/readChar
# or line by line;
# conn <- file(fileName,open="r")
# linn <-readLines(conn)
# for (i in 1:length(linn)){
# print(linn[i])
# }
# close(conn)
if (!file.exists(fileName)) {
stop(paste("File", fileName, "does not exist"))
}
parse.xmlstring(readChar(fileName, file.info(fileName)$size))
} | /scratch/gouwar.j/cran-all/cranData/xmlr/R/xmlImporter.R |
#' xmlr
#' @description A package for creating and reading and manipulating XML
#' inspired by JDOM (http://www.jdom.org/), implemented with Reference Classes.
#' @import methods
#' @docType package
#' @name xmlr
#' @examples
#' library("xmlr")
#' doc <- Document$new()
#' root <- Element$new("table")
#' root$setAttribute("xmlns", "http://www.w3.org/TR/html4/")
#' doc$setRootElement(root)
#'
#' root$addContent(
#' Element$new("tr")
#' $addContent(Element$new("td")$setText("Apples"))
#' $addContent(Element$new("td")$setText("Bananas"))
#' )
#' table <- doc$getRootElement()
#' stopifnot(table$getName() == "table")
#' stopifnot(table$getAttribute("xmlns") == "http://www.w3.org/TR/html4/")
#'
#' children <- table$getChild("tr")$getChildren()
#' stopifnot(length(children) == 2)
#' stopifnot(children[[1]]$getText() == "Apples")
#' stopifnot(children[[2]]$getText() == "Bananas")
#'
#' # you can also parse character strings (or parse a file using parse.xmlfile(fileName))
#' doc <- parse.xmlstring("<foo><bar><baz val='the baz attribute'/></bar></foo>")
NULL | /scratch/gouwar.j/cran-all/cranData/xmlr/R/xmlr.R |
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ----setup--------------------------------------------------------------------
library(xmlr)
## -----------------------------------------------------------------------------
doc <- parse.xmlstring("
<table xmlns='http://www.w3.org/TR/html4/'>
<tr>
<td class='fruit'>Apples</td>
<td class='fruit'>Bananas</td>
</tr>
</table>")
## ---- eval = FALSE------------------------------------------------------------
# doc <- parse.xmlfile("pom.xml")
## -----------------------------------------------------------------------------
doc <- Document$new()
root <- Element$new("table")
root$setAttribute("xmlns", "http://www.w3.org/TR/html4/")
doc$setRootElement(root)
root$addContent(
Element$new("tr")
$addContent(
Element$new("td")$setAttribute("class", "fruit")$setText("Apples")
)
$addContent(
Element$new("td")$setAttribute("class", "fruit")$setText("Bananas")
)
)
# print it out just to show the content
print(doc)
## -----------------------------------------------------------------------------
doc$getRootElement()$getChild("tr")$getChildren()[[2]]$getText()
## -----------------------------------------------------------------------------
groceriesDf <- NULL
for ( child in doc$getRootElement()$getChild("tr")$getChildren() ) {
row <- list()
row[["class"]] <- child$getAttribute("class")
row[["item"]] <- child$getText()
if (is.null(groceriesDf)) {
groceriesDf <- data.frame(row, stringsAsFactors = FALSE)
} else {
groceriesDf <- rbind(groceriesDf, row)
}
}
groceriesDf
## -----------------------------------------------------------------------------
# print the contents of the tr element
root$getChild("tr")
## -----------------------------------------------------------------------------
paste("The root element is", root)
## -----------------------------------------------------------------------------
e <- Element$new()
e$setName("foo")
## -----------------------------------------------------------------------------
e <- Element$new("foo")$addContent(
Element$new("Bar")$setAttribute("note", "Some text")
)$addContent(
Element$new("Baz")$setAttribute("note", "More stuff")
)
e
## -----------------------------------------------------------------------------
e <- Element$new("car")$setText("Volvo")
## -----------------------------------------------------------------------------
xml <- "<car>Volvo<value sek='200000'></value></car>"
e <- Element$new("car")
e$addContent(Text$new("Volvo"))
e$addContent(Element$new("value")$setAttribute("sek", "200000"))
stopifnot(e$toString() == xml)
## -----------------------------------------------------------------------------
parent <- Element$new("parent")
parent <- Element$new("parent")$setAttribute("xmlns:env", "http://some.namespace.com")
parent$addContent(Element$new("env:child"))
parent
## -----------------------------------------------------------------------------
xml <- "
<groceries>
<item type='fruit' number='4'>Apples</item>
<item type='fruit' number='2'>Bananas</item>
<item type='vegetables'number='6'>Tomatoes</item>
</groceries>
"
doc <- parse.xmlstring(xml)
xmldf <- xmlrToDataFrame(doc$getRootElement())
xmldf
## -----------------------------------------------------------------------------
isRc(Element$new("Hello"), "Element")
isRc(Text$new("Hello"), "Element")
| /scratch/gouwar.j/cran-all/cranData/xmlr/inst/doc/xmlr.R |
---
title: "xmlr"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{xmlr}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
```{r setup}
library(xmlr)
```
Xmlr is a document object model of XML written in base-R. It is similar in functionality to the XML package but does not have any dependencies or require compilation. Xmlr allows you to read, write and manipulate XML.
# Why xmlr?
I had problems on one of my machines to install the XML package (some gcc issue) so needed an alternative.
As I have been thinking about doing something more comprehensive with Reference Classes I decided to create
a pure base-R DOM model with some simple ways to do input and output to strings and files. As it turned out to
be useful to me, I thought it might be for others as well, so I decided to open source and publish it.
# Creating the XML tree
There are 2 ways to create an XML tree, by parsing XML text or by creating it programmatically.
## Parsing
Xmlr supports two ways of parsing text: either from a character string or from a xml file.
To parse a string you do something like:
```{r}
doc <- parse.xmlstring("
<table xmlns='http://www.w3.org/TR/html4/'>
<tr>
<td class='fruit'>Apples</td>
<td class='fruit'>Bananas</td>
</tr>
</table>")
```
...and similarly to parse a XML file you do:
```{r, eval = FALSE}
doc <- parse.xmlfile("pom.xml")
```
## Programmatic creation
To create the following xml
```
<table xmlns='http://www.w3.org/TR/html4/'>
<tr>
<td class='fruit'>Apples</td>
<td class='fruit'>Bananas</td>
</tr>
</table>
```
...you could do something like this:
```{r}
doc <- Document$new()
root <- Element$new("table")
root$setAttribute("xmlns", "http://www.w3.org/TR/html4/")
doc$setRootElement(root)
root$addContent(
Element$new("tr")
$addContent(
Element$new("td")$setAttribute("class", "fruit")$setText("Apples")
)
$addContent(
Element$new("td")$setAttribute("class", "fruit")$setText("Bananas")
)
)
# print it out just to show the content
print(doc)
```
## Navigating the tree
As XML is a hierarchical model it is very well suited for an Object based implementation. The top-level class is the Document class. It contains a reference to the root element that you get through the `getRootElement()` method.
Elements contain attributes and child content (more elements or a Text node). To get the text of the second td element (tag) you would something like this:
```{r}
doc$getRootElement()$getChild("tr")$getChildren()[[2]]$getText()
```
This is useful when you have a more complex structure, and you want to create a data.frame of a part of the xml. e.g.
```{r}
groceriesDf <- NULL
for ( child in doc$getRootElement()$getChild("tr")$getChildren() ) {
row <- list()
row[["class"]] <- child$getAttribute("class")
row[["item"]] <- child$getText()
if (is.null(groceriesDf)) {
groceriesDf <- data.frame(row, stringsAsFactors = FALSE)
} else {
groceriesDf <- rbind(groceriesDf, row)
}
}
groceriesDf
```
You can also move upwards in the tree by using the **getParent()** function which exists for all Content (Element and Text nodes).
## Outputting
As you saw in the example above the default print will render the object model as an XML string. Print is available for each element and will print all the content in and below this element e.g.
```{r}
# print the contents of the tr element
root$getChild("tr")
```
# The object model
The xmlr object model is very simple, you basically only need to care about the Document and the Element classes.
In general all Objects has a toString() function that returns the textual XML representation of the object.
as.character and as.vector are also specified for each class allowing you to do stuff like:
```{r}
paste("The root element is", root)
```
Which is the same as doing `paste("The root element is", root$toString())`
## Document
As mentioned before the most useful thing to do with the Document object is to set or get the rootElement. In a future version you might also be interested in processing instructions etc. but those are not supported yet.
## Element
An Element has three "interests", name, attributes and child nodes. text is handled in a special way (there is a Text class) since the form `<foo>Som text here</foo>` is very common.
### Name
This set the name of the Element (the tag) e.g. to create the element <foo/> you can either do `e <- Element$new("foo")`
or use the **setName(name)** function:
```{r}
e <- Element$new()
e$setName("foo")
```
To get the Element name you use the function **getName()**
### Attributes
The following functions are available for attributes:
* **getAttribute(name)**
This gets the attribute value for the name argument supplied, e.g. `child$getAttribute("class")`
* **getAttributes()**
This gives you the list of attributes for this Element. You can navigate the list just like normal e.g.
`child$getAttributes()[["class"]]` or use in a loop or apply etc.
* **setAttribute(name, value)**
Creates or updates an existing attribute for the name and value supplied. E.g. `root$setAttribute("xmlns", "http://www.w3.org/TR/html4/")`.
* **setAttributes(attributes)**
This sets all the attributes of the Element to the list given. Note that you MUST supply a named list for this to work.
Any existing attribute will vanish.
* **addAttributes(attributes)**
Similar to setAttributes but will not erase any existing attributes.
* **hasAttributes()**
TRUE if any attributes are defined for the element.
### Content
Content can be either other Element(s) or Text.
For the xml
```
<foo>
<Bar note='Some text'</Bar>
<Baz note='More stuff'</Baz>
</foo>
```
...you can do something like this:
```{r}
e <- Element$new("foo")$addContent(
Element$new("Bar")$setAttribute("note", "Some text")
)$addContent(
Element$new("Baz")$setAttribute("note", "More stuff")
)
e
```
To retrieve content there are several ways:
* **getContent()**
This will get you the complete list of content regardless if they are Elements or Text nodes.
* **getChildren()**
This will give you a list of Elements belonging to this element.
* **removeContent(content)**
This will remove the content supplied from this Elements content list.
* **removeContentAt(index)**
Same as above but for the position in the list matching the index supplied.
* **contentIndex(content)**
Gives you the index of the content supplied or -1 if no content was found.
* **getChild(name)**
Gives you the *first* occurrence of the Element that is a child of this element with the name matching the name supplied
* **hasContent()**
TRUE if there is any content belonging to this element
* **hasChildren()**
TRUE if there is any child elements for this element
### Text
As mentioned above Text is treated a bit special.
You typically use the **setText(text)** function to set text content e.g. to create `<car>Volvo</car>` you would do:
```{r}
e <- Element$new("car")$setText("Volvo")
```
However, for more complex cases it is possible to mix text and elements using **addContent()**. E.g. for the xml
`<cars>Volvo<value sek='200000'></value></cars>`
You can create it by creating and adding a Text node explicitly rather than using the setText function.
```{r}
xml <- "<car>Volvo<value sek='200000'></value></car>"
e <- Element$new("car")
e$addContent(Text$new("Volvo"))
e$addContent(Element$new("value")$setAttribute("sek", "200000"))
stopifnot(e$toString() == xml)
```
To check if there is any text defined for this element you can use the function **hasText()**
# Namespaces
Namespaces is handled in a very simplistic way in xmlr. You declare the namespace as an attribute, and
you maintain the correct prefix "manually" by prefixing the element name e.g:
```{r}
parent <- Element$new("parent")
parent <- Element$new("parent")$setAttribute("xmlns:env", "http://some.namespace.com")
parent$addContent(Element$new("env:child"))
parent
```
# Other useful stuff
There is a simplistic way to produce a dataframe from a XML tree: **xmlrToDataFrame(element)**
it can be used (similar to the xmlToDataFrame in the classic XML package) as follows:
```{r}
xml <- "
<groceries>
<item type='fruit' number='4'>Apples</item>
<item type='fruit' number='2'>Bananas</item>
<item type='vegetables'number='6'>Tomatoes</item>
</groceries>
"
doc <- parse.xmlstring(xml)
xmldf <- xmlrToDataFrame(doc$getRootElement())
xmldf
```
If you have a more complex xml structure you need to build your data frame "by hand" e.g. in a similar fashion to what
was outlined in the "Navigating the tree" section.
## Misc
There are some general purpose classes and functions that might be useful if you want to extend or customize xmlr:
* **isRc(x, clazz = "refClass")**
Check if the object is a reference class, similar to isS4() when only the object is supplied but can be narrowed
down to the specific RC class if the clazz argument is given. E.g. to check that the object is an Element you can do
```{r}
isRc(Element$new("Hello"), "Element")
isRc(Text$new("Hello"), "Element")
```
* **Stack**
This is a general purpose linked stack with the expected functions i.e.
* **pop()**
Retrieve and remove the top item from the stack
* **push(item)**
Add an item to the stack
* **peek()**
Retrieve the top item from the stack without removing it
* **size()**
Get the number of items on the stack
* **isEmpty()**
Returns TRUE if the stack is empty or FALSE if it is still has items.
* **Parser**
A general purpose, SAX like, parser that you could create your own builder for. A builder needs to have the following functions (See **DomBuilder** for an example):
* **startDocument()**
* **endDocument()**
* **startElement(name, attributes)**
* **endElement(name)**
* **text(text)**
| /scratch/gouwar.j/cran-all/cranData/xmlr/inst/doc/xmlr.Rmd |
---
title: "xmlr"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{xmlr}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
```{r setup}
library(xmlr)
```
Xmlr is a document object model of XML written in base-R. It is similar in functionality to the XML package but does not have any dependencies or require compilation. Xmlr allows you to read, write and manipulate XML.
# Why xmlr?
I had problems on one of my machines to install the XML package (some gcc issue) so needed an alternative.
As I have been thinking about doing something more comprehensive with Reference Classes I decided to create
a pure base-R DOM model with some simple ways to do input and output to strings and files. As it turned out to
be useful to me, I thought it might be for others as well, so I decided to open source and publish it.
# Creating the XML tree
There are 2 ways to create an XML tree, by parsing XML text or by creating it programmatically.
## Parsing
Xmlr supports two ways of parsing text: either from a character string or from a xml file.
To parse a string you do something like:
```{r}
doc <- parse.xmlstring("
<table xmlns='http://www.w3.org/TR/html4/'>
<tr>
<td class='fruit'>Apples</td>
<td class='fruit'>Bananas</td>
</tr>
</table>")
```
...and similarly to parse a XML file you do:
```{r, eval = FALSE}
doc <- parse.xmlfile("pom.xml")
```
## Programmatic creation
To create the following xml
```
<table xmlns='http://www.w3.org/TR/html4/'>
<tr>
<td class='fruit'>Apples</td>
<td class='fruit'>Bananas</td>
</tr>
</table>
```
...you could do something like this:
```{r}
doc <- Document$new()
root <- Element$new("table")
root$setAttribute("xmlns", "http://www.w3.org/TR/html4/")
doc$setRootElement(root)
root$addContent(
Element$new("tr")
$addContent(
Element$new("td")$setAttribute("class", "fruit")$setText("Apples")
)
$addContent(
Element$new("td")$setAttribute("class", "fruit")$setText("Bananas")
)
)
# print it out just to show the content
print(doc)
```
## Navigating the tree
As XML is a hierarchical model it is very well suited for an Object based implementation. The top-level class is the Document class. It contains a reference to the root element that you get through the `getRootElement()` method.
Elements contain attributes and child content (more elements or a Text node). To get the text of the second td element (tag) you would something like this:
```{r}
doc$getRootElement()$getChild("tr")$getChildren()[[2]]$getText()
```
This is useful when you have a more complex structure, and you want to create a data.frame of a part of the xml. e.g.
```{r}
groceriesDf <- NULL
for ( child in doc$getRootElement()$getChild("tr")$getChildren() ) {
row <- list()
row[["class"]] <- child$getAttribute("class")
row[["item"]] <- child$getText()
if (is.null(groceriesDf)) {
groceriesDf <- data.frame(row, stringsAsFactors = FALSE)
} else {
groceriesDf <- rbind(groceriesDf, row)
}
}
groceriesDf
```
You can also move upwards in the tree by using the **getParent()** function which exists for all Content (Element and Text nodes).
## Outputting
As you saw in the example above the default print will render the object model as an XML string. Print is available for each element and will print all the content in and below this element e.g.
```{r}
# print the contents of the tr element
root$getChild("tr")
```
# The object model
The xmlr object model is very simple, you basically only need to care about the Document and the Element classes.
In general all Objects has a toString() function that returns the textual XML representation of the object.
as.character and as.vector are also specified for each class allowing you to do stuff like:
```{r}
paste("The root element is", root)
```
Which is the same as doing `paste("The root element is", root$toString())`
## Document
As mentioned before the most useful thing to do with the Document object is to set or get the rootElement. In a future version you might also be interested in processing instructions etc. but those are not supported yet.
## Element
An Element has three "interests", name, attributes and child nodes. text is handled in a special way (there is a Text class) since the form `<foo>Som text here</foo>` is very common.
### Name
This set the name of the Element (the tag) e.g. to create the element <foo/> you can either do `e <- Element$new("foo")`
or use the **setName(name)** function:
```{r}
e <- Element$new()
e$setName("foo")
```
To get the Element name you use the function **getName()**
### Attributes
The following functions are available for attributes:
* **getAttribute(name)**
This gets the attribute value for the name argument supplied, e.g. `child$getAttribute("class")`
* **getAttributes()**
This gives you the list of attributes for this Element. You can navigate the list just like normal e.g.
`child$getAttributes()[["class"]]` or use in a loop or apply etc.
* **setAttribute(name, value)**
Creates or updates an existing attribute for the name and value supplied. E.g. `root$setAttribute("xmlns", "http://www.w3.org/TR/html4/")`.
* **setAttributes(attributes)**
This sets all the attributes of the Element to the list given. Note that you MUST supply a named list for this to work.
Any existing attribute will vanish.
* **addAttributes(attributes)**
Similar to setAttributes but will not erase any existing attributes.
* **hasAttributes()**
TRUE if any attributes are defined for the element.
### Content
Content can be either other Element(s) or Text.
For the xml
```
<foo>
<Bar note='Some text'</Bar>
<Baz note='More stuff'</Baz>
</foo>
```
...you can do something like this:
```{r}
e <- Element$new("foo")$addContent(
Element$new("Bar")$setAttribute("note", "Some text")
)$addContent(
Element$new("Baz")$setAttribute("note", "More stuff")
)
e
```
To retrieve content there are several ways:
* **getContent()**
This will get you the complete list of content regardless if they are Elements or Text nodes.
* **getChildren()**
This will give you a list of Elements belonging to this element.
* **removeContent(content)**
This will remove the content supplied from this Elements content list.
* **removeContentAt(index)**
Same as above but for the position in the list matching the index supplied.
* **contentIndex(content)**
Gives you the index of the content supplied or -1 if no content was found.
* **getChild(name)**
Gives you the *first* occurrence of the Element that is a child of this element with the name matching the name supplied
* **hasContent()**
TRUE if there is any content belonging to this element
* **hasChildren()**
TRUE if there is any child elements for this element
### Text
As mentioned above Text is treated a bit special.
You typically use the **setText(text)** function to set text content e.g. to create `<car>Volvo</car>` you would do:
```{r}
e <- Element$new("car")$setText("Volvo")
```
However, for more complex cases it is possible to mix text and elements using **addContent()**. E.g. for the xml
`<cars>Volvo<value sek='200000'></value></cars>`
You can create it by creating and adding a Text node explicitly rather than using the setText function.
```{r}
xml <- "<car>Volvo<value sek='200000'></value></car>"
e <- Element$new("car")
e$addContent(Text$new("Volvo"))
e$addContent(Element$new("value")$setAttribute("sek", "200000"))
stopifnot(e$toString() == xml)
```
To check if there is any text defined for this element you can use the function **hasText()**
# Namespaces
Namespaces is handled in a very simplistic way in xmlr. You declare the namespace as an attribute, and
you maintain the correct prefix "manually" by prefixing the element name e.g:
```{r}
parent <- Element$new("parent")
parent <- Element$new("parent")$setAttribute("xmlns:env", "http://some.namespace.com")
parent$addContent(Element$new("env:child"))
parent
```
# Other useful stuff
There is a simplistic way to produce a dataframe from a XML tree: **xmlrToDataFrame(element)**
it can be used (similar to the xmlToDataFrame in the classic XML package) as follows:
```{r}
xml <- "
<groceries>
<item type='fruit' number='4'>Apples</item>
<item type='fruit' number='2'>Bananas</item>
<item type='vegetables'number='6'>Tomatoes</item>
</groceries>
"
doc <- parse.xmlstring(xml)
xmldf <- xmlrToDataFrame(doc$getRootElement())
xmldf
```
If you have a more complex xml structure you need to build your data frame "by hand" e.g. in a similar fashion to what
was outlined in the "Navigating the tree" section.
## Misc
There are some general purpose classes and functions that might be useful if you want to extend or customize xmlr:
* **isRc(x, clazz = "refClass")**
Check if the object is a reference class, similar to isS4() when only the object is supplied but can be narrowed
down to the specific RC class if the clazz argument is given. E.g. to check that the object is an Element you can do
```{r}
isRc(Element$new("Hello"), "Element")
isRc(Text$new("Hello"), "Element")
```
* **Stack**
This is a general purpose linked stack with the expected functions i.e.
* **pop()**
Retrieve and remove the top item from the stack
* **push(item)**
Add an item to the stack
* **peek()**
Retrieve the top item from the stack without removing it
* **size()**
Get the number of items on the stack
* **isEmpty()**
Returns TRUE if the stack is empty or FALSE if it is still has items.
* **Parser**
A general purpose, SAX like, parser that you could create your own builder for. A builder needs to have the following functions (See **DomBuilder** for an example):
* **startDocument()**
* **endDocument()**
* **startElement(name, attributes)**
* **endElement(name)**
* **text(text)**
| /scratch/gouwar.j/cran-all/cranData/xmlr/vignettes/xmlr.Rmd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.