1
0
mirror of https://github.com/msberends/AMR.git synced 2024-12-25 19:26:13 +01:00

add clipboard functions again

This commit is contained in:
dr. M.S. (Matthijs) Berends 2018-06-27 15:54:56 +02:00
parent dab085d7ad
commit 649a8025aa
10 changed files with 358 additions and 2 deletions

View File

@ -1,6 +1,6 @@
Package: AMR Package: AMR
Version: 0.2.0.9005 Version: 0.2.0.9006
Date: 2018-06-20 Date: 2018-06-28
Title: Antimicrobial Resistance Analysis Title: Antimicrobial Resistance Analysis
Authors@R: c( Authors@R: c(
person( person(
@ -28,12 +28,14 @@ Depends:
R (>= 3.0.0) R (>= 3.0.0)
Imports: Imports:
backports, backports,
clipr,
curl, curl,
dplyr (>= 0.7.0), dplyr (>= 0.7.0),
data.table (>= 1.10.0), data.table (>= 1.10.0),
reshape2 (>= 1.4.0), reshape2 (>= 1.4.0),
xml2 (>= 1.0.0), xml2 (>= 1.0.0),
knitr (>= 1.0.0), knitr (>= 1.0.0),
readr,
rvest (>= 0.3.2), rvest (>= 0.3.2),
tibble tibble
Suggests: Suggests:

View File

@ -28,6 +28,8 @@ export(as.rsi)
export(atc_ddd) export(atc_ddd)
export(atc_groups) export(atc_groups)
export(atc_property) export(atc_property)
export(clipboard_export)
export(clipboard_import)
export(first_isolate) export(first_isolate)
export(freq) export(freq)
export(frequency_tbl) export(frequency_tbl)
@ -63,6 +65,8 @@ exportMethods(print.tbl)
exportMethods(print.tbl_df) exportMethods(print.tbl_df)
exportMethods(summary.mic) exportMethods(summary.mic)
exportMethods(summary.rsi) exportMethods(summary.rsi)
importFrom(clipr,read_clip_tbl)
importFrom(clipr,write_clip)
importFrom(curl,nslookup) importFrom(curl,nslookup)
importFrom(data.table,data.table) importFrom(data.table,data.table)
importFrom(dplyr,"%>%") importFrom(dplyr,"%>%")
@ -70,6 +74,7 @@ importFrom(dplyr,all_vars)
importFrom(dplyr,any_vars) importFrom(dplyr,any_vars)
importFrom(dplyr,arrange) importFrom(dplyr,arrange)
importFrom(dplyr,arrange_at) importFrom(dplyr,arrange_at)
importFrom(dplyr,as_tibble)
importFrom(dplyr,between) importFrom(dplyr,between)
importFrom(dplyr,desc) importFrom(dplyr,desc)
importFrom(dplyr,filter) importFrom(dplyr,filter)
@ -98,6 +103,8 @@ importFrom(graphics,axis)
importFrom(graphics,barplot) importFrom(graphics,barplot)
importFrom(graphics,plot) importFrom(graphics,plot)
importFrom(graphics,text) importFrom(graphics,text)
importFrom(readr,locale)
importFrom(readr,parse_guess)
importFrom(reshape2,dcast) importFrom(reshape2,dcast)
importFrom(rvest,html_children) importFrom(rvest,html_children)
importFrom(rvest,html_node) importFrom(rvest,html_node)
@ -109,4 +116,6 @@ importFrom(stats,sd)
importFrom(utils,browseVignettes) importFrom(utils,browseVignettes)
importFrom(utils,object.size) importFrom(utils,object.size)
importFrom(utils,packageDescription) importFrom(utils,packageDescription)
importFrom(utils,read.delim)
importFrom(utils,write.table)
importFrom(xml2,read_html) importFrom(xml2,read_html)

View File

@ -3,6 +3,7 @@
* Function `top_freq` function to get the top/below *n* items of frequency tables * Function `top_freq` function to get the top/below *n* items of frequency tables
* Vignette about frequency tables * Vignette about frequency tables
* Possibility to globally set the default for the amount of items to print in frequency tables (`freq` function), with `options(max.print.freq = n)` * Possibility to globally set the default for the amount of items to print in frequency tables (`freq` function), with `options(max.print.freq = n)`
* Functions `clipboard_import` and `clipboard_export` as helper functions to quickly copy and paste from/to software like Excel and SPSS
#### Changed #### Changed
* Renamed `toConsole` parameter of `freq` function to `as.data.frame` * Renamed `toConsole` parameter of `freq` function to `as.data.frame`

178
R/clipboard.R Normal file
View File

@ -0,0 +1,178 @@
#' Import/export from clipboard
#'
#' @description These are helper functions around \code{\link{read.table}} and \code{\link{write.table}} to import from and export to clipboard with support for Windows, Linux and macOS.
#'
#' The data will be read and written as tab-separated by default, which makes it possible to copy and paste from other software like Excel and SPSS without further transformation.
#'
#' Supports automatic column type transformation and supports new classes \code{\link{as.rsi}} and \code{\link{as.mic}}.
#' @rdname clipboard
#' @name clipboard
#' @inheritParams utils::read.table
#' @inheritParams utils::write.table
#' @inheritParams readr::locale
#' @param startrow \emph{n}th row to start importing from. When \code{header = TRUE}, the import will start on row \code{startrow} \emph{below} the header.
#' @param as_vector a logical value indicating whether data consisting of only one column should be imported as vector using \code{\link[dplyr]{pull}}. This will strip off the header.
#' @param guess_col_types a logical value indicating whether column types should be guessed with the \code{readr} package.
#' @param info print info about copying
#' @keywords clipboard clipboard_import clipboard_export import export
#' @importFrom dplyr %>% pull as_tibble
#' @importFrom clipr read_clip_tbl write_clip
#' @importFrom utils read.delim write.table object.size
#' @importFrom readr parse_guess locale
#' @details
#' When using \code{guess_col_types = TRUE}, all column types will be determined automatically with \code{\link[readr]{parse_guess}} from the \code{readr} package. Besides, the antimicrobial classes in this AMR package (\code{\link{as.rsi}} and \code{\link{as.mic}}) are also supported.
#'
#' \if{html}{
#' \strong{Example for copying from Excel:}
#' \out{<div style="text-align: left">}\figure{clipboard_copy.png}\out{</div>}
#' \cr
#' \strong{And pasting in R:} \cr
#' \cr
#' \code{> data <- clipboard_import()} \cr
#' \code{> data} \cr
#' \out{<div style="text-align: left">}\figure{clipboard_paste.png}\out{</div>}
#' \cr
#' \strong{The resulting data contains the right RSI-classes:} \cr
#' \cr
#' \code{> data$amox} \cr
#' \out{<div style="text-align: left">}\figure{clipboard_rsi.png}\out{</div>}
#' }
#' @export
clipboard_import <- function(sep = '\t',
header = TRUE,
dec = ".",
na = c("", "NA", "NULL"),
startrow = 1,
as_vector = TRUE,
guess_col_types = TRUE,
date_names = 'en',
date_format = '%Y-%m-%d',
time_format = '%H:%M',
tz = Sys.timezone(),
encoding = "UTF-8",
info = FALSE) {
if (clipr::clipr_available() & info == TRUE) {
cat('Importing from clipboard...')
}
# this will fail when clipr is not available
import_tbl <- clipr::read_clip_tbl(file = file,
sep = sep,
header = header,
strip.white = TRUE,
dec = dec,
na.strings = na,
encoding = 'UTF-8',
stringsAsFactors = FALSE)
if (info == TRUE) {
cat('OK\n')
}
# use tibble, so column types will be translated correctly
import_tbl <- as_tibble(import_tbl)
if (startrow > 1) {
# would else lose column headers
import_tbl <- import_tbl[startrow:nrow(import_tbl),]
}
colnames(import_tbl) <- gsub('[.]+', '_', colnames(import_tbl))
if (guess_col_types == TRUE) {
if (info == TRUE) {
cat('Transforming columns with readr::parse_guess...')
}
import_tbl <- clipboard_format(tbl = import_tbl,
date_names = date_names,
date_format = date_format,
time_format = time_format,
decimal_mark = dec,
tz = tz,
encoding = encoding,
na = na)
if (info == TRUE) {
cat('OK\n')
}
}
if (NCOL(import_tbl) == 1 & as_vector == TRUE) {
import_tbl <- import_tbl %>% pull(1)
}
if (info == TRUE) {
cat("Successfully imported from clipboard:", NROW(import_tbl), "obs. of", NCOL(import_tbl), "variables.\n")
}
import_tbl
}
#' @rdname clipboard
#' @importFrom dplyr %>% pull as_tibble
#' @export
clipboard_export <- function(x,
sep = '\t',
dec = ".",
na = "",
header = TRUE,
info = TRUE) {
clipr::write_clip(content = x,
na = na,
sep = sep,
row.names = FALSE,
col.names = header,
dec = dec,
quote = FALSE)
if (info == TRUE) {
cat("Successfully exported to clipboard:", NROW(x), "obs. of", NCOL(x), "variables.\n")
}
}
clipboard_format <- function(tbl,
date_names = 'en',
date_format = '%Y-%m-%d',
time_format = '%H:%M',
decimal_mark = '.',
tz = Sys.timezone(),
encoding = "UTF-8",
na = c("", "NA", "NULL")) {
date_format <- date_generic(date_format)
time_format <- date_generic(time_format)
# set col types with readr
for (i in 1:ncol(tbl)) {
if (!all(tbl %>% pull(i) %>% class() %in% c('list', 'matrix'))) {
tbl[, i] <- readr::parse_guess(x = tbl %>% pull(i) %>% as.character(),
na = na,
locale = readr::locale(date_names = date_names,
date_format = date_format,
time_format = time_format,
decimal_mark = decimal_mark,
encoding = encoding,
tz = tz,
asciify = FALSE))
}
if (any(tbl %>% pull(i) %>% class() %in% c('factor', 'character'))) {
# get values
distinct_val <- tbl %>% pull(i) %>% unique() %>% sort()
# remove ASCII escape character: https://en.wikipedia.org/wiki/Escape_character#ASCII_escape_character
tbl[, i] <- tbl %>% pull(i) %>% gsub('\033', ' ', ., fixed = TRUE)
# look for RSI, shouldn't all be "" and must be valid antibiotic interpretations
if (!all(distinct_val[!is.na(distinct_val)] == '')
& all(distinct_val[!is.na(distinct_val)] %in% c('', 'I', 'I;I', 'R', 'R;R', 'S', 'S;S'))) {
tbl[, i] <- tbl %>% pull(i) %>% as.rsi()
}
}
# convert to MIC class
if (colnames(tbl)[i] %like% '_mic$') {
tbl[, i] <- tbl %>% pull(i) %>% as.mic()
}
}
tbl
}

View File

@ -114,3 +114,55 @@ size_humanreadable <- function(bytes, decimals = 1) {
out <- paste(sprintf(paste0("%.", decimals, "f"), bytes / (1024 ^ factor)), size[factor + 1]) out <- paste(sprintf(paste0("%.", decimals, "f"), bytes / (1024 ^ factor)), size[factor + 1])
out out
} }
# transforms date format like "dddd d mmmm yyyy" to "%A %e %B %Y"
date_generic <- function(format) {
if (!grepl('%', format, fixed = TRUE)) {
# first months and minutes, after that everything is case INsensitive
format <- gsub('mmmm', '%B1', format, fixed = TRUE)
format <- gsub('mmm', '%b', format, fixed = TRUE)
format <- gsub('mm', '%m', format, fixed = TRUE)
format <- gsub('MM', '%M1', format, fixed = TRUE)
format <- format %>%
tolower() %>%
gsub('%b1', '%B', ., fixed = TRUE) %>%
gsub('%m1', '%M', ., fixed = TRUE)
# dates
format <- gsub('dddd', '%A', format, fixed = TRUE)
format <- gsub('ddd', '%a', format, fixed = TRUE)
format <- gsub('dd', '%!', format, fixed = TRUE)
format <- gsub('d', '%e', format, fixed = TRUE)
format <- gsub('%!', '%d', format, fixed = TRUE)
format <- gsub('ww', '%V', format, fixed = TRUE)
format <- gsub('w', '%V', format, fixed = TRUE)
format <- gsub('qq', 'Qq', format, fixed = TRUE) # so will be 'Q%%q' after this
format <- gsub('kk', 'Kq', format, fixed = TRUE)
format <- gsub('k', 'q', format, fixed = TRUE)
format <- gsub('q', '%%q', format, fixed = TRUE)
format <- gsub('yyyy_iso', '%G', format, fixed = TRUE)
format <- gsub('jjjj_iso', '%G', format, fixed = TRUE)
format <- gsub('yyyy', '%Y', format, fixed = TRUE)
format <- gsub('jjjj', '%Y', format, fixed = TRUE)
format <- gsub('yy_iso', '%g', format, fixed = TRUE)
format <- gsub('jj_iso', '%g', format, fixed = TRUE)
format <- gsub('yy', '%y', format, fixed = TRUE)
format <- gsub('jj', '%y', format, fixed = TRUE)
# time
format <- gsub('hh', '%H', format, fixed = TRUE)
format <- gsub('h', '%k', format, fixed = TRUE)
format <- gsub('ss', '%S', format, fixed = TRUE)
# seconds since the Epoch, 1970-01-01 00:00:00
format <- gsub('unix', '%s', format, fixed = TRUE)
# Equivalent to %Y-%m-%d (the ISO 8601 date format)
format <- gsub('iso', '%F', format, fixed = TRUE)
}
format
}

105
man/clipboard.Rd Normal file
View File

@ -0,0 +1,105 @@
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/clipboard.R
\name{clipboard}
\alias{clipboard}
\alias{clipboard_import}
\alias{clipboard_export}
\title{Import/export from clipboard}
\usage{
clipboard_import(sep = "\\t", header = TRUE, dec = ".", na = c("", "NA",
"NULL"), startrow = 1, as_vector = TRUE, guess_col_types = TRUE,
date_names = "en", date_format = "\%Y-\%m-\%d", time_format = "\%H:\%M",
tz = Sys.timezone(), encoding = "UTF-8", info = FALSE)
clipboard_export(x, sep = "\\t", dec = ".", na = "", header = TRUE,
info = TRUE)
}
\arguments{
\item{sep}{the field separator character. Values on each line of the
file are separated by this character. If \code{sep = ""} (the
default for \code{read.table}) the separator is \sQuote{white space},
that is one or more spaces, tabs, newlines or carriage returns.}
\item{header}{a logical value indicating whether the file contains the
names of the variables as its first line. If missing, the value is
determined from the file format: \code{header} is set to \code{TRUE}
if and only if the first row contains one fewer field than the
number of columns.}
\item{dec}{the character used in the file for decimal points.}
\item{na}{the string to use for missing values in the data.}
\item{startrow}{\emph{n}th row to start importing from. When \code{header = TRUE}, the import will start on row \code{startrow} \emph{below} the header.}
\item{as_vector}{a logical value indicating whether data consisting of only one column should be imported as vector using \code{\link[dplyr]{pull}}. This will strip off the header.}
\item{guess_col_types}{a logical value indicating whether column types should be guessed with the \code{readr} package.}
\item{date_names}{Character representations of day and month names. Either
the language code as string (passed on to \code{\link[=date_names_lang]{date_names_lang()}})
or an object created by \code{\link[=date_names]{date_names()}}.}
\item{date_format}{Default date and time formats.}
\item{time_format}{Default date and time formats.}
\item{tz}{Default tz. This is used both for input (if the time zone isn't
present in individual strings), and for output (to control the default
display). The default is to use "UTC", a time zone that does not use
daylight savings time (DST) and hence is typically most useful for data.
The absence of time zones makes it approximately 50x faster to generate
UTC times than any other time zone.
Use \code{""} to use the system default time zone, but beware that this
will not be reproducible across systems.
For a complete list of possible time zones, see \code{\link{OlsonNames}()}.
Americans, note that "EST" is a Canadian time zone that does not have
DST. It is \emph{not} Eastern Standard Time. It's better to use
"US/Eastern", "US/Central" etc.}
\item{encoding}{encoding to be assumed for input strings. It is
used to mark character strings as known to be in
Latin-1 or UTF-8 (see \code{\link{Encoding}}): it is not used to
re-encode the input, but allows \R to handle encoded strings in
their native encoding (if one of those two). See \sQuote{Value}
and \sQuote{Note}.
}
\item{info}{print info about copying}
\item{x}{the object to be written, preferably a matrix or data frame.
If not, it is attempted to coerce \code{x} to a data frame.}
}
\description{
These are helper functions around \code{\link{read.table}} and \code{\link{write.table}} to import from and export to clipboard with support for Windows, Linux and macOS.
The data will be read and written as tab-separated by default, which makes it possible to copy and paste from other software like Excel and SPSS without further transformation.
Supports automatic column type transformation and supports new classes \code{\link{as.rsi}} and \code{\link{as.mic}}.
}
\details{
When using \code{guess_col_types = TRUE}, all column types will be determined automatically with \code{\link[readr]{parse_guess}} from the \code{readr} package. Besides, the antimicrobial classes in this AMR package (\code{\link{as.rsi}} and \code{\link{as.mic}}) are also supported.
\if{html}{
\strong{Example for copying from Excel:}
\out{<div style="text-align: left">}\figure{clipboard_copy.png}\out{</div>}
\cr
\strong{And pasting in R:} \cr
\cr
\code{> data <- clipboard_import()} \cr
\code{> data} \cr
\out{<div style="text-align: left">}\figure{clipboard_paste.png}\out{</div>}
\cr
\strong{The resulting data contains the right RSI-classes:} \cr
\cr
\code{> data$amox} \cr
\out{<div style="text-align: left">}\figure{clipboard_rsi.png}\out{</div>}
}
}
\keyword{clipboard}
\keyword{clipboard_export}
\keyword{clipboard_import}
\keyword{export}
\keyword{import}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@ -0,0 +1,9 @@
context("clipboard.R")
test_that("clipboard works", {
skip_if_not(clipr::clipr_available())
clipboard_export(antibiotics)
expect_identical(antibiotics,
clipboard_import())
})