Title: | Various Programming Utilities |
---|---|
Description: | Utility functions useful when programming and developing R packages. |
Authors: | Henrik Bengtsson [aut, cre, cph] |
Maintainer: | Henrik Bengtsson <[email protected]> |
License: | LGPL (>= 2.1) |
Version: | 2.12.3 |
Built: | 2024-11-12 03:09:37 UTC |
Source: | https://github.com/HenrikBengtsson/R.utils |
Utility functions useful when programming and developing R packages.
Warning: The Application Programming Interface (API) of the classes and methods in this package may change. Classes and methods are considered either to be stable, or to be in beta or alpha (pre-beta) stage. See list below for details.
The main reason for publishing this package on CRAN although it lacks a stable API, is that its methods and classes are used internally by other packages on CRAN that the author has published.
For package history, see showHistory(R.utils)
.
This package requires the R.oo package [1].
To install this package do:
install.packages("R.utils")
[alpha] Methods for common argument processing.
[alpha] Methods for assertion of values and states.
[alpha] A character string class with methods for simple substitution.
[beta] Reads and writes Java streams.
[alpha] Tree-structured options queried in a file-system like manner.
[alpha] An Options class for reading and writing package settings.
[beta] Text-based progress bar.
[beta] A ProgressBar that reports progress as file size.
[alpha] Methods for access to system.
[alpha] A class for verbose and log output. Utilized by the VComments and LComments classes.
[alpha] Methods for preprocessing source code comments of certain formats into R code.
In addition to the above, there is a large set of function for file handling such as support for reading/following Windows Shortcut links, but also other standalone utility functions. See package index for a list of these. These should also be considered to be in alpha or beta stage.
Whenever using this package, please cite [1] as
Bengtsson, H. The R.oo package - Object-Oriented Programming with References Using Standard R Code, Proceedings of the 3rd International Workshop on Distributed Statistical Computing (DSC 2003), ISSN 1609-395X, Hornik, K.; Leisch, F. & Zeileis, A. (ed.), 2003
Here is a list of features that would be useful, but which I have too little time to add myself. Contributions are appreciated.
Write a TclTkProgressBar class.
Improve/stabilize the GString class.
Mature the SmartComments classes. Also add AComments and PComments for assertion and progress/status comments.
If you consider implement some of the above, make sure it is not already implemented by downloading the latest "devel" version!
The releases of this package is licensed under LGPL version 2.1 or newer.
The development code of the packages is under a private licence (where applicable) and patches sent to the author fall under the latter license, but will be, if incorporated, released under the "release" license above.
[1] H. Bengtsson, The R.oo package - Object-Oriented Programming with References Using Standard R Code, In Kurt Hornik, Friedrich Leisch and Achim Zeileis, editors, Proceedings of the 3rd International Workshop on Distributed Statistical Computing (DSC 2003), March 20-22, Vienna, Austria. https://www.r-project.org/conferences/DSC-2003/Proceedings/
Henrik Bengtsson
Modifies .Last() to call 'finalizeSession() before calling the default .Last()
function.
Note that .Last()
is not guaranteed to be called when
the R session finished. For instance, the user may quit R by calling
quit(runLast=FALSE)
or run R in batch mode.
Note that this function is called when the R.utils package is loaded.
## Default S3 method: addFinalizerToLast(...)
## Default S3 method: addFinalizerToLast(...)
... |
Not used. |
Returns (invisibly) TRUE
if .Last()
was modified,
otherwise FALSE
.
Henrik Bengtsson
Package: R.utils
Class Arguments
Object
~~|
~~+--
Arguments
Directly known subclasses:
public static class Arguments
extends Object
Methods:
getCharacter |
- | |
getCharacters |
- | |
getDirectory |
- | |
getDouble |
- | |
getDoubles |
- | |
getEnvironment |
- | |
getFilename |
- | |
getIndex |
- | |
getIndices |
- | |
getInstanceOf |
- | |
getInteger |
- | |
getIntegers |
- | |
getLogical |
- | |
getLogicals |
- | |
getNumeric |
- | |
getNumerics |
- | |
getReadablePath |
- | |
getReadablePathname |
- | |
getReadablePathnames |
- | |
getRegularExpression |
- | |
getVector |
- | |
getVerbose |
- | |
getWritablePath |
- | |
getWritablePathname |
- | |
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
Package: R.utils
Class Assert
Object
~~|
~~+--
Assert
Directly known subclasses:
public static class Assert
extends Object
Assert(...)
Assert(...)
... |
Not used. |
Methods:
check |
- | |
inheritsFrom |
- | |
isMatrix |
- | |
isScalar |
- | |
isVector |
- | |
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
Assigns an objects elements locally.
## S3 method for class 'list' attachLocally(object, fields=NULL, excludeFields=NULL, overwrite=TRUE, envir=parent.frame(), ...)
## S3 method for class 'list' attachLocally(object, fields=NULL, excludeFields=NULL, overwrite=TRUE, envir=parent.frame(), ...)
object |
An object with named elements such as an |
fields |
A |
excludeFields |
A |
overwrite |
If |
envir |
The |
... |
Not used. |
Returns (invisibly) a character
vector
of the fields copied.
Henrik Bengtsson
attachLocally()
of class Object.
attach
().
foo <- function(object) { cat("Local objects in foo():\n") print(ls()) attachLocally(object) cat("\nLocal objects in foo():\n") print(ls()) for (name in ls()) { cat("\nObject '", name, "':\n", sep="") print(get(name, inherits=FALSE)) } } a <- "A string" l <- list(a=1:10, msg="Hello world", df=data.frame(a=NA, b=2)) foo(l) print(a)
foo <- function(object) { cat("Local objects in foo():\n") print(ls()) attachLocally(object) cat("\nLocal objects in foo():\n") print(ls()) for (name in ls()) { cat("\nObject '", name, "':\n", sep="") print(get(name, inherits=FALSE)) } } a <- "A string" l <- list(a=1:10, msg="Hello world", df=data.frame(a=NA, b=2)) foo(l) print(a)
Call hook functions by hook name.
## Default S3 method: callHooks(hookName, ..., removeCalledHooks=FALSE)
## Default S3 method: callHooks(hookName, ..., removeCalledHooks=FALSE)
hookName |
A |
... |
Argument passed to each hook function. |
removeCalledHooks |
If |
Returns (invisibly) whatever callHooks.list
() returns.
Henrik Bengtsson
Internally, after retrieving hook functions, callHooks.list
() is
called.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Example 1 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # First, clean up if called more than once setHook("myFunction.onEnter", NULL, action="replace") setHook("myFunction.onExit", NULL, action="replace") runConference <- function(...) { callHooks("myFunction.onEnter") cat("Speaker A: Hello there...\n") callHooks("myFunction.onExit") } setHook("myFunction.onEnter", function(...) { cat("Chair: Welcome to our conference.\n") }) setHook("myFunction.onEnter", function(...) { cat("Chair: Please welcome Speaker A!\n") }) setHook("myFunction.onExit", function(...) { cat("Chair: Please thanks Speaker A!\n") }) runConference() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Example 2 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - setHook("randomNumber", NULL, action="replace") setHook("randomNumber", rnorm) # By function setHook("randomNumber", "rexp") # By name setHook("randomNumber", "runiff") # Non-existing name setHook("randomNumber", .GlobalEnv) # Not a function res <- callHooks("randomNumber", n=1) str(res) cat("Number of hooks: ", length(res), "\n") isErroneous <- unlist(lapply(res, FUN=function(x) !is.null(x$exception))) cat("Erroneous hooks: ", sum(isErroneous), "\n")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Example 1 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # First, clean up if called more than once setHook("myFunction.onEnter", NULL, action="replace") setHook("myFunction.onExit", NULL, action="replace") runConference <- function(...) { callHooks("myFunction.onEnter") cat("Speaker A: Hello there...\n") callHooks("myFunction.onExit") } setHook("myFunction.onEnter", function(...) { cat("Chair: Welcome to our conference.\n") }) setHook("myFunction.onEnter", function(...) { cat("Chair: Please welcome Speaker A!\n") }) setHook("myFunction.onExit", function(...) { cat("Chair: Please thanks Speaker A!\n") }) runConference() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Example 2 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - setHook("randomNumber", NULL, action="replace") setHook("randomNumber", rnorm) # By function setHook("randomNumber", "rexp") # By name setHook("randomNumber", "runiff") # Non-existing name setHook("randomNumber", .GlobalEnv) # Not a function res <- callHooks("randomNumber", n=1) str(res) cat("Number of hooks: ", length(res), "\n") isErroneous <- unlist(lapply(res, FUN=function(x) !is.null(x$exception))) cat("Erroneous hooks: ", sum(isErroneous), "\n")
Call hook functions.
## S3 method for class 'function' callHooks(hooks, ...)
## S3 method for class 'function' callHooks(hooks, ...)
hooks |
|
... |
Argument passed to each hook function. |
Returns (invisibly) a list
that is named with hook names, if possible.
Each element in the list is in turn a list
with three element:
fcn
is the hook function called, result
is its return
value, and exception
is the exception caught or NULL
.
Henrik Bengtsson
See callHooks
() to call hook function by name.
Capitalizes/decapitalized (making the first letter upper/lower case) of each character string in a vector.
## Default S3 method: capitalize(str, ...) ## Default S3 method: decapitalize(str, ...)
## Default S3 method: capitalize(str, ...) ## Default S3 method: decapitalize(str, ...)
str |
|
... |
Not used. |
Returns a vector
of character
strings of the same length as the input
vector.
Henrik Bengtsson
words <- strsplit("Hello wOrld", " ")[[1]] cat(paste(toupper(words), collapse=" "), "\n") # "HELLO WORLD" cat(paste(tolower(words), collapse=" "), "\n") # "hello world" cat(paste(capitalize(words), collapse=" "), "\n") # "Hello WOrld" cat(paste(decapitalize(words), collapse=" "), "\n") # "hello wOrld" # Sanity checks stopifnot(paste(toupper(words), collapse=" ") == "HELLO WORLD") stopifnot(paste(tolower(words), collapse=" ") == "hello world") stopifnot(paste(capitalize(words), collapse=" ") == "Hello WOrld") stopifnot(paste(decapitalize(words), collapse=" ") == "hello wOrld")
words <- strsplit("Hello wOrld", " ")[[1]] cat(paste(toupper(words), collapse=" "), "\n") # "HELLO WORLD" cat(paste(tolower(words), collapse=" "), "\n") # "hello world" cat(paste(capitalize(words), collapse=" "), "\n") # "Hello WOrld" cat(paste(decapitalize(words), collapse=" "), "\n") # "hello wOrld" # Sanity checks stopifnot(paste(toupper(words), collapse=" ") == "HELLO WORLD") stopifnot(paste(tolower(words), collapse=" ") == "hello world") stopifnot(paste(capitalize(words), collapse=" ") == "Hello WOrld") stopifnot(paste(decapitalize(words), collapse=" ") == "hello wOrld")
Evaluate an R expression and captures the output.
captureOutput(expr, file=NULL, append=FALSE, collapse=NULL, envir=parent.frame())
captureOutput(expr, file=NULL, append=FALSE, collapse=NULL, envir=parent.frame())
expr |
The R expression to be evaluated. |
file |
A file name or a |
append |
If |
collapse |
A |
envir |
The |
This method imitates capture.output
with the major
difference that it captures strings via a raw
connection rather
than via internal strings. The latter becomes exponentially slow
for large outputs [1,2].
Returns captured output as a character
vector
.
Henrik Bengtsson
[1] R-devel thread 'capture.output(): Using a rawConnection() [linear] instead of textConnection() [exponential]?', 2014-02-04. https://stat.ethz.ch/pipermail/r-devel/2014-February/068349.html [2] JottR blog post 'PERFORMANCE: captureOutput() is much faster than capture.output()', 2015-05-26. https://www.jottr.org/2014/05/26/captureoutput/
Internally, eval
() is used to evaluate the expression.
and capture.output
to capture the output.
# captureOutput() is much faster than capture.output() # for large outputs when capturing to a string. for (n in c(10e3, 20e3, 30e3, 40e3)) { printf("n=%d\n", n) x <- rnorm(n) t0 <- system.time({ bfr0 <- capture.output(print(x)) }) print(t0) t1 <- system.time({ bfr <- captureOutput(print(x)) }) print(t1) print(t1/t0) bfr2n <- captureOutput(print(x), collapse="\n") bfr2r <- captureOutput(print(x), collapse="\r") stopifnot(identical(bfr, bfr0)) } # for (n ...)
# captureOutput() is much faster than capture.output() # for large outputs when capturing to a string. for (n in c(10e3, 20e3, 30e3, 40e3)) { printf("n=%d\n", n) x <- rnorm(n) t0 <- system.time({ bfr0 <- capture.output(print(x)) }) print(t0) t1 <- system.time({ bfr <- captureOutput(print(x)) }) print(t1) print(t1/t0) bfr2n <- captureOutput(print(x), collapse="\n") bfr2r <- captureOutput(print(x), collapse="\r") stopifnot(identical(bfr, bfr0)) } # for (n ...)
Simple access to parsed command-line arguments.
cmdArgs(args=NULL, names=NULL, unique=TRUE, ..., .args=NULL) cmdArg(...)
cmdArgs(args=NULL, names=NULL, unique=TRUE, ..., .args=NULL) cmdArg(...)
args |
A named |
names |
A |
unique |
If |
... |
For |
.args |
(advanced/internal) A named |
cmdArgs()
returns a named list
with command-line arguments.
cmdArg()
return the value of the requested command-line argument.
The value of each command-line argument is returned as a character
string, unless an argument share name with ditto in the (optional)
arguments always
and default
in case the retrieved
value is coerced to that of the latter.
Finally, remaining character string command-line arguments are
coerced to numeric
s (via as.numeric
()), if possible,
that is unless the coerced value becomes NA
.
Henrik Bengtsson
Internally, commandArgs
() is used.
args <- cmdArgs() cat("User command-line arguments used when invoking R:\n") str(args) # Retrieve command line argument 'n', e.g. '-n 13' or '--n=13' n <- cmdArg("n", 42L) printf("Argument n=%d\n", n) # Short version doing the same n <- cmdArg(n=42L) printf("Argument n=%d\n", n)
args <- cmdArgs() cat("User command-line arguments used when invoking R:\n") str(args) # Retrieve command line argument 'n', e.g. '-n 13' or '--n=13' n <- cmdArg("n", 42L) printf("Argument n=%d\n", n) # Short version doing the same n <- cmdArg(n=42L) printf("Argument n=%d\n", n)
Creates a vector of column classes used for tabular reading based on a compact format string.
## Default S3 method: colClasses(fmt, ...)
## Default S3 method: colClasses(fmt, ...)
fmt |
A |
... |
Optional arguments for the |
Returns a vector
of character
strings.
Henrik Bengtsson
# All predefined types print(colClasses("-?cdfilnrzDP")) ## [1] "NULL" "NA" "character" "double" ## [5] "factor" "integer" "logical" "numeric" ## [9] "raw" "complex" "Date" "POSIXct" # A string in column 1, integers in column 4 and 5, rest skipped print(colClasses("c--ii----")) ## [1] "character" "NULL" "NULL" "integer" ## [5] "integer" "NULL" "NULL" "NULL" ## [9] "NULL" # Repeats and custom column classes c1 <- colClasses("3c{MyClass}3{foo}") print(c1) ## [1] "character" "character" "character" "MyClass" ## [5] "foo" "foo" "foo" # Passing repeats and class names using sprintf() syntax c2 <- colClasses("%dc{%s}%d{foo}", 3, "MyClass", 3) stopifnot(identical(c1, c2)) # Repeats of a vector of column classes c3 <- colClasses("3{MyClass,c}") print(c3) ## [1] "MyClass" "character" "MyClass" "character" ## [4] "MyClass" "character" # Large number repeats c4 <- colClasses("321{MyClass,c,i,d}") c5 <- rep(c("MyClass", "character", "integer", "double"), times=321) stopifnot(identical(c4, c5))
# All predefined types print(colClasses("-?cdfilnrzDP")) ## [1] "NULL" "NA" "character" "double" ## [5] "factor" "integer" "logical" "numeric" ## [9] "raw" "complex" "Date" "POSIXct" # A string in column 1, integers in column 4 and 5, rest skipped print(colClasses("c--ii----")) ## [1] "character" "NULL" "NULL" "integer" ## [5] "integer" "NULL" "NULL" "NULL" ## [9] "NULL" # Repeats and custom column classes c1 <- colClasses("3c{MyClass}3{foo}") print(c1) ## [1] "character" "character" "character" "MyClass" ## [5] "foo" "foo" "foo" # Passing repeats and class names using sprintf() syntax c2 <- colClasses("%dc{%s}%d{foo}", 3, "MyClass", 3) stopifnot(identical(c1, c2)) # Repeats of a vector of column classes c3 <- colClasses("3{MyClass,c}") print(c3) ## [1] "MyClass" "character" "MyClass" "character" ## [4] "MyClass" "character" # Large number repeats c4 <- colClasses("321{MyClass,c,i,d}") c5 <- rep(c("MyClass", "character", "integer", "double"), times=321) stopifnot(identical(c4, c5))
Compressing and decompressing files such as gzip:ed and bzip2:ed files.
NOTE: The default (remove=TRUE
) behavior is that
the input file is removed after that the output file
is fully created and closed.
## Default S3 method: compressFile(filename, destname=sprintf("%s.%s", filename, ext), ext, FUN, temporary=FALSE, skip=FALSE, overwrite=FALSE, remove=TRUE, BFR.SIZE=1e+07, ...) ## Default S3 method: decompressFile(filename, destname=gsub(sprintf("[.]%s$", ext), "", filename, ignore.case = TRUE), ext, FUN, temporary=FALSE, skip=FALSE, overwrite=FALSE, remove=TRUE, BFR.SIZE=1e+07, ...) ## Default S3 method: isCompressedFile(filename, method=c("extension", "content"), ext, fileClass, ...) ## Default S3 method: bzip2(filename, ..., ext="bz2", FUN=bzfile) ## Default S3 method: bunzip2(filename, ..., ext="bz2", FUN=bzfile) ## Default S3 method: gzip(filename, ..., ext="gz", FUN=gzfile) ## Default S3 method: gunzip(filename, ..., ext="gz", FUN=gzfile)
## Default S3 method: compressFile(filename, destname=sprintf("%s.%s", filename, ext), ext, FUN, temporary=FALSE, skip=FALSE, overwrite=FALSE, remove=TRUE, BFR.SIZE=1e+07, ...) ## Default S3 method: decompressFile(filename, destname=gsub(sprintf("[.]%s$", ext), "", filename, ignore.case = TRUE), ext, FUN, temporary=FALSE, skip=FALSE, overwrite=FALSE, remove=TRUE, BFR.SIZE=1e+07, ...) ## Default S3 method: isCompressedFile(filename, method=c("extension", "content"), ext, fileClass, ...) ## Default S3 method: bzip2(filename, ..., ext="bz2", FUN=bzfile) ## Default S3 method: bunzip2(filename, ..., ext="bz2", FUN=bzfile) ## Default S3 method: gzip(filename, ..., ext="gz", FUN=gzfile) ## Default S3 method: gunzip(filename, ..., ext="gz", FUN=gzfile)
filename |
Pathname of input file. |
destname |
Pathname of output file. |
temporary |
If |
skip |
If |
overwrite |
If |
remove |
If |
BFR.SIZE |
The number of bytes read in each chunk. |
... |
Passed to the underlying function or alternatively not used. |
method |
A |
ext , fileClass , FUN
|
(internal) Filename extension, file class,
and a connection |
Internally bzfile()
and gzfile()
(see connections
) are used to read (write) files.
If the process is interrupted before completed, the partially written
output file is automatically removed.
Returns the pathname of the output file. The number of bytes processed is returned as an attribute.
isCompressedFile()
, isGzipped()
and isBzipped()
return a logical
.
Note that with method = "extension"
(default), only the filename
extension is used to infer whether the file is compressed or not.
Specifically, it does not matter whether the file actually exists or not.
Henrik Bengtsson
## bzip2 cat(file="foo.txt", "Hello world!") print(isBzipped("foo.txt")) print(isBzipped("foo.txt.bz2")) bzip2("foo.txt") print(file.info("foo.txt.bz2")) print(isBzipped("foo.txt")) print(isBzipped("foo.txt.bz2")) bunzip2("foo.txt.bz2") print(file.info("foo.txt")) ## gzip cat(file="foo.txt", "Hello world!") print(isGzipped("foo.txt")) print(isGzipped("foo.txt.gz")) gzip("foo.txt") print(file.info("foo.txt.gz")) print(isGzipped("foo.txt")) print(isGzipped("foo.txt.gz")) gunzip("foo.txt.gz") print(file.info("foo.txt")) ## Cleanup file.remove("foo.txt")
## bzip2 cat(file="foo.txt", "Hello world!") print(isBzipped("foo.txt")) print(isBzipped("foo.txt.bz2")) bzip2("foo.txt") print(file.info("foo.txt.bz2")) print(isBzipped("foo.txt")) print(isBzipped("foo.txt.bz2")) bunzip2("foo.txt.bz2") print(file.info("foo.txt")) ## gzip cat(file="foo.txt", "Hello world!") print(isGzipped("foo.txt")) print(isGzipped("foo.txt.gz")) gzip("foo.txt") print(file.info("foo.txt.gz")) print(isGzipped("foo.txt")) print(isGzipped("foo.txt.gz")) gunzip("foo.txt.gz") print(file.info("foo.txt")) ## Cleanup file.remove("foo.txt")
Compresses a PDF (into a new PDF).
## Default S3 method: compressPDF(filename, path=NULL, outFilename=basename(pathname), outPath="compressedPDFs", skip=FALSE, overwrite=FALSE, compression="gs(ebook)+qpdf", ...)
## Default S3 method: compressPDF(filename, path=NULL, outFilename=basename(pathname), outPath="compressedPDFs", skip=FALSE, overwrite=FALSE, compression="gs(ebook)+qpdf", ...)
filename , path
|
The filename and (optional) path of the PDF to be compressed. |
outFilename , outPath
|
The generated PDF. |
skip |
If |
overwrite |
If |
compression |
A |
... |
Additional arguments passed to |
Returns the pathname of the generated PDF.
Henrik Bengtsson
Internally compactPDF
is utilized.
## Not run: pathnameZ <- compressPDF("report.pdf") ## End(Not run)
## Not run: pathnameZ <- compressPDF("report.pdf") ## End(Not run)
Copies a directory.
## Default S3 method: copyDirectory(from, to=".", ..., private=TRUE, recursive=TRUE)
## Default S3 method: copyDirectory(from, to=".", ..., private=TRUE, recursive=TRUE)
from |
The pathname of the source directory to be copied. |
to |
The pathname of the destination directory. |
... |
Additional arguments passed to
|
private |
If |
recursive |
If |
Note that this method does not use copyFile
() to
copy the files, but file.copy
().
Returns (invisibly) a character
vector
of pathnames copied.
Henrik Bengtsson
Counts the number of lines in a text file by counting the number of occurrences of platform-independent newlines (CR, LF, and CR+LF [1]), including a last line with neither. An empty file has zero lines.
## Default S3 method: countLines(file, chunkSize=5e+07, ...)
## Default S3 method: countLines(file, chunkSize=5e+07, ...)
file |
A |
chunkSize |
The number of bytes read in each chunk. |
... |
Not used. |
Both compressed and non-compressed files are supported.
Returns an non-negative integer
.
Henrik Bengtsson
[1] Page Newline, Wikipedia, July 2008. https://en.wikipedia.org/wiki/Newline
pathname <- system.file("NEWS.md", package="R.utils"); n <- countLines(pathname); n2 <- length(readLines(pathname)); stopifnot(n == n2);
pathname <- system.file("NEWS.md", package="R.utils"); n <- countLines(pathname); n2 <- length(readLines(pathname)); stopifnot(n == n2);
Creates a file atomically by first creating and writing to a temporary file which is then renamed.
## Default S3 method: createFileAtomically(filename, path=NULL, FUN, ..., skip=FALSE, overwrite=FALSE, backup=TRUE, verbose=FALSE)
## Default S3 method: createFileAtomically(filename, path=NULL, FUN, ..., skip=FALSE, overwrite=FALSE, backup=TRUE, verbose=FALSE)
filename |
The filename of the file to create. |
path |
The path to the file. |
FUN |
A |
... |
Additional arguments passed to |
skip |
If |
overwrite |
If |
backup |
If |
verbose |
Returns (invisibly) the pathname.
Henrik Bengtsson
Internally,
pushTemporaryFile
() and popTemporaryFile
() are used for
working toward a temporary file, and
pushBackupFile
() and popBackupFile
() are used for backing up
and restoring already existing file.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Create a file atomically # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - n <- 10 pathname <- createFileAtomically("foobar.txt", path=tempdir(), FUN=function(pathname) { cat(file=pathname, "This file was created atomically.\n") cat(file=pathname, "Timestamp: ", as.character(Sys.time()), "\n", sep="") for (kk in 1:n) { cat(file=pathname, kk, "\n", append=TRUE) # Emulate a slow process if (interactive()) Sys.sleep(0.1) } cat(file=pathname, "END OF FILE\n", append=TRUE) }, overwrite=TRUE) bfr <- readLines(pathname) cat(bfr, sep="\n") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Overwrite the file atomically (emulate write failure) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - tryCatch({ pathname <- createFileAtomically("foobar.txt", path=tempdir(), FUN=function(pathname) { cat(file=pathname, "Trying to create a new file.\n") cat(file=pathname, "Writing a bit, but then an error...\n", append=TRUE) # Emulate write error stop("An error occured while writing to the new file.") cat(file=pathname, "END OF FILE\n", append=TRUE) }, overwrite=TRUE) }, error = function(ex) { print(ex$message) }) # The original file was never overwritten bfr2 <- readLines(pathname) cat(bfr2, sep="\n") stopifnot(identical(bfr2, bfr)) # The partially temporary file remains pathnameT <- sprintf("%s.tmp", pathname) stopifnot(isFile(pathnameT)) bfr3 <- readLines(pathnameT) cat(bfr3, sep="\n") file.remove(pathnameT) file.remove(pathname)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Create a file atomically # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - n <- 10 pathname <- createFileAtomically("foobar.txt", path=tempdir(), FUN=function(pathname) { cat(file=pathname, "This file was created atomically.\n") cat(file=pathname, "Timestamp: ", as.character(Sys.time()), "\n", sep="") for (kk in 1:n) { cat(file=pathname, kk, "\n", append=TRUE) # Emulate a slow process if (interactive()) Sys.sleep(0.1) } cat(file=pathname, "END OF FILE\n", append=TRUE) }, overwrite=TRUE) bfr <- readLines(pathname) cat(bfr, sep="\n") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Overwrite the file atomically (emulate write failure) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - tryCatch({ pathname <- createFileAtomically("foobar.txt", path=tempdir(), FUN=function(pathname) { cat(file=pathname, "Trying to create a new file.\n") cat(file=pathname, "Writing a bit, but then an error...\n", append=TRUE) # Emulate write error stop("An error occured while writing to the new file.") cat(file=pathname, "END OF FILE\n", append=TRUE) }, overwrite=TRUE) }, error = function(ex) { print(ex$message) }) # The original file was never overwritten bfr2 <- readLines(pathname) cat(bfr2, sep="\n") stopifnot(identical(bfr2, bfr)) # The partially temporary file remains pathnameT <- sprintf("%s.tmp", pathname) stopifnot(isFile(pathnameT)) bfr3 <- readLines(pathnameT) cat(bfr3, sep="\n") file.remove(pathnameT) file.remove(pathname)
Creates a link to a file or a directory. This method tries to create a link to a file/directory on the file system, e.g. a symbolic link and Windows Shortcut links. It depends on operating and file system (and argument settings), which type of link is finally created, but all this is hidden internally so that links can be created the same way regardless of system.
## Default S3 method: createLink(link=".", target, skip=!overwrite, overwrite=FALSE, methods=getOption("createLink/args/methods", c("unix-symlink", "windows-ntfs-symlink", "windows-shortcut")), ...)
## Default S3 method: createLink(link=".", target, skip=!overwrite, overwrite=FALSE, methods=getOption("createLink/args/methods", c("unix-symlink", "windows-ntfs-symlink", "windows-shortcut")), ...)
link |
The path or pathname of the link to be created.
If |
target |
The target file or directory to which the shortcut should point to. |
skip |
If |
overwrite |
If |
methods |
A |
... |
Not used. |
Returns (invisibly) the path or pathname to the link.
If no link was created, NULL
is returned.
In order for method="unix-symlink"
(utilizing
file.symlink()
),
method="windows-ntfs-symlink"
(utilizing executable mklink
),
and/or method="windows-shortcut"
(utilizing
createWindowsShortcut
()) to succeed on Windows,
the client/R session must run with sufficient privileges
(it has been reported that Administrative rights are necessary).
Henrik Bengtsson
Ben Garrett, Windows File Junctions, Symbolic Links and Hard Links,
September 2009 [https://devtidbits.com/2009/09/07/windows-file-junctions-symbolic-links-and-hard-links/]
createWindowsShortcut
() and
file.symlink()
Creates a Microsoft Windows Shortcut (.lnk file).
## Default S3 method: createWindowsShortcut(pathname, target, overwrite=FALSE, mustWork=FALSE, ...)
## Default S3 method: createWindowsShortcut(pathname, target, overwrite=FALSE, mustWork=FALSE, ...)
pathname |
The pathname (with file extension *.lnk) of the link file to be created. |
target |
The target file or directory to which the shortcut should point to. |
overwrite |
If |
mustWork |
If |
... |
Not used. |
Returns (invisibly) the pathname.
In order for this method, which utilizes Windows Script Host a VBScript, to succeed on Windows, the client/R session must run with sufficient privileges (it has been reported that Administrative rights are necessary).
Henrik Bengtsson
[1] Create a windows shortcut (.LNK file), SS64.com,
https://ss64.com/nt/shortcut.html
# Create Windows Shortcut links to a directory and a file targets <- list( system.file(package="R.utils"), system.file("DESCRIPTION", package="R.utils") ) for (kk in seq_along(targets)) { cat("Link #", kk, "\n", sep="") target <- targets[[kk]] cat("Target: ", target, "\n", sep="") # Name of *.lnk file pathname <- sprintf("%s.LNK", tempfile()) tryCatch({ # Will only work on Windows systems with support for VB scripting createWindowsShortcut(pathname, target=target) }, error = function(ex) { print(ex) }) # Was it created? if (isFile(pathname)) { cat("Created link file: ", pathname, "\n", sep="") # Validate that it points to the correct target dest <- filePath(pathname, expandLinks="any") cat("Available target: ", dest, "\n", sep="") res <- all.equal(tolower(dest), tolower(target)) if (!isTRUE(res)) { msg <- sprintf("Link target does not match expected target: %s != %s", dest, target) cat(msg, "\n") warning(msg) } # Cleanup file.remove(pathname) } }
# Create Windows Shortcut links to a directory and a file targets <- list( system.file(package="R.utils"), system.file("DESCRIPTION", package="R.utils") ) for (kk in seq_along(targets)) { cat("Link #", kk, "\n", sep="") target <- targets[[kk]] cat("Target: ", target, "\n", sep="") # Name of *.lnk file pathname <- sprintf("%s.LNK", tempfile()) tryCatch({ # Will only work on Windows systems with support for VB scripting createWindowsShortcut(pathname, target=target) }, error = function(ex) { print(ex) }) # Was it created? if (isFile(pathname)) { cat("Created link file: ", pathname, "\n", sep="") # Validate that it points to the correct target dest <- filePath(pathname, expandLinks="any") cat("Available target: ", dest, "\n", sep="") res <- all.equal(tolower(dest), tolower(target)) if (!isTRUE(res)) { msg <- sprintf("Link target does not match expected target: %s != %s", dest, target) cat(msg, "\n") warning(msg) } # Cleanup file.remove(pathname) } }
Allocates a data frame with given column classes.
## Default S3 method: dataFrame(colClasses, nrow=1, ...)
## Default S3 method: dataFrame(colClasses, nrow=1, ...)
colClasses |
A |
nrow |
An |
... |
Not used. |
Returns an NxK data.frame
where N equals nrow
and
K equals length(colClasses)
.
df <- dataFrame(colClasses=c(a="integer", b="double"), nrow=10) df[,1] <- sample(1:nrow(df)) df[,2] <- rnorm(nrow(df)) print(df)
df <- dataFrame(colClasses=c(a="integer", b="double"), nrow=10) df[,1] <- sample(1:nrow(df)) df[,2] <- rnorm(nrow(df)) print(df)
Detaches packages by name, if loaded.
## Default S3 method: detachPackage(pkgname, ...)
## Default S3 method: detachPackage(pkgname, ...)
pkgname |
|
... |
Not used. |
Returns (invisibly) a named logical
vector
indicating whether
each package was detached or not.
Henrik Bengtsson
detach
().
Sets the dimension of an object with the option to infer one dimension automatically.
If one of the elements in the dimension vector
is NA
, then its value
is inferred from the length of the object and the other elements in the
dimension vector. If the inferred dimension is not an integer
, an
error is thrown.
## Default S3 replacement method: dimNA(x) <- value
## Default S3 replacement method: dimNA(x) <- value
x |
An R object. |
value |
Returns (invisibly) what dim<-()
returns
(see dim
() for more details).
Henrik Bengtsson
dim
().
x <- 1:12 dimNA(x) <- c(2,NA,3) stopifnot(dim(x) == as.integer(c(2,2,3)))
x <- 1:12 dimNA(x) <- c(2,NA,3) stopifnot(dim(x) == as.integer(c(2,2,3)))
Displays the contents of a text file with line numbers and more.
## Default S3 method: displayCode(con=NULL, code=NULL, numerate=TRUE, lines=-1, wrap=79, highlight=NULL, pager=getOption("pager"), ...)
## Default S3 method: displayCode(con=NULL, code=NULL, numerate=TRUE, lines=-1, wrap=79, highlight=NULL, pager=getOption("pager"), ...)
con |
A |
code |
|
numerate |
If |
lines |
If a single |
wrap |
The (output) column |
highlight |
A |
pager |
If |
... |
Additional arguments passed to |
Returns (invisibly) the formatted code as a character
string.
Henrik Bengtsson
file.show
().
file <- system.file("DESCRIPTION", package="R.utils") cat("Displaying: ", file, ":\n", sep="") displayCode(file) file <- system.file("NEWS.md", package="R.utils") cat("Displaying: ", file, ":\n", sep="") displayCode(file, numerate=FALSE, lines=100:110, wrap=65) file <- system.file("NEWS.md", package="R.utils") cat("Displaying: ", file, ":\n", sep="") displayCode(file, lines=100:110, wrap=65, highlight=c(101,104:108))
file <- system.file("DESCRIPTION", package="R.utils") cat("Displaying: ", file, ":\n", sep="") displayCode(file) file <- system.file("NEWS.md", package="R.utils") cat("Displaying: ", file, ":\n", sep="") displayCode(file, numerate=FALSE, lines=100:110, wrap=65) file <- system.file("NEWS.md", package="R.utils") cat("Displaying: ", file, ":\n", sep="") displayCode(file, lines=100:110, wrap=65, highlight=c(101,104:108))
Executes a function call with option to ignore unused arguments.
## Default S3 method: doCall(.fcn, ..., args=NULL, alwaysArgs=NULL, .functions=list(.fcn), .ignoreUnusedArgs=TRUE, envir=parent.frame())
## Default S3 method: doCall(.fcn, ..., args=NULL, alwaysArgs=NULL, .functions=list(.fcn), .ignoreUnusedArgs=TRUE, envir=parent.frame())
.fcn |
A |
... |
Named arguments to be passed to the function. |
args |
A |
alwaysArgs |
A |
.functions |
A |
.ignoreUnusedArgs |
If |
envir |
An |
Henrik Bengtsson
do.call
().
doCall("plot", x=1:10, y=sin(1:10), col="red", dummyArg=54, alwaysArgs=list(xlab="x", ylab="y"), .functions=c("plot", "plot.xy"))
doCall("plot", x=1:10, y=sin(1:10), col="red", dummyArg=54, alwaysArgs=list(xlab="x", ylab="y"), .functions=c("plot", "plot.xy"))
Downloads a file.
## S3 method for class 'character' downloadFile(url, filename=basename(url), path=NULL, skip=TRUE, overwrite=!skip, ..., username=NULL, password=NULL, binary=TRUE, dropEmpty=TRUE, verbose=FALSE)
## S3 method for class 'character' downloadFile(url, filename=basename(url), path=NULL, skip=TRUE, overwrite=!skip, ..., username=NULL, password=NULL, binary=TRUE, dropEmpty=TRUE, verbose=FALSE)
url |
A |
filename , path
|
(optional) |
skip |
If |
overwrite |
If |
... |
Additional arguments passed to |
username , password
|
|
binary |
If |
dropEmpty |
If |
verbose |
Currently arguments username
and password
are only used
for downloads via URL protocol 'https'. The 'https' protocol requires
that either of 'curl' or 'wget' are available on the system.
Returns the local pathname to the downloaded filename,
or NULL
if no file was downloaded.
Henrik Bengtsson
Internally download.file
is used.
That function may generate an empty file if the URL is not available.
## Not run: pathname <- downloadFile("https://www.r-project.org/index.html", path="www.r-project.org/") print(pathname) ## End(Not run)
## Not run: pathname <- downloadFile("https://www.r-project.org/index.html", path="www.r-project.org/") print(pathname) ## End(Not run)
Global substitute of expression using regular expressions.
egsub(pattern, replacement, x, ..., value=TRUE, envir=parent.frame(), inherits=TRUE)
egsub(pattern, replacement, x, ..., value=TRUE, envir=parent.frame(), inherits=TRUE)
pattern |
A |
replacement |
A |
x |
The |
... |
Additional arguments passed to |
value |
If |
envir , inherits
|
An |
Returns an expression
.
Henrik Bengtsson
# Original expression expr <- substitute({ res <- foo.bar.yaa(2) print(res) R.utils::use("R.oo") x <- .b. }) # Some predefined objects foo.bar.yaa <- function(x) str(x) a <- 2 b <- a # Substitute with variable name expr2 <- egsub("^[.]([a-zA-Z0-9_.]+)[.]$", "\\1", expr, value=FALSE) print(expr2) ## { ## res <- foo.bar.yaa(2) ## print(res) ## R.utils::use("R.oo") ## x <- b ## } # Substitute with variable value expr3 <- egsub("^[.]([a-zA-Z0-9_.]+)[.]$", "\\1", expr, value=TRUE) print(expr3) ## { ## res <- foo.bar.yaa(2) ## print(res) ## R.utils::use("R.oo") ## x <- 2 ## } # Substitute the body of a function warnifnot <- egsub("stop", "warning", stopifnot, value=FALSE) print(warnifnot) warnifnot(pi == 3.14)
# Original expression expr <- substitute({ res <- foo.bar.yaa(2) print(res) R.utils::use("R.oo") x <- .b. }) # Some predefined objects foo.bar.yaa <- function(x) str(x) a <- 2 b <- a # Substitute with variable name expr2 <- egsub("^[.]([a-zA-Z0-9_.]+)[.]$", "\\1", expr, value=FALSE) print(expr2) ## { ## res <- foo.bar.yaa(2) ## print(res) ## R.utils::use("R.oo") ## x <- b ## } # Substitute with variable value expr3 <- egsub("^[.]([a-zA-Z0-9_.]+)[.]$", "\\1", expr, value=TRUE) print(expr3) ## { ## res <- foo.bar.yaa(2) ## print(res) ## R.utils::use("R.oo") ## x <- 2 ## } # Substitute the body of a function warnifnot <- egsub("stop", "warning", stopifnot, value=FALSE) print(warnifnot) warnifnot(pi == 3.14)
Creates a new environment, evaluates an expression therein, and returns the environment.
env(..., hash=FALSE, parent=parent.frame(), size=29L)
env(..., hash=FALSE, parent=parent.frame(), size=29L)
... |
Arguments passed to |
hash , parent , size
|
Arguments passed to |
Returns an environment
.
Henrik Bengtsson
[1] R-devel thread 'Create an environment and assign objects to it in
one go?' on March 9-10, 2011.
Internally new.env
() and evalq
() are used.
x <- list(); x$case1 <- env({ # Cut'n'pasted from elsewhere a <- 1; b <- 2; }); x$case2 <- env({ # Cut'n'pasted from elsewhere foo <- function(x) x^2; a <- foo(2); b <- 1; rm(foo); # Not needed anymore }); # Turn into a list of lists x <- lapply(x, FUN=as.list); str(x);
x <- list(); x$case1 <- env({ # Cut'n'pasted from elsewhere a <- 1; b <- 2; }); x$case2 <- env({ # Cut'n'pasted from elsewhere foo <- function(x) x^2; a <- foo(2); b <- 1; rm(foo); # Not needed anymore }); # Turn into a list of lists x <- lapply(x, FUN=as.list); str(x);
Extract a subset of an array, matrix or a vector with unknown dimensions.
This method is useful when you do not know the number of dimensions of the object your wish to extract values from, cf. example.
## S3 method for class 'array' extract(x, ..., indices=list(...), dims=names(indices), drop=FALSE)
## S3 method for class 'array' extract(x, ..., indices=list(...), dims=names(indices), drop=FALSE)
x |
|
... |
These arguments are by default put into the
|
indices |
|
dims |
An |
drop |
If |
Returns an array
.
Henrik Bengtsson
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Example using an array with a random number of dimensions # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - maxdim <- 4 dim <- sample(3:maxdim, size=sample(2:maxdim, size=1), replace=TRUE) ndim <- length(dim) dimnames <- list() for (kk in 1:ndim) dimnames[[kk]] <- sprintf("%s%d", letters[kk], 1:dim[kk]) x <- 1:prod(dim) x <- array(x, dim=dim, dimnames=dimnames) cat("\nArray 'x':\n") print(x) cat("\nExtract 'x[2:3,...]':\n") print(extract(x, "1"=2:3)) cat("\nExtract 'x[3,2:3,...]':\n") print(extract(x, "1"=3,"2"=2:3)) cat("\nExtract 'x[...,2:3]':\n") print(extract(x, indices=2:3, dims=length(dim(x)))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Assertions # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - y <- array(1:24, dim=c(2,3,4)) yA <- y[,,2:3] yB <- extract(y, indices=list(2:3), dims=length(dim(y))) stopifnot(identical(yB, yA)) yA <- y[,2:3,2] yB <- extract(y, indices=list(2:3,2), dims=c(2,3), drop=TRUE) stopifnot(identical(yB, yA))
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Example using an array with a random number of dimensions # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - maxdim <- 4 dim <- sample(3:maxdim, size=sample(2:maxdim, size=1), replace=TRUE) ndim <- length(dim) dimnames <- list() for (kk in 1:ndim) dimnames[[kk]] <- sprintf("%s%d", letters[kk], 1:dim[kk]) x <- 1:prod(dim) x <- array(x, dim=dim, dimnames=dimnames) cat("\nArray 'x':\n") print(x) cat("\nExtract 'x[2:3,...]':\n") print(extract(x, "1"=2:3)) cat("\nExtract 'x[3,2:3,...]':\n") print(extract(x, "1"=3,"2"=2:3)) cat("\nExtract 'x[...,2:3]':\n") print(extract(x, indices=2:3, dims=length(dim(x)))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Assertions # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - y <- array(1:24, dim=c(2,3,4)) yA <- y[,,2:3] yB <- extract(y, indices=list(2:3), dims=length(dim(y))) stopifnot(identical(yB, yA)) yA <- y[,2:3,2] yB <- extract(y, indices=list(2:3,2), dims=c(2,3), drop=TRUE) stopifnot(identical(yB, yA))
Checks the permission of a file or a directory.
## Default S3 method: fileAccess(pathname, mode=0, safe=TRUE, ...)
## Default S3 method: fileAccess(pathname, mode=0, safe=TRUE, ...)
pathname |
A |
mode |
An |
safe |
If |
... |
Not used. |
In R there is file.access
() for checking whether the
permission of a file.
Unfortunately, that function cannot be 100% trusted depending on
platform used and file system queried, cf. [1].
Returns an integer
; 0 if the permission exists, -1 if not.
This function follows symbolic links (also on Windows) and returns a value based on the link target (rather than the link itself).
Henrik Bengtsson
[1] R-devel thread
file.access() on network (mounted) drive on Windows Vista?
on Nov 26, 2008.
https://stat.ethz.ch/pipermail/r-devel/2008-December/051461.html
[2] Filesystem permissions, Wikipedia, 2010.
https://en.wikipedia.org/wiki/Filesystem_permissions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Current directory # - - - - - - - - - - - - - - - - - - - - - - - - - - - - path <- "." # Test for existence print(fileAccess(path, mode=0)) # Test for execute permission print(fileAccess(path, mode=1)) # Test for write permission print(fileAccess(path, mode=2)) # Test for read permission print(fileAccess(path, mode=4)) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - # A temporary file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - pathname <- tempfile() cat(file=pathname, "Hello world!") # Test for existence print(fileAccess(pathname, mode=0)) # Test for execute permission print(fileAccess(pathname, mode=1)) # Test for write permission print(fileAccess(pathname, mode=2)) # Test for read permission print(fileAccess(pathname, mode=4)) file.remove(pathname) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - # The 'base' package directory # - - - - - - - - - - - - - - - - - - - - - - - - - - - - path <- system.file(package="base") # Test for existence print(fileAccess(path, mode=0)) # Test for execute permission print(fileAccess(path, mode=1)) # Test for write permission print(fileAccess(path, mode=2)) # Test for read permission print(fileAccess(path, mode=4)) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - # The 'base' package DESCRIPTION file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - pathname <- system.file("DESCRIPTION", package="base") # Test for existence print(fileAccess(pathname, mode=0)) # Test for execute permission print(fileAccess(pathname, mode=1)) # Test for write permission print(fileAccess(pathname, mode=2)) # Test for read permission print(fileAccess(pathname, mode=4))
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Current directory # - - - - - - - - - - - - - - - - - - - - - - - - - - - - path <- "." # Test for existence print(fileAccess(path, mode=0)) # Test for execute permission print(fileAccess(path, mode=1)) # Test for write permission print(fileAccess(path, mode=2)) # Test for read permission print(fileAccess(path, mode=4)) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - # A temporary file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - pathname <- tempfile() cat(file=pathname, "Hello world!") # Test for existence print(fileAccess(pathname, mode=0)) # Test for execute permission print(fileAccess(pathname, mode=1)) # Test for write permission print(fileAccess(pathname, mode=2)) # Test for read permission print(fileAccess(pathname, mode=4)) file.remove(pathname) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - # The 'base' package directory # - - - - - - - - - - - - - - - - - - - - - - - - - - - - path <- system.file(package="base") # Test for existence print(fileAccess(path, mode=0)) # Test for execute permission print(fileAccess(path, mode=1)) # Test for write permission print(fileAccess(path, mode=2)) # Test for read permission print(fileAccess(path, mode=4)) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - # The 'base' package DESCRIPTION file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - pathname <- system.file("DESCRIPTION", package="base") # Test for existence print(fileAccess(pathname, mode=0)) # Test for execute permission print(fileAccess(pathname, mode=1)) # Test for write permission print(fileAccess(pathname, mode=2)) # Test for read permission print(fileAccess(pathname, mode=4))
Construct the path to a file from components and expands Windows Shortcuts along the pathname from root to leaf. This function is backward compatible with
file.path
() when argument removeUps=FALSE
and
expandLinks="none"
, except that a (character) NA
is
return if any argument is NA.
This function exists on all platforms, not only Windows systems.
## Default S3 method: filePath(..., fsep=.Platform$file.sep, removeUps=TRUE, expandLinks=c("none", "any", "local", "relative", "network"), unmap=FALSE, mustExist=FALSE, verbose=FALSE)
## Default S3 method: filePath(..., fsep=.Platform$file.sep, removeUps=TRUE, expandLinks=c("none", "any", "local", "relative", "network"), unmap=FALSE, mustExist=FALSE, verbose=FALSE)
... |
Arguments to be pasted together to a file path and then be
parsed from the root to the leaf where Windows shortcut files are
recognized and expanded according to argument |
fsep |
the path separator to use. |
removeUps |
If |
expandLinks |
A |
unmap |
If |
mustExist |
If |
verbose |
If |
If expandLinks != "none"
, each component, call it parent,
in the absolute path is processed from the left to the right as follows:
1. If a "real" directory of name parent exists, it is followed.
2. Otherwise, if Microsoft Windows Shortcut file with name
parent.lnk exists, it is read. If its local target exists, that
is followed, otherwise its network target is followed.
3. If no valid existing directory was found in (1) or (2), the expanded
this far followed by the rest of the pathname is returned quietly.
4. If all of the absolute path was expanded successfully the expanded
absolute path is returned.
Returns a character
string.
Internal file.exists()
is call while expanding the pathname.
This is used to check if there exists a Windows shortcut file named
'foo.lnk' in 'path/foo/bar'. If it does, 'foo.lnk' has to be followed,
and in other cases 'foo' is ordinary directory.
The file.exists()
is unfortunately a bit slow, which is why
this function appears slow if called many times.
Henrik Bengtsson
readWindowsShellLink
().
readWindowsShortcut
().
file.path
().
# Default print(file.path("foo", "bar", "..", "name")) # "foo/bar/../name" # Shorten pathname, if possible print(filePath("foo", "bar", "..", "name")) # "foo/name" print(filePath("foo/bar/../name")) # "foo/name" # Recognize Windows Shortcut files along the path, cf. Unix soft links filename <- system.file("data-ex/HISTORY.LNK", package="R.utils") print(filename) filename <- filePath(filename, expandLinks="relative") print(filename)
# Default print(file.path("foo", "bar", "..", "name")) # "foo/bar/../name" # Shorten pathname, if possible print(filePath("foo", "bar", "..", "name")) # "foo/name" print(filePath("foo/bar/../name")) # "foo/name" # Recognize Windows Shortcut files along the path, cf. Unix soft links filename <- system.file("data-ex/HISTORY.LNK", package="R.utils") print(filename) filename <- filePath(filename, expandLinks="relative") print(filename)
Package: R.utils
Class FileProgressBar
Object
~~|
~~+--
ProgressBar
~~~~~~~|
~~~~~~~+--
FileProgressBar
Directly known subclasses:
public static class FileProgressBar
extends ProgressBar
FileProgressBar(pathname=NULL, ...)
FileProgressBar(pathname=NULL, ...)
pathname |
The pathname of the output file. |
... |
Other arguments accepted by the |
A progress bar that sets the size of a file accordingly. This class useful to check the progress of a batch job by just querying the size of a file, for instance, via ftp.
Methods:
cleanup |
- | |
update |
- | |
Methods inherited from ProgressBar:
as.character, getBarString, increase, isDone, reset, setMaxValue, setProgress, setStepLength, setTicks, setValue, update
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
## Not run: # Creates a progress bar (of length 100) that displays it self as a file. pb <- FileProgressBar(file.path(tempdir(), "progress.simulation"), max = 10L) reset(pb) while (!isDone(pb)) { x <- rnorm(3e4) increase(pb) # Emulate a slow process if (interactive()) Sys.sleep(0.1) cat(sprintf("File size: %d bytes\n", file.info(pb$pathname)$size)) Sys.sleep(0.01) } ## End(Not run)
## Not run: # Creates a progress bar (of length 100) that displays it self as a file. pb <- FileProgressBar(file.path(tempdir(), "progress.simulation"), max = 10L) reset(pb) while (!isDone(pb)) { x <- rnorm(3e4) increase(pb) # Emulate a slow process if (interactive()) Sys.sleep(0.1) cat(sprintf("File size: %d bytes\n", file.info(pb$pathname)$size)) Sys.sleep(0.01) } ## End(Not run)
Function to call for finalizing the R session. When called, all registered "onSessionExit" hooks
(functions) are called. To define such hooks, use the
onSessionExit
() function.
This method should not be used by the user.
## Default S3 method: finalizeSession(...)
## Default S3 method: finalizeSession(...)
... |
Not used. |
Returns (invisibly) the hooks successfully called.
Henrik Bengtsson
Finds all 'srcfile' objects generated by source() in all call frames. This makes it possible to find out which files are
currently scripted by source
().
## Default S3 method: findSourceTraceback(...)
## Default S3 method: findSourceTraceback(...)
... |
Not used. |
Returns a named list of srcfile
() objects and/or
character
strings.
The names of the list entries corresponds to the 'filename'
value of each corresponding 'srcfile' object.
The returned list is empty if source
() was not called.
Henrik Bengtsson
See also sourceutils
.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Create two R script files where one source():s the other # and both lists the traceback of filenames source():d. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - path <- tempdir() pathnameA <- Arguments$getWritablePathname("foo.R", path=path) pathnameB <- Arguments$getWritablePathname("bar.R", path=path) code <- 'cat("BEGIN foo.R\n")' code <- c(code, 'print(findSourceTraceback());') code <- c(code, sprintf('source("%s");', pathnameB)) code <- c(code, 'cat("END foo.R\n")') code <- paste(code, collapse="\n") cat(file=pathnameA, code) code <- 'cat("BEGIN bar.R\n")' code <- c(code, 'x <- findSourceTraceback();') code <- c(code, 'print(x);') code <- c(code, 'cat("END bar.R\n")') code <- paste(code, collapse="\n") cat(file=pathnameB, code) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Source the first file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - source(pathnameA, echo=TRUE)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Create two R script files where one source():s the other # and both lists the traceback of filenames source():d. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - path <- tempdir() pathnameA <- Arguments$getWritablePathname("foo.R", path=path) pathnameB <- Arguments$getWritablePathname("bar.R", path=path) code <- 'cat("BEGIN foo.R\n")' code <- c(code, 'print(findSourceTraceback());') code <- c(code, sprintf('source("%s");', pathnameB)) code <- c(code, 'cat("END foo.R\n")') code <- paste(code, collapse="\n") cat(file=pathnameA, code) code <- 'cat("BEGIN bar.R\n")' code <- c(code, 'x <- findSourceTraceback();') code <- c(code, 'print(x);') code <- c(code, 'cat("END bar.R\n")') code <- paste(code, collapse="\n") cat(file=pathnameB, code) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Source the first file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - source(pathnameA, echo=TRUE)
Converts a binary/octal/hexadecimal number into a string.
## S3 method for class 'binmode' format(x, ...)
## S3 method for class 'binmode' format(x, ...)
x |
Object to be converted. |
... |
Not used. |
Returns a character
.
Henrik Bengtsson
format.octmode()
, cf. octmode
.
intToBin
() (incl. intToOct()
and intToHex()
).
Parses, evaluates and outputs a GString.
## Default S3 method: gcat(..., file="", append=FALSE, envir=parent.frame())
## Default S3 method: gcat(..., file="", append=FALSE, envir=parent.frame())
... |
|
file |
A |
append |
Only applied if |
envir |
The |
Returns (invisibly) a character
string.
Henrik Bengtsson
gstring
().
Identifies and removes DLLs of packages already unloaded. When packages are unloaded, they are ideally also unloading any DLLs (also known as a dynamic shared object or library) they have loaded. Unfortunately, not all package do this resulting in "stray" DLLs still being loaded and occupying R's limited registry. These functions identifies and removes such DLLs.
gcDLLs(gc=TRUE, quiet=TRUE)
gcDLLs(gc=TRUE, quiet=TRUE)
gc |
If |
quiet |
If |
If a library fails to unload, an informative warning is generated.
Returns (invisibly) the set of stray DLLs identified.
To unload a package DLL whenever the package in unloaded, add the following to your package:
.onUnload <- function(libpath) { ## (1) Force finalizers to be called before removing the DLL ## in case some of them need the DLL. gc() ## (2) Unload the DLL for this package library.dynam.unload(.packageName, libpath) }
Henrik Bengtsson
Gets the absolute pathname string.
## Default S3 method: getAbsolutePath(pathname, workDirectory=getwd(), expandTilde=FALSE, ...)
## Default S3 method: getAbsolutePath(pathname, workDirectory=getwd(), expandTilde=FALSE, ...)
pathname |
A |
workDirectory |
A |
expandTilde |
If |
... |
Not used. |
This method will replace replicated slashes ('/') with a single one, except for the double forward slashes prefixing a Microsoft Windows UNC (Universal Naming Convention) pathname.
Returns a character
string of the absolute pathname.
Henrik Bengtsson
Gets the string of the parent specified by this pathname. This is basically, by default the string before the last path separator of the absolute pathname.
## Default S3 method: getParent(pathname, depth=1L, fsep=.Platform$file.sep, ...)
## Default S3 method: getParent(pathname, depth=1L, fsep=.Platform$file.sep, ...)
pathname |
A |
depth |
An |
fsep |
A |
... |
Not used. |
Returns a character
string if the parent exists, otherwise NULL
.
Henrik Bengtsson
Gets the relative pathname relative to a directory.
## Default S3 method: getRelativePath(pathname, relativeTo=getwd(), caseSensitive=NULL, ...)
## Default S3 method: getRelativePath(pathname, relativeTo=getwd(), caseSensitive=NULL, ...)
pathname |
A |
relativeTo |
A |
caseSensitive |
If |
... |
Not used. |
In case the two paths are on different file systems, for instance,
C:/foo/bar/ and D:/foo/, the method returns pathname
as is.
Returns a character
string of the relative pathname.
If caseSensitive == NULL
, the relative path is used to decide if
the comparison should be done in a case-sensitive mode or not.
The current check is if it is a Windows path or not, that is, if
the relative path starts with a device letter, then the comparison
is non-case sensitive.
Henrik Bengtsson
getAbsolutePath
().
isAbsolutePath
().
getRelativePath("foo", "foo") # "." getRelativePath("foo/bar", "foo") # "bar" getRelativePath("foo/bar", "foo/bar/yah") # ".." getRelativePath("foo/bar/cool", "foo/bar/yah/sub/") # "../../cool" getRelativePath("/tmp/bar/", "/bar/foo/") # "../../tmp/bar" # Windows getRelativePath("C:/foo/bar/", "C:/bar/") # "../foo/bar" getRelativePath("C:/foo/bar/", "D:/bar/") # "C:/foo/bar"
getRelativePath("foo", "foo") # "." getRelativePath("foo/bar", "foo") # "bar" getRelativePath("foo/bar", "foo/bar/yah") # ".." getRelativePath("foo/bar/cool", "foo/bar/yah/sub/") # "../../cool" getRelativePath("/tmp/bar/", "/bar/foo/") # "../../tmp/bar" # Windows getRelativePath("C:/foo/bar/", "C:/bar/") # "../foo/bar" getRelativePath("C:/foo/bar/", "D:/bar/") # "C:/foo/bar"
Parses and evaluates a GString into a regular string.
## Default S3 method: gstring(..., file=NULL, path=NULL, envir=parent.frame())
## Default S3 method: gstring(..., file=NULL, path=NULL, envir=parent.frame())
... |
|
file , path
|
Alternatively, a file, a URL or a |
envir |
The |
Returns a character
string.
Henrik Bengtsson
gcat
().
Package: R.utils
Class GString
character
~~|
~~+--
GString
Directly known subclasses:
public static class GString
extends character
GString(..., sep="")
GString(..., sep="")
... |
one or more objects, to be coerced to |
sep |
A |
Methods:
as.character |
- | |
evaluate |
- | |
gcat |
- | |
getBuiltinDate |
- | |
getBuiltinDatetime |
- | |
getBuiltinHostname |
- | |
getBuiltinOs |
- | |
getBuiltinPid |
- | |
getBuiltinRhome |
- | |
getBuiltinRversion |
- | |
getBuiltinTime |
- | |
getBuiltinUsername |
- | |
getRaw |
- | |
getVariableValue |
- | |
gstring |
- | |
parse |
- | |
print |
- | |
Methods inherited from character:
Ops,nonStructure,vector-method, Ops,structure,vector-method, Ops,vector,nonStructure-method, Ops,vector,structure-method, all.equal, as.Date, as.POSIXlt, as.data.frame, as.raster, coerce,ANY,character-method, coerce,character,SuperClassMethod-method, coerce,character,signature-method, coerce<-,ObjectsWithPackage,character-method, coerce<-,signature,character-method, downloadFile, formula, getDLLRegisteredRoutines, glyphJust, isOpen, makeRaw, sha1, toAsciiRegExprPattern, toFileListTree, toLatex, uses
Henrik Bengtsson
For convenience, see functions gstring
() and gcat
().
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # First example # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - who <- "world" # Compare this... cat(as.character(GString("Hello ${who}\n"))) # ...to this. cat(GString("Hello ${who}\n")) # Escaping cat(as.character(GString("Hello \\${who}\n"))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Looping over vectors # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - x <- 1:5 y <- c("hello", "world") cat(as.character(GString("(x,y)=(${x},${y})")), sep=", ") cat("\n") cat(as.character(GString("(x,y)=(${x},$[capitalize]{y})")), sep=", ") cat("\n") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Predefined ("builtin") variables # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat(as.character(GString("Hello ${username} on host ${hostname} running ", "R v${rversion} in process #${pid} on ${os}. R is installed in ${rhome}."))) # Other built-in variables/functions... cat(as.character(GString("Current date: ${date}\n"))) cat(as.character(GString("Current date: $[format='%d/%m/%y']{date}\n"))) cat(as.character(GString("Current time: ${time}\n"))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Evaluating inline R code # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat(as.character(GString("Simple calculation: 1+1=${`1+1`}\n"))) cat(as.character(GString("Alternative current date: ${`date()`}\n"))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Function values # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Call function rnorm with arguments n=1, i.e. rnorm(n=1) cat(as.character(GString("Random normal number: $[n=1]{rnorm}\n"))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Global search-replace feature # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Replace all '-' with '.' cat(as.character(GString("Current date: ${date/-/.}\n"))) # Another example cat(as.character(GString("Escaped string: 12*12=${`12*12`/1/}\n"))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Defining new "builtin" function values # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Define your own builtin variables (functions) setMethodS3("getBuiltinAletter", "GString", function(object, ...) { base::letters[runif(1, min=1, max=length(base::letters))] }) cat(as.character(GString("A letter: ${aletter}\n"))) cat(as.character(GString("Another letter: ${aletter}\n"))) # Another example setMethodS3("getBuiltinGstring", "GString", function(object, ...) { # Return another GString. GString("${date} ${time}") }) cat(as.character(GString("Advanced example: ${gstring}\n"))) # Advanced example setMethodS3("getBuiltinRunif", "GString", function(object, n=1, min=0, max=1, ...) { formatC(runif(n=n, min=min, max=max), ...) }) cat(as.character(GString("A random number: ${runif}\n"))) n <- 5 cat(as.character(GString("${n} random numbers: "))) cat(as.character(GString("$[n=n, format='f']{runif}"))) cat("\n") # Advanced options. # Options are parsed as if they are elements in a list, e.g. # list(n=runif(n=1,min=1,max=5), format='f') cat(as.character(GString("$Random number of numbers: "))) cat(as.character(GString("$[n=runif(n=1,min=1,max=5), format='f']{runif}"))) cat("\n")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # First example # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - who <- "world" # Compare this... cat(as.character(GString("Hello ${who}\n"))) # ...to this. cat(GString("Hello ${who}\n")) # Escaping cat(as.character(GString("Hello \\${who}\n"))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Looping over vectors # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - x <- 1:5 y <- c("hello", "world") cat(as.character(GString("(x,y)=(${x},${y})")), sep=", ") cat("\n") cat(as.character(GString("(x,y)=(${x},$[capitalize]{y})")), sep=", ") cat("\n") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Predefined ("builtin") variables # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat(as.character(GString("Hello ${username} on host ${hostname} running ", "R v${rversion} in process #${pid} on ${os}. R is installed in ${rhome}."))) # Other built-in variables/functions... cat(as.character(GString("Current date: ${date}\n"))) cat(as.character(GString("Current date: $[format='%d/%m/%y']{date}\n"))) cat(as.character(GString("Current time: ${time}\n"))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Evaluating inline R code # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat(as.character(GString("Simple calculation: 1+1=${`1+1`}\n"))) cat(as.character(GString("Alternative current date: ${`date()`}\n"))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Function values # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Call function rnorm with arguments n=1, i.e. rnorm(n=1) cat(as.character(GString("Random normal number: $[n=1]{rnorm}\n"))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Global search-replace feature # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Replace all '-' with '.' cat(as.character(GString("Current date: ${date/-/.}\n"))) # Another example cat(as.character(GString("Escaped string: 12*12=${`12*12`/1/}\n"))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Defining new "builtin" function values # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Define your own builtin variables (functions) setMethodS3("getBuiltinAletter", "GString", function(object, ...) { base::letters[runif(1, min=1, max=length(base::letters))] }) cat(as.character(GString("A letter: ${aletter}\n"))) cat(as.character(GString("Another letter: ${aletter}\n"))) # Another example setMethodS3("getBuiltinGstring", "GString", function(object, ...) { # Return another GString. GString("${date} ${time}") }) cat(as.character(GString("Advanced example: ${gstring}\n"))) # Advanced example setMethodS3("getBuiltinRunif", "GString", function(object, n=1, min=0, max=1, ...) { formatC(runif(n=n, min=min, max=max), ...) }) cat(as.character(GString("A random number: ${runif}\n"))) n <- 5 cat(as.character(GString("${n} random numbers: "))) cat(as.character(GString("$[n=n, format='f']{runif}"))) cat("\n") # Advanced options. # Options are parsed as if they are elements in a list, e.g. # list(n=runif(n=1,min=1,max=5), format='f') cat(as.character(GString("$Random number of numbers: "))) cat(as.character(GString("$[n=runif(n=1,min=1,max=5), format='f']{runif}"))) cat("\n")
Checks if one or several pathnames has a URL protocol.
## Default S3 method: hasUrlProtocol(pathname, ...)
## Default S3 method: hasUrlProtocol(pathname, ...)
pathname |
|
... |
Not used. |
Henrik Bengtsson
Concatenating vectors into human-readable strings such as "1, 2, 3, ..., 10".
## Default S3 method: hpaste(..., sep="", collapse=", ", lastCollapse=NULL, maxHead=if (missing(lastCollapse)) 3 else Inf, maxTail=if (is.finite(maxHead)) 1 else Inf, abbreviate="...", empty=character(0L))
## Default S3 method: hpaste(..., sep="", collapse=", ", lastCollapse=NULL, maxHead=if (missing(lastCollapse)) 3 else Inf, maxTail=if (is.finite(maxHead)) 1 else Inf, abbreviate="...", empty=character(0L))
... |
Arguments to be pasted. |
sep |
A |
collapse , lastCollapse
|
The |
maxHead , maxTail , abbreviate
|
Non-negative |
empty |
A |
hpaste(..., sep=" ", maxHead=Inf)
corresponds to
paste(..., sep=" ", collapse=", ")
.
Returns a character
string.
Henrik Bengtsson
Internally paste
() is used.
# Some vectors x <- 1:6 y <- 10:1 z <- LETTERS[x] # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Abbreviation of output vector # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("x = %s.\n", hpaste(x)) ## x = 1, 2, 3, ..., 6. printf("x = %s.\n", hpaste(x, maxHead=2)) ## x = 1, 2, ..., 6. printf("x = %s.\n", hpaste(x, maxHead=3)) # Default ## x = 1, 2, 3, ..., 6. # It will never output 1, 2, 3, 4, ..., 6 printf("x = %s.\n", hpaste(x, maxHead=4)) ## x = 1, 2, 3, 4, 5, 6. # Showing the tail printf("x = %s.\n", hpaste(x, maxHead=1, maxTail=2)) ## x = 1, ..., 5, 6. # Turning off abbreviation printf("y = %s.\n", hpaste(y, maxHead=Inf)) ## y = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ## ...or simply printf("y = %s.\n", paste(y, collapse=", ")) ## y = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Adding a special separator before the last element # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Change last separator printf("x = %s.\n", hpaste(x, lastCollapse=", and ")) ## x = 1, 2, 3, 4, 5, and 6. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Backward compatibility with paste() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - s1 <- hpaste(x, maxHead=Inf) s2 <- paste(x, collapse=", ") printf("s = %s.\n", s1); stopifnot(identical(s1, s2)) s1 <- hpaste('<', x, '>', maxHead=Inf) s2 <- paste('<', x, '>', sep="", collapse=", ") printf("s = %s.\n", s1); stopifnot(identical(s1, s2)) s1 <- hpaste(x, y, z, sep="/", maxHead=Inf) s2 <- paste(x, y, z, sep="/", collapse=", ") printf("s = %s.\n", s1); stopifnot(identical(s1, s2)) s1 <- hpaste(x, collapse=NULL, maxHead=Inf) s2 <- paste(x, collapse=NULL) stopifnot(identical(s1, s2))
# Some vectors x <- 1:6 y <- 10:1 z <- LETTERS[x] # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Abbreviation of output vector # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("x = %s.\n", hpaste(x)) ## x = 1, 2, 3, ..., 6. printf("x = %s.\n", hpaste(x, maxHead=2)) ## x = 1, 2, ..., 6. printf("x = %s.\n", hpaste(x, maxHead=3)) # Default ## x = 1, 2, 3, ..., 6. # It will never output 1, 2, 3, 4, ..., 6 printf("x = %s.\n", hpaste(x, maxHead=4)) ## x = 1, 2, 3, 4, 5, 6. # Showing the tail printf("x = %s.\n", hpaste(x, maxHead=1, maxTail=2)) ## x = 1, ..., 5, 6. # Turning off abbreviation printf("y = %s.\n", hpaste(y, maxHead=Inf)) ## y = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ## ...or simply printf("y = %s.\n", paste(y, collapse=", ")) ## y = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Adding a special separator before the last element # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Change last separator printf("x = %s.\n", hpaste(x, lastCollapse=", and ")) ## x = 1, 2, 3, 4, 5, and 6. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Backward compatibility with paste() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - s1 <- hpaste(x, maxHead=Inf) s2 <- paste(x, collapse=", ") printf("s = %s.\n", s1); stopifnot(identical(s1, s2)) s1 <- hpaste('<', x, '>', maxHead=Inf) s2 <- paste('<', x, '>', sep="", collapse=", ") printf("s = %s.\n", s1); stopifnot(identical(s1, s2)) s1 <- hpaste(x, y, z, sep="/", maxHead=Inf) s2 <- paste(x, y, z, sep="/", collapse=", ") printf("s = %s.\n", s1); stopifnot(identical(s1, s2)) s1 <- hpaste(x, collapse=NULL, maxHead=Inf) s2 <- paste(x, collapse=NULL) stopifnot(identical(s1, s2))
Checks if a set of values are inside one or more intervals.
## S3 method for class 'numeric' inAnyInterval(...)
## S3 method for class 'numeric' inAnyInterval(...)
... |
Arguments passed to |
Henrik Bengtsson
Insert values to a vector at certain positions.
## Default S3 method: insert(x, ats, values=NA, useNames=TRUE, ...)
## Default S3 method: insert(x, ats, values=NA, useNames=TRUE, ...)
x |
The |
ats |
The indices of |
values |
A |
useNames |
If |
... |
Not used. |
Henrik Bengtsson
append
() takes argument after
(a scalar). For example,
append(x, y, after=after) == insert(x, values=y, ats=after+1)
.
Contrary to append()
, insert()
accepts a vector of insert indices.
# Insert NAs (default) between all values y <- c(a=1, b=2, c=3) print(y) x <- insert(y, ats=2:length(y)) Ex <- c(y[1], NA_real_, y[2], NA_real_, y[3]) print(x) stopifnot(identical(x,Ex)) # Insert at first position y <- c(a=1, b=2, c=3) print(y) x <- insert(y, ats=1, values=rep(NA_real_,2)) Ex <- c(NA_real_,NA_real_,y) print(x) stopifnot(identical(x,Ex)) x <- insert(y, ats=1, values=rep(NA_real_,2), useNames=FALSE) print(x) # Insert at last position (names of 'values' are ignored # because input vector has no names) x <- insert(1:3, ats=4, values=c(d=2, e=1)) Ex <- c(1:3,2,1) print(x) stopifnot(identical(x,Ex)) # Insert in the middle of a vector x <- insert(c(1,3,2,1), ats=2, values=2) print(x) stopifnot(identical(as.double(x),as.double(Ex))) # Insert multiple vectors at multiple indices at once x0 <- c(1:4, 8:11, 13:15) x <- insert(x0, ats=c(5,9), values=list(5:7,12)) print(x) Ex <- 1:max(x) stopifnot(identical(as.double(x),as.double(Ex))) x <- insert(x0, ats=c(5,9,12), values=list(5:7,12,16:18)) print(x) Ex <- 1:max(x) stopifnot(identical(as.double(x),as.double(Ex))) # Insert missing indices Ex <- 1:20 missing <- setdiff(Ex, x0) x <- x0 for (m in missing) x <- insert(x, ats=m, values=m) print(x) stopifnot(identical(as.double(x),as.double(Ex)))
# Insert NAs (default) between all values y <- c(a=1, b=2, c=3) print(y) x <- insert(y, ats=2:length(y)) Ex <- c(y[1], NA_real_, y[2], NA_real_, y[3]) print(x) stopifnot(identical(x,Ex)) # Insert at first position y <- c(a=1, b=2, c=3) print(y) x <- insert(y, ats=1, values=rep(NA_real_,2)) Ex <- c(NA_real_,NA_real_,y) print(x) stopifnot(identical(x,Ex)) x <- insert(y, ats=1, values=rep(NA_real_,2), useNames=FALSE) print(x) # Insert at last position (names of 'values' are ignored # because input vector has no names) x <- insert(1:3, ats=4, values=c(d=2, e=1)) Ex <- c(1:3,2,1) print(x) stopifnot(identical(x,Ex)) # Insert in the middle of a vector x <- insert(c(1,3,2,1), ats=2, values=2) print(x) stopifnot(identical(as.double(x),as.double(Ex))) # Insert multiple vectors at multiple indices at once x0 <- c(1:4, 8:11, 13:15) x <- insert(x0, ats=c(5,9), values=list(5:7,12)) print(x) Ex <- 1:max(x) stopifnot(identical(as.double(x),as.double(Ex))) x <- insert(x0, ats=c(5,9,12), values=list(5:7,12,16:18)) print(x) Ex <- 1:max(x) stopifnot(identical(as.double(x),as.double(Ex))) # Insert missing indices Ex <- 1:20 missing <- setdiff(Ex, x0) x <- x0 for (m in missing) x <- insert(x, ats=m, values=m) print(x) stopifnot(identical(as.double(x),as.double(Ex)))
Install R packages by name or URL.
## Default S3 method: installPackages(pkgs, types="auto", repos=getOption("repos"), ..., destPath=".", cleanup=TRUE)
## Default S3 method: installPackages(pkgs, types="auto", repos=getOption("repos"), ..., destPath=".", cleanup=TRUE)
pkgs |
A |
types |
|
repos |
|
... |
Additional arguments passed to |
destPath |
Path where any downloaded files are saved. |
cleanup |
If |
Returns nothing.
This method cannot install any packages that are already in use. Certain packages are always in use when calling this method, e.g. R.methodsS3, R.oo, and R.utils.
Henrik Bengtsson
## Not run: installPackages("R.rsp") installPackages("https://cran.r-project.org/src/contrib/Archive/R.rsp/R.rsp_0.8.2.tar.gz") installPackages("https://cran.r-project.org/bin/windows/contrib/4.0/R.rsp_0.44.0.zip") ## End(Not run)
## Not run: installPackages("R.rsp") installPackages("https://cran.r-project.org/src/contrib/Archive/R.rsp/R.rsp_0.8.2.tar.gz") installPackages("https://cran.r-project.org/bin/windows/contrib/4.0/R.rsp_0.44.0.zip") ## End(Not run)
Generates a vector of indices from a matrix of intervals.
## S3 method for class 'matrix' intervalsToSeq(fromTo, sort=FALSE, unique=FALSE, ...)
## S3 method for class 'matrix' intervalsToSeq(fromTo, sort=FALSE, unique=FALSE, ...)
fromTo |
|
sort |
If |
unique |
If |
... |
Not used. |
Henrik Bengtsson
## Not run: See example(seqToIntervals)
## Not run: See example(seqToIntervals)
Converts an integer to a binary/octal/hexadecimal number.
intToBin(x) intToOct(x) intToHex(x)
intToBin(x) intToOct(x) intToHex(x)
x |
A |
For length(x)
> 1, the number of characters in each of returned
elements is the same and driven by the x
element that requires
the highest number of character - all other elements are padded with
zeros (or ones for negative values). This is why we for instance get
intToHex(15) == "f"
but intToHex(15:16) == c("0f", "10")
.
The supported range for intToHex()
, intToOct()
, and
intToBin()
is that of R integers, i.e.
[-.Machine$integer.max, +.Machine$integer.max]
where.
.Machine$integer.max
is .
This limitation is there such that negative values can be converted too.
Returns a character
string of length length(x)
.
For coercions out of range, NA_character_
is returned for
such elements.
Henrik Bengtsson
Checks if this pathname is absolute.
## Default S3 method: isAbsolutePath(pathname, ...)
## Default S3 method: isAbsolutePath(pathname, ...)
pathname |
A |
... |
Not used. |
Returns a TRUE
if the pathname is absolute, otherwise FALSE
.
Henrik Bengtsson
Checks if the file specification is a directory.
## Default S3 method: isDirectory(pathname, ...)
## Default S3 method: isDirectory(pathname, ...)
pathname |
A |
... |
Not used. |
Returns TRUE
if the file specification is a directory, otherwise
FALSE
is returned.
This function follows symbolic links (also on Windows) and returns a value based on the link target (rather than the link itself).
Henrik Bengtsson
To check if it is a file see isFile
().
Internally file.info
() is used.
See also file_test
.
Checks if the current file position for a connection is at the 'End of File'.
## S3 method for class 'connection' isEof(con, ...)
## S3 method for class 'connection' isEof(con, ...)
con |
A |
... |
Not used. |
Internally seek
() is used, which according to to the R help
is discouraged on Windows. However, after many years of large-scale
testing on various Windows versions and file systems we have yet to
experience issues with using seek()
on Windows.
Returns a logical
.
Henrik Bengtsson
For more information see connection
.
Checks if the file specification is a file.
## Default S3 method: isFile(pathname, ...)
## Default S3 method: isFile(pathname, ...)
pathname |
A |
... |
Not used. |
Returns TRUE
if the file specification is a file, otherwise
FALSE
is returned.
This function follows symbolic links (also on Windows) and returns a value based on the link target (rather than the link itself).
Henrik Bengtsson
To check if it is a directory see isDirectory
().
Internally file.info
() is used.
See also file_test
.
Checks if there is an open connection to a file.
## S3 method for class 'character' isOpen(pathname, rw=c("read", "write"), ...)
## S3 method for class 'character' isOpen(pathname, rw=c("read", "write"), ...)
pathname |
|
rw |
A |
... |
Not used. |
Returns a logical
vector
indicating for each file whether there
exists an open file connection
or not.
Henrik Bengtsson
See isOpen()
in connections
.
showConnections
().
Checks if a package is installed or not.
## Default S3 method: isPackageInstalled(package, ...)
## Default S3 method: isPackageInstalled(package, ...)
package |
|
... |
Not used. |
Henrik Bengtsson
Checks if a package is loaded or not.
Note that, contrary to require()
,
this function does not load the package if not loaded.
## Default S3 method: isPackageLoaded(package, version=NULL, ...)
## Default S3 method: isPackageLoaded(package, version=NULL, ...)
package |
The name of the package. |
version |
A |
... |
Not used. |
Returns a logical
.
Henrik Bengtsson
To check if a package is installed or not, see isPackageInstalled
().
Identifies all entries with replicated values, that is, with values that exist more than once.
isReplicated(x, ...) replicates(x, ...)
isReplicated(x, ...) replicates(x, ...)
x |
A |
... |
Additional arguments passed to |
Let reps <- isReplicated(x)
. Then it always holds that:
reps == rev(isReplicated(rev(x)))
reps == duplicated(x) | duplicated(x, fromLast=TRUE)
reps == !is.element(x, setdiff(x, unique(x[duplicated(x)])))
A logical
vector
of length K,
where TRUE
indicates that the value exists elsewhere,
otherwise not.
Henrik Bengtsson
Internally duplicated
() is used.
See also isSingle
().
x <- c(1,1,2,3,4,2,1) x <- base::letters[x] print(x) # Identify entries with replicated values reps <- isReplicated(x) print(x[reps]) stopifnot(x[reps] == replicates(x)) # Identify entries with unique values print(x[!reps]) stopifnot(x[!reps] == singles(x)) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Validation # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - x <- c(1,1,2,3,4,2,1) x <- base::letters[x] reps <- isReplicated(x) stopifnot(all(table(x[reps]) > 1)) stopifnot(all(table(x[!reps]) == 1)) stopifnot(all(reps == rev(isReplicated(rev(x))))) stopifnot(all(reps == duplicated(x) | duplicated(x, fromLast=TRUE))) stopifnot(all(reps == !is.element(x, setdiff(x, unique(x[duplicated(x)]))))) stopifnot(all(sort(c(singles(x), replicates(x))) == sort(x))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Benchmarking singles() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - set.seed(0xBEEF) n <- 1e6 x <- sample(1:(n/2), size=n, replace=TRUE) t <- system.time({ s <- isSingle(x) }) print(sum(s)) t0 <- system.time({ s0 <- !(x %in% x[duplicated(x)]); }) print(t/t0) stopifnot(all(s == s0))
x <- c(1,1,2,3,4,2,1) x <- base::letters[x] print(x) # Identify entries with replicated values reps <- isReplicated(x) print(x[reps]) stopifnot(x[reps] == replicates(x)) # Identify entries with unique values print(x[!reps]) stopifnot(x[!reps] == singles(x)) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Validation # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - x <- c(1,1,2,3,4,2,1) x <- base::letters[x] reps <- isReplicated(x) stopifnot(all(table(x[reps]) > 1)) stopifnot(all(table(x[!reps]) == 1)) stopifnot(all(reps == rev(isReplicated(rev(x))))) stopifnot(all(reps == duplicated(x) | duplicated(x, fromLast=TRUE))) stopifnot(all(reps == !is.element(x, setdiff(x, unique(x[duplicated(x)]))))) stopifnot(all(sort(c(singles(x), replicates(x))) == sort(x))) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Benchmarking singles() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - set.seed(0xBEEF) n <- 1e6 x <- sample(1:(n/2), size=n, replace=TRUE) t <- system.time({ s <- isSingle(x) }) print(sum(s)) t0 <- system.time({ s0 <- !(x %in% x[duplicated(x)]); }) print(t/t0) stopifnot(all(s == s0))
Identifies all entries that exists exactly once.
isSingle(x, ...) singles(x, ...)
isSingle(x, ...) singles(x, ...)
x |
A |
... |
Additional arguments passed to |
A logical
vector
of length K,
indicating whether the value is unique or not.
Henrik Bengtsson
Internally isReplicated
() is used.
Checks if one or several pathnames is URLs.
## Default S3 method: isUrl(pathname, ...)
## Default S3 method: isUrl(pathname, ...)
pathname |
|
... |
Not used. |
Returns a logical
vector
of either TRUE
or FALSE
.
Henrik Bengtsson
Checks if a value (or a vector of values) is (close to) zero or not
where "close" means if the absolute value is less than neps*eps
.
Note that x == 0
will not work in all cases.
By default eps
is the smallest possible floating point value
that can be represented by the running machine, i.e.
.Machine$double.eps
and neps
is one.
By changing neps
it is easy to adjust how close to zero "close"
means without having to know the machine precision (or remembering how
to get it).
## Default S3 method: isZero(x, neps=1, eps=.Machine$double.eps, ...)
## Default S3 method: isZero(x, neps=1, eps=.Machine$double.eps, ...)
x |
A |
eps |
The smallest possible floating point. |
neps |
A scale factor of |
... |
Not used. |
Returns a logical
vector
indicating if the elements are zero or not.
Henrik Bengtsson
all.equal
().
Comparison
.
.Machine
.
x <- 0 print(x == 0) # TRUE print(isZero(x)) # TRUE x <- 1 print(x == 0) # FALSE print(isZero(x)) # FALSE x <- .Machine$double.eps print(x == 0) # FALSE print(isZero(x)) # FALSE x <- 0.9*.Machine$double.eps print(x == 0) # FALSE print(isZero(x)) # TRUE # From help(Comparisions) x1 <- 0.5 - 0.3 x2 <- 0.3 - 0.1 print(x1 - x2) print(x1 == x2) # FALSE on most machines print(identical(all.equal(x1, x2), TRUE)) # TRUE everywhere print(isZero(x1-x2)) # TRUE everywhere
x <- 0 print(x == 0) # TRUE print(isZero(x)) # TRUE x <- 1 print(x == 0) # FALSE print(isZero(x)) # FALSE x <- .Machine$double.eps print(x == 0) # FALSE print(isZero(x)) # FALSE x <- 0.9*.Machine$double.eps print(x == 0) # FALSE print(isZero(x)) # TRUE # From help(Comparisions) x1 <- 0.5 - 0.3 x2 <- 0.3 - 0.1 print(x1 - x2) print(x1 == x2) # FALSE on most machines print(identical(all.equal(x1, x2), TRUE)) # TRUE everywhere print(isZero(x1-x2)) # TRUE everywhere
Package: R.utils
Class Java
Object
~~|
~~+--
Java
Directly known subclasses:
public static class Java
extends Object
Static class that provides methods for reading and writing Java data types.
Currently the following data types are supported: byte, short and int.
R character strings can be written as UTF-8 formatted strings, which can
be read by Java. Currently on Java String's that contain ASCII characters
can be imported into R. The reason for this is that other characters are
translated into non-eight bits data, e.g. 16- and 24-bits, which the
readChar() method currently does not support.
Furthermore, the Java class defines some static constants describing the
minimum and maximum value of some of the common Java data types:
BYTE.MIN
, BYTE.MAX
SHORT.MIN
, SHORT.MAX
INT.MIN
, INT.MAX
LONG.MIN
, and LONG.MAX
.
Java()
Java()
Methods:
asByte |
- | |
asInt |
- | |
asLong |
- | |
asShort |
- | |
readByte |
- | |
readInt |
- | |
readShort |
- | |
readUTF |
- | |
writeByte |
- | |
writeInt |
- | |
writeShort |
- | |
writeUTF |
- | |
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
pathname <- tempfile() # Open the temporary file for writing out <- file(pathname, open="wb") b <- -128:127 Java$writeByte(out, b) s <- -32768:32767 Java$writeShort(out, s) i <- c(-2147483648, -2147483647, -1, 0, +1, 2147483646, 2147483647); Java$writeInt(out, i) str <- c("This R string was written (using the UTF-8 format) using", "the static methods of the Java class in the R.io package.") str <- paste(str, collapse="\n") Java$writeUTF(out, str) close(out) # Open the temporary file for reading inn <- file(pathname, open="rb") bfr <- Java$readByte(inn, n=length(b)) cat("Read ", length(bfr), " bytes.\n", sep="") if (!identical(bfr, b)) throw("Failed to read the same data that was written.") bfr <- Java$readShort(inn, n=length(s)) cat("Read ", length(bfr), " shorts.\n", sep="") if (!identical(bfr, s)) throw("Failed to read the same data that was written.") bfr <- Java$readInt(inn, n=length(i)) cat("Read ", length(bfr), " ints.\n", sep="") if (!identical(bfr, i)) throw("Failed to read the same data that was written.") bfr <- Java$readUTF(inn) cat("Read ", nchar(bfr), " UTF characters:\n", "'", bfr, "'\n", sep="") close(inn) file.remove(pathname)
pathname <- tempfile() # Open the temporary file for writing out <- file(pathname, open="wb") b <- -128:127 Java$writeByte(out, b) s <- -32768:32767 Java$writeShort(out, s) i <- c(-2147483648, -2147483647, -1, 0, +1, 2147483646, 2147483647); Java$writeInt(out, i) str <- c("This R string was written (using the UTF-8 format) using", "the static methods of the Java class in the R.io package.") str <- paste(str, collapse="\n") Java$writeUTF(out, str) close(out) # Open the temporary file for reading inn <- file(pathname, open="rb") bfr <- Java$readByte(inn, n=length(b)) cat("Read ", length(bfr), " bytes.\n", sep="") if (!identical(bfr, b)) throw("Failed to read the same data that was written.") bfr <- Java$readShort(inn, n=length(s)) cat("Read ", length(bfr), " shorts.\n", sep="") if (!identical(bfr, s)) throw("Failed to read the same data that was written.") bfr <- Java$readInt(inn, n=length(i)) cat("Read ", length(bfr), " ints.\n", sep="") if (!identical(bfr, i)) throw("Failed to read the same data that was written.") bfr <- Java$readUTF(inn) cat("Read ", nchar(bfr), " UTF characters:\n", "'", bfr, "'\n", sep="") close(inn) file.remove(pathname)
Gets the time when the file was last modified. The time is returned as a POSIXct
object.
## Default S3 method: lastModified(pathname, ...)
## Default S3 method: lastModified(pathname, ...)
pathname |
A |
... |
Not used. |
Returns POSIXct
object specifying when the file was last modified.
If the file does not exist or it is a directory, 0
is returned.
This function follows symbolic links (also on Windows) and returns a value based on the link target (rather than the link itself).
Henrik Bengtsson
Internally file.info
() is used.
Package: R.utils
Class LComments
Object
~~|
~~+--
SmartComments
~~~~~~~|
~~~~~~~+--
VComments
~~~~~~~~~~~~|
~~~~~~~~~~~~+--
LComments
Directly known subclasses:
public static class LComments
extends VComments
The LComments class.
This class, is almost identical to the super class, except that the constructor has different defaults.
LComments(letter="L", verboseName="log", ...)
LComments(letter="L", verboseName="log", ...)
letter |
The smart letter. |
verboseName |
The name of the verbose object. |
... |
Not used. |
Methods:
No methods defined.
Methods inherited from VComments:
convertComment, reset, validate
Methods inherited from SmartComments:
compile, convertComment, parse, reset, validate
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
Gets the file names in the directory.
Contrary to list.files()
, this method guarantees to work
recursively. Moreover, when subdirectories are processed recursively,
directory names are also returned.
## Default S3 method: listDirectory(path=".", pattern=NULL, recursive=FALSE, allNames=FALSE, fullNames=FALSE, ...)
## Default S3 method: listDirectory(path=".", pattern=NULL, recursive=FALSE, allNames=FALSE, fullNames=FALSE, ...)
path |
A path to be listed. |
pattern |
A |
recursive |
If |
allNames |
If |
fullNames |
If |
... |
Not used. |
Returns a vector
of file names.
Recursive searching of directory structure is done breath-first in a lexicographic order.
Henrik Bengtsson
Internally list.files
() is used.
Method to load object from a file or a connection, which previously have been saved using saveObject
().
## Default S3 method: loadObject(file, path=NULL, format=c("auto", "xdr", "rds"), ...)
## Default S3 method: loadObject(file, path=NULL, format=c("auto", "xdr", "rds"), ...)
file |
A filename or |
path |
The path where the file exists. |
format |
File format. |
... |
Not used. |
The main difference from this method and load
() in the
base package, is that this one returns the object read rather
than storing it in the global environment by its default name.
This makes it possible to load objects back using any variable name.
Returns the saved object.
Henrik Bengtsson
saveObject
() to save an object to file.
Internally load
() is used.
See also loadToEnv
().
See also saveRDS
().
Maps values to intervals by returning an index vector
specifying the (first)
interval that each value maps to, if any.
## S3 method for class 'numeric' mapToIntervals(x, intervals, includeLower=TRUE, includeUpper=TRUE, ...)
## S3 method for class 'numeric' mapToIntervals(x, intervals, includeLower=TRUE, includeUpper=TRUE, ...)
x |
|
intervals |
The N intervals to be matched against.
If an Nx2 |
includeLower , includeUpper
|
If |
... |
Not used. |
Returns an integer
vector
of length K.
Values that do not map to any interval have return value NA
.
Henrik Bengtsson
inAnyInterval
().
match
().
findInterval
().
cut
().
Merges intervals by returning an index vector
specifying the (first)
interval that each value maps to, if any.
## S3 method for class 'numeric' mergeIntervals(intervals, ...)
## S3 method for class 'numeric' mergeIntervals(intervals, ...)
intervals |
The N intervals to be merged.
If an Nx2 |
... |
Not used. |
The upper and lower bounds are considered to be inclusive, that is, all intervals are interpreted to be of form [a,b]. There is currently no way to specify intervals with open bounds, e.g. (a,b].
Furthermore, the bounds are currently treated as real values. For instance, merging [0,1] and [2,3] will return the same intervals. Note, if integer intervals were treated specially, we would merge these intervals to integer interval [0,3] == {0,1,2,3}.
Returns a matrix
(or a vector
) of M intervals, where M <= N.
The intervals are ordered by their lower bounds.
The @mode of the returned intervals is the same as the mode of
the input intervals.
Henrik Bengtsson
inAnyInterval
().
match
().
Creates a directory including any necessary but nonexistent parent directories.
## Default S3 method: mkdirs(pathname, mustWork=FALSE, maxTries=5L, ...)
## Default S3 method: mkdirs(pathname, mustWork=FALSE, maxTries=5L, ...)
pathname |
A |
mustWork |
If |
maxTries |
A positive |
... |
Not used. |
Returns TRUE
if the directory was successfully created,
otherwise FALSE
.
Note that if the directory already exists, FALSE
is returned.
On very rare occasions, we have observed on a large shared file
system that if one tests for the existence of a directory immediately
after creating it with dir.create
(), it may appear not
to be created. We believe this is due to the fact that there is a
short delay between creating a directory and that information being
fully propagated on the file system. To minimize the risk for such
false assertions on "slow" file systems, this method tries to create
a missing directory multiple times (argument maxTries
) (while
waiting a short period of time between each round) before giving up.
Henrik Bengtsson
Internally dir.create
() is used.
Miscellaneous functions for outputting via message().
These "m*" methods work analogously to their corresponding "*" methods
print
(), cat
(), show
,
str
, and printf
() but uses message
()
to output the content, which in turn outputs to standard error.
The mout()
method can be used for all other output methods,
e.g. mout(write(x, file=stdout()))
.
mout(..., appendLF=FALSE)
mout(..., appendLF=FALSE)
... |
Arguments passed to the underlying output method. |
appendLF |
A |
Returns what the message
() returns.
Henrik Bengtsson
print(letters[1:8]) mprint(letters[1:8]) cat(c(letters[1:8], "\n")) mcat(c(letters[1:8], "\n")) str(letters[1:8]) mstr(letters[1:8]) printf("x=%d\n", 1:3) mprintf("x=%d\n", 1:3)
print(letters[1:8]) mprint(letters[1:8]) cat(c(letters[1:8], "\n")) mcat(c(letters[1:8], "\n")) str(letters[1:8]) mstr(letters[1:8]) printf("x=%d\n", 1:3) mprintf("x=%d\n", 1:3)
A \"pager\" function that outputs to standard error and is compatible with file.show
().
mpager(files, header=NULL, title="R Information", delete.file=FALSE)
mpager(files, header=NULL, title="R Information", delete.file=FALSE)
files |
|
header |
|
title |
A |
delete.file |
If |
Returns nothing.
Henrik Bengtsson
file.show
() and argument pager
.
Gets the pathname or a connection to the NULL device on the current platform.
nullfile() nullcon()
nullfile() nullcon()
nullfile()
returns a character
string, which is "/dev/null"
except on Windows where it is "nul:"
.
nullcon()
returns a newly opened (binary) connection
to
the NULL device - make sure to close it when no longer needed.
Henrik Bengtsson
In R (>= 3.6.0), there exists base::nullfile()
, which is
identical to R.utils::nullfile()
.
Package: R.utils
Class NullVerbose
Object
~~|
~~+--
Verbose
~~~~~~~|
~~~~~~~+--
NullVerbose
Directly known subclasses:
public static class NullVerbose
extends Verbose
A Verbose class ignoring everything.
NullVerbose(...)
NullVerbose(...)
... |
Ignored. |
Methods:
cat |
- | |
enter |
- | |
evaluate |
- | |
exit |
- | |
header |
- | |
isOn |
- | |
isVisible |
- | |
newline |
- | |
print |
- | |
printf |
- | |
ruler |
- | |
str |
- | |
summary |
- | |
writeRaw |
- | |
Methods inherited from Verbose:
as.character, as.double, as.logical, capture, cat, enter, enterf, equals, evaluate, exit, getThreshold, getTimestampFormat, header, isOn, isVisible, less, more, newline, off, on, popState, print, printWarnings, printf, pushState, ruler, setDefaultLevel, setThreshold, setTimestampFormat, str, summary, timestamp, timestampOff, timestampOn, writeRaw
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
verbose <- Verbose() cat(verbose, "A verbose messages") verbose <- NullVerbose() cat(verbose, "A verbose messages") # Ignored
verbose <- Verbose() cat(verbose, "A verbose messages") verbose <- NullVerbose() cat(verbose, "A verbose messages") # Ignored
Registers a function to be called when the R garbage collector is (detected to be) running.
## Default S3 method: onGarbageCollect(fcn, action=c("prepend", "append", "replace"), ...)
## Default S3 method: onGarbageCollect(fcn, action=c("prepend", "append", "replace"), ...)
fcn |
A |
action |
A |
... |
Not used. |
Returns (invisibly) the hooks successfully called.
Henrik Bengtsson
## Not run: onGarbageCollect(function(...) { message("The R garbage collector is running!") }) ## End(Not run)
## Not run: onGarbageCollect(function(...) { message("The R garbage collector is running!") }) ## End(Not run)
Registers a function to be called when the R session finishes.
## Default S3 method: onSessionExit(fcn, action=c("prepend", "append", "replace"), ...)
## Default S3 method: onSessionExit(fcn, action=c("prepend", "append", "replace"), ...)
fcn |
A |
action |
A |
... |
Not used. |
Functions registered this way are called when finalizeSession
() is
called. Moreover, when this package is loaded, the .Last()
function is modified such that finalizeSession()
is called.
However, note that .Last()
is not guaranteed to be called
when the R session finished. For instance, the user may quit R by
calling quit(callLast=FALSE)
.
Moreover, when R is run in batch mode, .Last()
is never called.
Returns (invisibly) the hooks successfully called.
Henrik Bengtsson
.Last()
.
finalizeSession
().
## Not run: onSessionExit(function(...) { message("Bye bye world!") }) quit() ## End(Not run)
## Not run: onSessionExit(function(...) { message("Bye bye world!") }) quit() ## End(Not run)
Package: R.utils
Class Options
Object
~~|
~~+--
Options
Directly known subclasses:
Settings
public static class Options
extends Object
A class to set and get either options stored in a list
tree structure.
Each option has a pathname. The format of a pathname is similar to a (Unix) filesystem pathname, e.g. "graphics/cex". See examples for more details.
Options(options=list(), ...)
Options(options=list(), ...)
options |
A tree |
... |
Not used. |
Note, this class and its methods do not operate on the global options structure defined in R (options).
The constructor returns an Options object.
Methods:
as.character |
- | |
as.list |
- | |
equals |
- | |
getLeaves |
- | |
getOption |
- | |
hasOption |
- | |
names |
- | |
nbrOfOptions |
- | |
setOption |
- | |
str |
- | |
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
local <- Options() # Query a missing option cex <- getOption(local, "graphics/cex") cat("graphics/cex =", cex, "\n") # Returns NULL # Query a missing option with default value cex <- getOption(local, "graphics/cex", defaultValue=1) cat("graphics/cex =", cex, "\n") # Returns NULL # Set option and get previous value oldCex <- setOption(local, "graphics/cex", 2) cat("previous graphics/cex =", oldCex, "\n") # Returns NULL # Set option again and get previous value oldCex <- setOption(local, "graphics/cex", 3) cat("previous graphics/cex =", oldCex, "\n") # Returns 2 # Query a missing option with default value, which is ignored cex <- getOption(local, "graphics/cex", defaultValue=1) cat("graphics/cex =", cex, "\n") # Returns 3 # Query multiple options with multiple default values multi <- getOption(local, c("graphics/cex", "graphics/pch"), c(1,2)) print(multi) # Check existance of multiple options has <- hasOption(local, c("graphics/cex", "graphics/pch")) print(has) # Get a subtree of options graphics <- getOption(local, "graphics") print(graphics) # Get the complete tree of options all <- getOption(local) print(all)
local <- Options() # Query a missing option cex <- getOption(local, "graphics/cex") cat("graphics/cex =", cex, "\n") # Returns NULL # Query a missing option with default value cex <- getOption(local, "graphics/cex", defaultValue=1) cat("graphics/cex =", cex, "\n") # Returns NULL # Set option and get previous value oldCex <- setOption(local, "graphics/cex", 2) cat("previous graphics/cex =", oldCex, "\n") # Returns NULL # Set option again and get previous value oldCex <- setOption(local, "graphics/cex", 3) cat("previous graphics/cex =", oldCex, "\n") # Returns 2 # Query a missing option with default value, which is ignored cex <- getOption(local, "graphics/cex", defaultValue=1) cat("graphics/cex =", cex, "\n") # Returns 3 # Query multiple options with multiple default values multi <- getOption(local, c("graphics/cex", "graphics/pch"), c(1,2)) print(multi) # Check existance of multiple options has <- hasOption(local, c("graphics/cex", "graphics/pch")) print(has) # Get a subtree of options graphics <- getOption(local, "graphics") print(graphics) # Get the complete tree of options all <- getOption(local) print(all)
Patches installed and loaded packages and more.
## Default S3 method: patchCode(paths=NULL, recursive=TRUE, suppressWarnings=TRUE, knownExtensions=c("R", "r", "S", "s"), verbose=FALSE, ...)
## Default S3 method: patchCode(paths=NULL, recursive=TRUE, suppressWarnings=TRUE, knownExtensions=c("R", "r", "S", "s"), verbose=FALSE, ...)
paths |
The path to the directory (and subdirectories) which
contains source code that will patch loaded packages.
If |
recursive |
If |
suppressWarnings |
|
knownExtensions |
A |
verbose |
If |
... |
Not used. |
The method will look for source code files (recursively or not) that
match known filename extensions. Each found source code file is
then source
()d.
If the search is recursive, subdirectories are entered if and only if either (1) the name of the subdirectory is the same as a loaded (and installed) package, or (2) if there is no installed package with that name. The latter allows common code to be organized in directories although it is still not assigned to packages.
Each of the directories given by argument paths
will be
processed one by one. This makes it possible to have more than one
file tree containing patches.
To set an options, see options
(). To set a system
environment, see Sys.setenv
().
The character ;
is interpreted as a separator. Due to
incompatibility with Windows pathnames, :
is not a
valid separator.
Returns (invisibly) the number of files sourced.
Henrik Bengtsson
## Not run: # Patch all source code files in the current directory patchCode(".") # Patch all source code files in R_PATCHES options("R_PATCHES"="~/R-patches/") # alternatively, Sys.setenv("R_PATCHES"="~/R-patches/") patchCode() ## End(Not run)
## Not run: # Patch all source code files in the current directory patchCode(".") # Patch all source code files in R_PATCHES options("R_PATCHES"="~/R-patches/") # alternatively, Sys.setenv("R_PATCHES"="~/R-patches/") patchCode() ## End(Not run)
Drops a backup suffix from the backup pathname and, by default, restores an existing backup file accordingly by renaming it.
## Default S3 method: popBackupFile(filename, path=NULL, suffix=".bak", isFile=TRUE, onMissing=c("ignore", "error"), drop=TRUE, ..., verbose=FALSE)
## Default S3 method: popBackupFile(filename, path=NULL, suffix=".bak", isFile=TRUE, onMissing=c("ignore", "error"), drop=TRUE, ..., verbose=FALSE)
filename |
The filename of the backup file. |
path |
The path of the file. |
suffix |
The suffix of the filename to be dropped. |
isFile |
If |
onMissing |
A |
drop |
If |
... |
Not used. |
verbose |
Returns the pathname with the backup suffix dropped.
Henrik Bengtsson
See pushBackupFile
() for more details and an example.
Drops a temporary suffix from the temporary pathname and, by default, renames an existing temporary file accordingly.
## Default S3 method: popTemporaryFile(filename, path=NULL, suffix=".tmp", isFile=TRUE, ..., verbose=FALSE)
## Default S3 method: popTemporaryFile(filename, path=NULL, suffix=".tmp", isFile=TRUE, ..., verbose=FALSE)
filename |
The filename of the temporary file. |
path |
The path of the temporary file. |
suffix |
The suffix of the temporary filename to be dropped. |
isFile |
If |
... |
Not used. |
verbose |
If isFile
is FALSE
, the pathname where the suffix of the
temporary pathname has been dropped is returned.
If isFile
is TRUE
, the temporary file is renamed.
Then, if the temporary file does not exists or it was not successfully
renamed, an exception is thrown.
Returns the pathname with the temporary suffix dropped.
Henrik Bengtsson
See pushTemporaryFile
() for more details and an example.
C-style formatted output.
## Default S3 method: printf(fmt, ..., sep="", file="")
## Default S3 method: printf(fmt, ..., sep="", file="")
fmt |
A |
... |
Additional arguments |
sep |
|
file |
A |
Returns nothing.
Henrik Bengtsson
For C-style formatting of character
strings, see sprintf
().
cat("Hello world\n") printf("Hello world\n") x <- 1.23 cat(sprintf("x=%.2f\n", x)) printf("x=%.2f\n", x) y <- 4.56 cat(sprintf(c("x=%.2f\n", "y=%.2f\n"), c(x,y)), sep="") printf(c("x=%.2f\n", "y=%.2f\n"), c(x,y))
cat("Hello world\n") printf("Hello world\n") x <- 1.23 cat(sprintf("x=%.2f\n", x)) printf("x=%.2f\n", x) y <- 4.56 cat(sprintf(c("x=%.2f\n", "y=%.2f\n"), c(x,y)), sep="") printf(c("x=%.2f\n", "y=%.2f\n"), c(x,y))
Package: R.utils
Class ProgressBar
Object
~~|
~~+--
ProgressBar
Directly known subclasses:
FileProgressBar
public static class ProgressBar
extends Object
ProgressBar(max=100, ticks=10, stepLength=1, newlineWhenDone=TRUE)
ProgressBar(max=100, ticks=10, stepLength=1, newlineWhenDone=TRUE)
max |
The maximum number of steps. |
ticks |
Put visual "ticks" every |
stepLength |
The default length for each increase. |
newlineWhenDone |
If |
Methods:
as.character |
- | |
getBarString |
- | |
increase |
- | |
isDone |
- | |
reset |
- | |
setMaxValue |
- | |
setProgress |
- | |
setStepLength |
- | |
setTicks |
- | |
setValue |
- | |
update |
- | |
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
# A progress bar with default step length one. pb <- ProgressBar(max=42) reset(pb) while (!isDone(pb)) { x <- rnorm(3e4) increase(pb) # Emulate a slow process if (interactive()) Sys.sleep(0.02) } cat("\n") # A "faster" progress bar with default step length 1.4. pb <- ProgressBar(max=42, stepLength=1.4) reset(pb) while (!isDone(pb)) { x <- rnorm(3e4) increase(pb) # Emulate a slow process if (interactive()) Sys.sleep(0.02) } cat("\n")
# A progress bar with default step length one. pb <- ProgressBar(max=42) reset(pb) while (!isDone(pb)) { x <- rnorm(3e4) increase(pb) # Emulate a slow process if (interactive()) Sys.sleep(0.02) } cat("\n") # A "faster" progress bar with default step length 1.4. pb <- ProgressBar(max=42, stepLength=1.4) reset(pb) while (!isDone(pb)) { x <- rnorm(3e4) increase(pb) # Emulate a slow process if (interactive()) Sys.sleep(0.02) } cat("\n")
Appends a backup suffix to the pathname and, optionally, renames an existing file accordingly.
In combination with popBackupFile
(), this method is useful
for creating a backup of a file and restoring it.
## Default S3 method: pushBackupFile(filename, path=NULL, suffix=".bak", isFile=TRUE, onMissing=c("ignore", "error"), copy=FALSE, overwrite=TRUE, ..., verbose=FALSE)
## Default S3 method: pushBackupFile(filename, path=NULL, suffix=".bak", isFile=TRUE, onMissing=c("ignore", "error"), copy=FALSE, overwrite=TRUE, ..., verbose=FALSE)
filename |
The filename of the file to backup. |
path |
The path of the file. |
suffix |
The suffix to be appended. |
isFile |
If |
onMissing |
A |
copy |
If |
overwrite |
If |
... |
Not used. |
verbose |
Returns the pathname with the suffix appended.
Henrik Bengtsson
# Create a file pathname <- file.path(tempdir(), "foobar.txt") cat(file=pathname, "File v1\n") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # (a) Backup and restore a file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Turn it into a backup file pathnameB <- pushBackupFile(pathname, verbose=TRUE) print(pathnameB) # Restore main file from backup pathnameR <- popBackupFile(pathnameB, verbose=TRUE) print(pathnameR) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # (b) Backup, create a new file and frop backup file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Turn it into a backup file pathnameB <- pushBackupFile(pathname, verbose=TRUE) print(pathnameB) # Create a new file cat(file=pathname, "File v2\n") # Drop backup because a new main file was successfully created pathnameR <- popBackupFile(pathnameB, verbose=TRUE) print(pathnameR)
# Create a file pathname <- file.path(tempdir(), "foobar.txt") cat(file=pathname, "File v1\n") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # (a) Backup and restore a file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Turn it into a backup file pathnameB <- pushBackupFile(pathname, verbose=TRUE) print(pathnameB) # Restore main file from backup pathnameR <- popBackupFile(pathnameB, verbose=TRUE) print(pathnameR) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # (b) Backup, create a new file and frop backup file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Turn it into a backup file pathnameB <- pushBackupFile(pathname, verbose=TRUE) print(pathnameB) # Create a new file cat(file=pathname, "File v2\n") # Drop backup because a new main file was successfully created pathnameR <- popBackupFile(pathnameB, verbose=TRUE) print(pathnameR)
Appends a temporary suffix to the pathname and, optionally, renames an existing file accordingly.
In combination with popTemporaryFile
(), this method is useful
for creating a file/writing data to file atomically, by
first writing to a temporary file which is the renamed. If for
some reason the generation of the file was interrupted, for instance
by a user interrupt or a power failure, then it is only the temporary
file that is incomplete.
## Default S3 method: pushTemporaryFile(filename, path=NULL, suffix=".tmp", isFile=FALSE, ..., verbose=FALSE)
## Default S3 method: pushTemporaryFile(filename, path=NULL, suffix=".tmp", isFile=FALSE, ..., verbose=FALSE)
filename |
The filename of the file. |
path |
The path of the file. |
suffix |
The suffix to be appended. |
isFile |
If |
... |
Not used. |
verbose |
If isFile
is FALSE
, the pathname where the suffix of the
temporary pathname has been added is returned.
If isFile
is TRUE
, the file is also renamed.
Then, if the file does not exists or it was not successfully
renamed, an exception is thrown.
Returns the pathname with the suffix appended.
Henrik Bengtsson
createAtomically <- function(pathname, ...) { cat("Pathname: ", pathname, "\n", sep=""); # Generate a file atomically, i.e. the file will either be # complete or not created at all. If interrupted while # writing, only a temporary file will exist/remain. pathnameT <- pushTemporaryFile(pathname); cat("Temporary pathname: ", pathnameT, "\n", sep=""); cat(file=pathnameT, "This file was created atomically:\n"); for (kk in 1:10) { cat(file=pathnameT, kk, "\n", append=TRUE); # Emulate a slow process if (interactive()) Sys.sleep(0.1) } cat(file=pathnameT, "END OF FILE\n", append=TRUE); # Rename the temporary file pathname <- popTemporaryFile(pathnameT); pathname; } # createAtomically() pathname <- tempfile(); tryCatch({ # Try to interrupt the process while writing... pathname <- createAtomically(pathname); }, interrupt=function(intr) { str(intr); }) # ...and this will throw an exception bfr <- readLines(pathname); cat(bfr, sep="\n");
createAtomically <- function(pathname, ...) { cat("Pathname: ", pathname, "\n", sep=""); # Generate a file atomically, i.e. the file will either be # complete or not created at all. If interrupted while # writing, only a temporary file will exist/remain. pathnameT <- pushTemporaryFile(pathname); cat("Temporary pathname: ", pathnameT, "\n", sep=""); cat(file=pathnameT, "This file was created atomically:\n"); for (kk in 1:10) { cat(file=pathnameT, kk, "\n", append=TRUE); # Emulate a slow process if (interactive()) Sys.sleep(0.1) } cat(file=pathnameT, "END OF FILE\n", append=TRUE); # Rename the temporary file pathname <- popTemporaryFile(pathnameT); pathname; } # createAtomically() pathname <- tempfile(); tryCatch({ # Try to interrupt the process while writing... pathname <- createAtomically(pathname); }, interrupt=function(intr) { str(intr); }) # ...and this will throw an exception bfr <- readLines(pathname); cat(bfr, sep="\n");
Gets the on R CMD check if the current R session was launched by it.
queryRCmdCheck(...)
queryRCmdCheck(...)
... |
Not used. |
Returns character
string
"checkingTests"
if 'R CMD check' runs one one of the package tests,
and "checkingExamples"
if it runs one of the package examples.
If the current R session was not launched by 'R CMD check',
then "notRunning"
is returned.
This function only works if the working directory has not been changed.
Henrik Bengtsson
status <- queryRCmdCheck() if (status != "notRunning") { cat("The current R session was launched by R CMD check. Status: ", status, "\n") } else { cat("The current R session was not launched by R CMD check.\n") } # Display how R was launched print(base::commandArgs()) # Display loaded packages etc. print(search()) # Display current working directory print(getwd())
status <- queryRCmdCheck() if (status != "notRunning") { cat("The current R session was launched by R CMD check. Status: ", status, "\n") } else { cat("The current R session was not launched by R CMD check.\n") } # Display how R was launched print(base::commandArgs()) # Display loaded packages etc. print(search()) # Display current working directory print(getwd())
Reads binary data from disjoint sections of a connection or a file.
## Default S3 method: readBinFragments(con, what, idxs=1, origin=c("current", "start"), size=NA, ..., verbose=FALSE)
## Default S3 method: readBinFragments(con, what, idxs=1, origin=c("current", "start"), size=NA, ..., verbose=FALSE)
con |
A |
what |
A |
idxs |
A |
origin |
A |
size |
The size of the data type to be read. If |
... |
Additional arguments passed to |
verbose |
Returns a vector
of the requested mode
().
Henrik Bengtsson
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Create a data file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - data <- 1:255 size <- 2 pathname <- tempfile("exampleReadBinFragments") writeBin(con=pathname, data, size=size) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Read and write using index vectors # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat("Read file...\n") # Read every 16:th byte in the file idxs <- seq(from=1, to=255, by=16) x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs) stopifnot(identical(x, data[idxs])) print(x) # Read every 16:th byte in a connection starting with the 6th. idxs <- idxs + 5L x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs) stopifnot(identical(x, data[idxs])) print(x) cat("Read file...done\n") cat("Write file...\n") # Update every 16:th byte in the file idxs <- seq(from=1, to=255, by=16) x0 <- data[idxs] writeBinFragments(pathname, idxs=idxs, rev(x0), size=size) x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs) print(x) stopifnot(identical(rev(x0), x)) # Update every 16:th byte in the file idxs <- seq(from=1, to=255, by=16) writeBinFragments(pathname, idxs=idxs, rev(x), size=size) x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs) print(x) stopifnot(identical(x0, x)) # Assert everything is as expected # Read the complete file x <- readBin(pathname, what="integer", size=size, signed=FALSE, n=length(data)) stopifnot(identical(x, data)) cat("Write file...done\n") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Ditto but via a connection # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat("Read connection...\n") # Read every 16:th byte in a connection con <- file(pathname, open="rb") idxs <- seq(from=1, to=255, by=16) x <- readBinFragments(con, what="integer", size=size, signed=FALSE, idxs=idxs) stopifnot(identical(x, data[idxs])) print(x) # Read every 16:th byte in a connection starting with the 6th. idxs <- idxs + 5L x <- readBinFragments(con, what="integer", size=size, signed=FALSE, idxs=idxs, origin="start") stopifnot(identical(x, data[idxs])) print(x) close(con) cat("Read connection...done\n") # Update every 16:th byte in a connection cat("Write connection...\n") con <- file(pathname, open="r+b") idxs <- seq(from=1, to=255, by=16) x0 <- data[idxs] writeBinFragments(pathname, idxs=idxs, rev(x0), size=size) x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs) print(x) stopifnot(identical(rev(x0), x)) # Update every 16:th byte in the file idxs <- seq(from=1, to=255, by=16) writeBinFragments(pathname, idxs=idxs, rev(x), size=size) x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs, origin="start") print(x) stopifnot(identical(x0, x)) close(con) # Assert everything is as expected # Read the complete file x <- readBin(pathname, what="integer", size=size, signed=FALSE, n=length(data)) stopifnot(identical(x, data)) cat("Write connection...done\n") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Clean up # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - file.remove(pathname)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Create a data file # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - data <- 1:255 size <- 2 pathname <- tempfile("exampleReadBinFragments") writeBin(con=pathname, data, size=size) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Read and write using index vectors # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat("Read file...\n") # Read every 16:th byte in the file idxs <- seq(from=1, to=255, by=16) x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs) stopifnot(identical(x, data[idxs])) print(x) # Read every 16:th byte in a connection starting with the 6th. idxs <- idxs + 5L x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs) stopifnot(identical(x, data[idxs])) print(x) cat("Read file...done\n") cat("Write file...\n") # Update every 16:th byte in the file idxs <- seq(from=1, to=255, by=16) x0 <- data[idxs] writeBinFragments(pathname, idxs=idxs, rev(x0), size=size) x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs) print(x) stopifnot(identical(rev(x0), x)) # Update every 16:th byte in the file idxs <- seq(from=1, to=255, by=16) writeBinFragments(pathname, idxs=idxs, rev(x), size=size) x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs) print(x) stopifnot(identical(x0, x)) # Assert everything is as expected # Read the complete file x <- readBin(pathname, what="integer", size=size, signed=FALSE, n=length(data)) stopifnot(identical(x, data)) cat("Write file...done\n") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Ditto but via a connection # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat("Read connection...\n") # Read every 16:th byte in a connection con <- file(pathname, open="rb") idxs <- seq(from=1, to=255, by=16) x <- readBinFragments(con, what="integer", size=size, signed=FALSE, idxs=idxs) stopifnot(identical(x, data[idxs])) print(x) # Read every 16:th byte in a connection starting with the 6th. idxs <- idxs + 5L x <- readBinFragments(con, what="integer", size=size, signed=FALSE, idxs=idxs, origin="start") stopifnot(identical(x, data[idxs])) print(x) close(con) cat("Read connection...done\n") # Update every 16:th byte in a connection cat("Write connection...\n") con <- file(pathname, open="r+b") idxs <- seq(from=1, to=255, by=16) x0 <- data[idxs] writeBinFragments(pathname, idxs=idxs, rev(x0), size=size) x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs) print(x) stopifnot(identical(rev(x0), x)) # Update every 16:th byte in the file idxs <- seq(from=1, to=255, by=16) writeBinFragments(pathname, idxs=idxs, rev(x), size=size) x <- readBinFragments(pathname, what="integer", size=size, signed=FALSE, idxs=idxs, origin="start") print(x) stopifnot(identical(x0, x)) close(con) # Assert everything is as expected # Read the complete file x <- readBin(pathname, what="integer", size=size, signed=FALSE, n=length(data)) stopifnot(identical(x, data)) cat("Write connection...done\n") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Clean up # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - file.remove(pathname)
Reads one or more Rd help files in a certain format.
## Default S3 method: readRdHelp(..., format=c("text", "html", "latex", "rd"), drop=TRUE)
## Default S3 method: readRdHelp(..., format=c("text", "html", "latex", "rd"), drop=TRUE)
... |
Arguments passed to |
format |
A |
drop |
If |
Returns a list
of character
strings or a single character
string.
Henrik Bengtsson
Reads a file in table format and creates a data frame from it, with cases corresponding to lines and variables to fields in the file.
WARNING: This method is very much in an alpha stage. Expect it to change.
This method is an extension to the default read.table
function in R. It is possible to specify a column name to column class
map such that the column classes are automatically assigned from the
column header in the file.
In addition, it is possible to read any subset of rows. The method is optimized such that only columns and rows that are of interest are parsed and read into R's memory. This minimizes memory usage at the same time as it speeds up the reading.
## Default S3 method: readTable(file, colClasses=NULL, isPatterns=FALSE, defColClass=NA, header=FALSE, skip=0, nrows=-1, rows=NULL, col.names=NULL, check.names=FALSE, path=NULL, ..., stripQuotes=TRUE, method=c("readLines", "intervals"), verbose=FALSE)
## Default S3 method: readTable(file, colClasses=NULL, isPatterns=FALSE, defColClass=NA, header=FALSE, skip=0, nrows=-1, rows=NULL, col.names=NULL, check.names=FALSE, path=NULL, ..., stripQuotes=TRUE, method=c("readLines", "intervals"), verbose=FALSE)
file |
A |
colClasses |
Either a named or an unnamed |
isPatterns |
If |
defColClass |
If the column class map specified by a named
|
header |
If |
skip |
The number of lines (commented or non-commented) to skip before trying to read the header or alternatively the data table. |
nrows |
The number of rows to read of the data table.
Ignored if |
rows |
An row index |
col.names |
Same as in |
check.names |
Same as in |
path |
If |
... |
Arguments passed to |
stripQuotes |
If |
method |
If |
verbose |
Returns a data.frame
.
Henrik Bengtsson
readTableIndex
().
read.table
.
colClasses
().
Reads a single column from file in table format, which can then be used as a index-to-row (look-up) map
for fast access to a subset of rows using readTable
().
## Default S3 method: readTableIndex(..., indexColumn=1, colClass="character", verbose=FALSE)
## Default S3 method: readTableIndex(..., indexColumn=1, colClass="character", verbose=FALSE)
indexColumn |
An single |
colClass |
A single |
... |
Arguments passed to |
verbose |
Returns a vector
.
Henrik Bengtsson
readTable
().
## Not run: # File containing data table to be access many times filename <- "somefile.txt" # Create a look-up index index <- readTableIndex(filename) # Keys of interest keys <- c("foo", "bar", "wah") # Read only those keys and do it fast df <- readTable(filename, rows=match(keys, index)) ## End(Not run)
## Not run: # File containing data table to be access many times filename <- "somefile.txt" # Create a look-up index index <- readTableIndex(filename) # Keys of interest keys <- c("foo", "bar", "wah") # Read only those keys and do it fast df <- readTable(filename, rows=match(keys, index)) ## End(Not run)
Reads a Microsoft Windows Shortcut (.lnk file).
## Default S3 method: readWindowsShortcut(con, verbose=FALSE, ...)
## Default S3 method: readWindowsShortcut(con, verbose=FALSE, ...)
con |
A |
verbose |
If |
... |
Not used. |
The MIME type for a Windows Shortcut file is
application/x-ms-shortcut
.
Returns a list
structure.
Henrik Bengtsson
[1] Wotsit's Format, http://www.wotsit.org/, 2005.
[2] Hager J, The Windows Shortcut File Format
(as reverse-engineered by), version 1.0.
[3] Microsoft Developer Network, IShellLink Interface, 2018.
https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-ishelllinka
[4] Andrews D, Parsing Windows Shortcuts (lnk) files in java,
comp.lang.java.help, Aug 1999.
https://groups.google.com/d/topic/comp.lang.java.help/ouFHsH1UgKI
[5] Multiple authors, Windows shell links (in Tcl), Tcler's Wiki,
April 2008. https://wiki.tcl-lang.org/1844
[6] Daniel S. Bensen, Shortcut File Format (.lnk), Stdlib.com,
April 24, 2009.
https://web.archive.org/web/20110817051855/http://www.stdlib.com/art6-Shortcut-File-Format-lnk.html (was http://www.stdlib.com/art6-Shortcut-File-Format-lnk.html)
[7] [MS-SHLLINK]: Shell Link (.LNK) Binary File Format, Microsoft Inc.,
September 25, 2009.
createWindowsShortcut
() and
filePath()
pathname <- system.file("data-ex/HISTORY.LNK", package="R.utils") lnk <- readWindowsShortcut(pathname) # Print all information print(lnk) # Get the relative path to the target file history <- file.path(dirname(pathname), lnk$relativePath) # Alternatively, everything in one call history <- filePath(pathname, expandLinks="relative")
pathname <- system.file("data-ex/HISTORY.LNK", package="R.utils") lnk <- readWindowsShortcut(pathname) # Print all information print(lnk) # Get the relative path to the target file history <- file.path(dirname(pathname), lnk$relativePath) # Alternatively, everything in one call history <- filePath(pathname, expandLinks="relative")
Removes a directory, and if requested, also its contents.
## Default S3 method: removeDirectory(path, recursive=FALSE, mustExist=TRUE, ...)
## Default S3 method: removeDirectory(path, recursive=FALSE, mustExist=TRUE, ...)
path |
A |
recursive |
If |
mustExist |
If |
... |
Not used. |
Returns (invisibly) TRUE
, the directory was successfully removed,
otherwise FALSE
, unless an exception is thrown.
This function can also be used to remove symbolic links to directories
without removing the target.
Note that neither file.remove
() nor unlink
()
is capable of remove symbolic directory links on Windows.
Henrik Bengtsson
Internally unlink
() is used.
Sample values from a set of elements.
Contrary to sample
(), this function also works as
expected when there is only one element in the set to be sampled, cf. [1].
This function originates from the example code of sample
()
as of R v2.12.0.
## Default S3 method: resample(x, ...)
## Default S3 method: resample(x, ...)
x |
A |
... |
Additional arguments passed to |
Returns a sampled vector
of the same data types as argument x
.
Henrik Bengtsson
[1] Henrik Bengtsson,
Using sample() to sample one value from a single value?,
R-devel mailing list, 2010-11-03.
Internally sample.int
() is used.
Saves an object to a file or a connection.
## Default S3 method: saveObject(object, file=NULL, path=NULL, format=c("auto", "xdr", "rds"), compress=TRUE, ..., safe=TRUE)
## Default S3 method: saveObject(object, file=NULL, path=NULL, format=c("auto", "xdr", "rds"), compress=TRUE, ..., safe=TRUE)
object |
The object to be saved. |
file |
A filename or |
path |
Optional path, if |
format |
File format. |
compress |
If |
... |
Other arguments accepted by |
safe |
If |
Returns (invisibly) the pathname or the connection
.
Henrik Bengtsson
loadObject
() to load an object from file.
digest
for how hash codes are calculated from an object.
See also saveRDS
().
Gets a short human readable string representation of an vector of indices.
## Default S3 method: seqToHumanReadable(idx, tau=2L, delimiter="-", collapse=", ", ...)
## Default S3 method: seqToHumanReadable(idx, tau=2L, delimiter="-", collapse=", ", ...)
idx |
|
tau |
A non-negative |
delimiter |
A |
collapse |
A |
... |
Not used. |
Henrik Bengtsson
Internally, seqToIntervals
() is used.
print(seqToHumanReadable(1:2)) # "1, 2" print(seqToHumanReadable(1:2, tau=1)) # "1-2" print(seqToHumanReadable(1:10)) # "1-10" print(seqToHumanReadable(c(1:10, 15:18, 20))) # "1-10, 15-18, 20"
print(seqToHumanReadable(1:2)) # "1, 2" print(seqToHumanReadable(1:2, tau=1)) # "1-2" print(seqToHumanReadable(1:10)) # "1-10" print(seqToHumanReadable(c(1:10, 15:18, 20))) # "1-10, 15-18, 20"
Gets all contiguous intervals of a vector of indices.
## Default S3 method: seqToIntervals(idx, ...)
## Default S3 method: seqToIntervals(idx, ...)
idx |
|
... |
Not used. |
Henrik Bengtsson
*intervalsToSeq()
.
To identify sequences of equal values, see rle
().
x <- 1:10 y <- seqToIntervals(x) print(y) # [1 10] x <- c(1:10, 15:18, 20) y <- seqToIntervals(x) print(y) # [1 10; 15 18; 20 20] z <- intervalsToSeq(y) print(z) stopifnot(all.equal(x,z))
x <- 1:10 y <- seqToIntervals(x) print(y) # [1 10] x <- c(1:10, 15:18, 20) y <- seqToIntervals(x) print(y) # [1 10; 15 18; 20 20] z <- intervalsToSeq(y) print(z) stopifnot(all.equal(x,z))
Sets a option in R by specifying its name as a character
string.
## Default S3 method: setOption(x, value, ...)
## Default S3 method: setOption(x, value, ...)
x |
The name of the option to be set. |
value |
The new value of the option. |
... |
Not used. |
Returns (invisibly) the previous value of the option.
Henrik Bengtsson
See getOption
() and "base::options".
Package: R.utils
Class Settings
Object
~~|
~~+--
Options
~~~~~~~|
~~~~~~~+--
Settings
Directly known subclasses:
public static class Settings
extends Options
Class for applicational settings.
Settings(basename=NULL, ...)
Settings(basename=NULL, ...)
basename |
A |
... |
Arguments passed to constructor of superclass Options. |
Methods:
findSettings |
- | |
getLoadedPathname |
- | |
isModified |
- | |
loadAnywhere |
- | |
promptAndSave |
- | |
saveAnywhere |
- | |
Methods inherited from Options:
as.character, as.list, equals, getLeaves, getOption, hasOption, names, nbrOfOptions, setOption, str
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Here is a generic .First.lib()
function for loading settings
with package. It also (almost) assures that the package is detached
when R finishes. See onSessionExit
() why it is not guaranteed!
The almost generic .Last.lib()
function, which will prompt
user to save settings, is called when a package is detached.
It is custom to put these functions in a file named zzz.R
.
.First.lib():
.First.lib <- function(libname, pkgname) { # Write a welcome message when package is loaded pkg <- Package(pkgname) assign(pkgname, pkg, pos=getPosition(pkg)) # Read settings file ".<pkgname>Settings" and store it in package # variable '<pkgname>Settings'. varname <- paste(pkgname, "Settings") basename <- paste(".", varname, sep="") settings <- Settings$loadAnywhere(basename, verbose=TRUE) if (is.null(settings)) settings <- Settings(basename) assign(varname, settings, pos=getPosition(pkg)) # Detach package when R finishes, which will save package settings too. onSessionExit(function(...) detachPackage(pkgname)) packageStartupMessage(getName(pkg), " v", getVersion(pkg), " (", getDate(pkg), ") successfully loaded. See ?", pkgname, " for help.\n", sep="") } # .First.lib()
.Last.lib():
.Last.lib <- function(libpath) { pkgname <- "<package name>" # Prompt and save package settings when package is detached. varname <- paste(pkgname, "Settings", sep="") if (exists(varname)) { settings <- get(varname) if (inherits(settings, "Settings")) promptAndSave(settings) } } # .Last.lib()
Henrik Bengtsson
# Load settings from file, or create default settings basename <- "some.settings" settings <- Settings$loadAnywhere(basename) if (is.null(settings)) settings <- Settings(basename) # Set default options, if missing. setOption(settings, "graphics/verbose", TRUE, overwrite=FALSE) setOption(settings, "io/verbose", Verbose(threshold=-1), overwrite=FALSE) # Save and reload settings path <- tempdir() saveAnywhere(settings, path=path) settings2 <- Settings$loadAnywhere(basename, paths=path) # Clean up file.remove(getLoadedPathname(settings2)) # Assert correctness stopifnot(equals(settings, settings2))
# Load settings from file, or create default settings basename <- "some.settings" settings <- Settings$loadAnywhere(basename) if (is.null(settings)) settings <- Settings(basename) # Set default options, if missing. setOption(settings, "graphics/verbose", TRUE, overwrite=FALSE) setOption(settings, "io/verbose", Verbose(threshold=-1), overwrite=FALSE) # Save and reload settings path <- tempdir() saveAnywhere(settings, path=path) settings2 <- Settings$loadAnywhere(basename, paths=path) # Clean up file.remove(getLoadedPathname(settings2)) # Assert correctness stopifnot(equals(settings, settings2))
Open a file or URL using Windows File Associations using shell.exec()
but makes some tweaks
to filenames to make them more likely to be opened properly.
This function is only applicable on Windows systems.
shell.exec2(file)
shell.exec2(file)
file |
A |
Before passing a file on the file system to
shell.exec()
, this function:
(i) unmaps any mapped drive letters used in the pathname
(e.g. 'X:/foo.bar.html' to 'C:/Users/Joe/bar.html'),
(ii) and replaces any forward slashed with backward ones
(e.g. 'C:/Users/Joe/bar.html' to 'C:\Users\Joe\bar.html').
URLs are passed as is to shell.exec()
.
The reason for (i) is that some web browsers (e.g. Google Chrome)
will not open files on mapped drives.
The reason for (ii) is that if forward slashes are used, then
shell.exec()
will give an error that the file was
not found (at least with the default Windows shell).
Returns nothing.
The intended usage of this function is to set it as the default
browser for browseURL
. Just add the following to
your .Rprofile
file:
if (.Platform$OS.type == "windows") options(browser=function(...) R.utils::shell.exec2(...))
This will only load (not attach) the R.utils package when the browser function is actual used.
Henrik Bengtsson
Package: R.utils
Class SmartComments
Object
~~|
~~+--
SmartComments
Directly known subclasses:
LComments, VComments
public abstract static class SmartComments
extends Object
Abstract class SmartComments.
SmartComments(letter=NA, ...)
SmartComments(letter=NA, ...)
letter |
A single |
... |
Not used. |
A "smart" source-code comment is an R comment, which start with a '#',
but is followed by a single letter, then a single symbol and a second
'#' and then an option character string, and there must not be any code
before the comment on the same line. In summary, a smart comment line
has format: <white spaces>#<letter><symbol># <some text>
.
Example code with two smart comments (VComments):
x <- 2 #V1# threshold=-1 #Vc# A v-comment log message cat("Hello world")
which after compilation becomes
x <- 2 verbose <- Verbose(threshold=-1) if (verbose) { cat(verbose, "A v-comment log message"); } cat("Hello world")
Methods:
compile |
- | |
convertComment |
- | |
parse |
- | |
reset |
- | |
validate |
- | |
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
Sources files recursively to either local or global environment.
## Default S3 method: sourceDirectory(path, pattern=".*[.](r|R|s|S|q)([.](lnk|LNK))*$", recursive=TRUE, envir=parent.frame(), onError=c("error", "warning", "skip"), modifiedOnly=TRUE, ..., verbose=FALSE)
## Default S3 method: sourceDirectory(path, pattern=".*[.](r|R|s|S|q)([.](lnk|LNK))*$", recursive=TRUE, envir=parent.frame(), onError=c("error", "warning", "skip"), modifiedOnly=TRUE, ..., verbose=FALSE)
path |
A path to a directory to be sourced. |
pattern |
A regular expression file name pattern to identify source code files. |
recursive |
If |
envir |
An |
onError |
If an error occurs, the error may stop the job, give a warning, or silently be skipped. |
modifiedOnly |
If |
... |
Additional arguments passed to |
verbose |
Returns a vector
of the full pathnames of the files sourced.
Subdirectories and files in each (sub-)directory are sourced in lexicographic order.
This method does not provide hooks, but the internally used
sourceTo
() does.
Henrik Bengtsson
sourceTo
() and compare to source
().
Parses and evaluates code from a file or a connection.
This has the same effect as if source(..., local=TRUE)
would have
been called from within the given environment.
This is useful when setting up a new local working environment.
## Default S3 method: sourceTo(file, path=NULL, chdir=FALSE, ..., local=TRUE, envir=parent.frame(), modifiedOnly=FALSE)
## Default S3 method: sourceTo(file, path=NULL, chdir=FALSE, ..., local=TRUE, envir=parent.frame(), modifiedOnly=FALSE)
file |
A |
path |
An optional |
chdir |
If |
... |
Arguments to |
local |
If |
envir |
An |
modifiedOnly |
If |
Return the result of source
().
This methods recognizes the hook sourceTo/onPreprocess
, which
is called after the lines in file has been read, but before they have
been parsed by the R parser, cf. parse
().
An onPreprocess
hook function should take a character
vector
of code lines and return a character
vector
of code lines.
This can for instance be used to pre-process R source code with special
directives such as VComments
.
Note that only one hook function can be used for this function, otherwise an error is generated.
Henrik Bengtsson
sourceDirectory
().
sys.source
() and source
().
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Example 1 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat("=== Example 1 ================================================\n") foo <- function(file, ...) { cat("Local objects before calling sourceTo():\n") print(ls()) res <- sourceTo(file, ...) cat("Local objects after calling sourceTo():\n") print(ls()) } cat("Global objects before calling foo():\n") lsBefore <- NA lsBefore <- ls() foo(file=textConnection(c('a <- 1', 'b <- 2'))) cat("Global objects after calling foo():\n") stopifnot(length(setdiff(ls(), lsBefore)) == 0) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Example 2 - with VComments preprocessor # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat("=== Example 2 ================================================\n") preprocessor <- function(lines, ...) { cat("-----------------------------------------\n") cat("Source code before preprocessing:\n") displayCode(code=lines, pager="console") cat("-----------------------------------------\n") cat("Source code after preprocessing:\n") lines <- VComments$compile(lines) displayCode(code=lines, pager="console") cat("-----------------------------------------\n") lines } oldHooks <- getHook("sourceTo/onPreprocess") setHook("sourceTo/onPreprocess", preprocessor, action="replace") code <- c( 'x <- 2', '#V1# threshold=-1', '#Vc# A v-comment log message', 'print("Hello world")' ) fh <- textConnection(code) sourceTo(fh) setHook("sourceTo/onPreprocess", oldHooks, action="replace")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Example 1 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat("=== Example 1 ================================================\n") foo <- function(file, ...) { cat("Local objects before calling sourceTo():\n") print(ls()) res <- sourceTo(file, ...) cat("Local objects after calling sourceTo():\n") print(ls()) } cat("Global objects before calling foo():\n") lsBefore <- NA lsBefore <- ls() foo(file=textConnection(c('a <- 1', 'b <- 2'))) cat("Global objects after calling foo():\n") stopifnot(length(setdiff(ls(), lsBefore)) == 0) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Example 2 - with VComments preprocessor # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat("=== Example 2 ================================================\n") preprocessor <- function(lines, ...) { cat("-----------------------------------------\n") cat("Source code before preprocessing:\n") displayCode(code=lines, pager="console") cat("-----------------------------------------\n") cat("Source code after preprocessing:\n") lines <- VComments$compile(lines) displayCode(code=lines, pager="console") cat("-----------------------------------------\n") lines } oldHooks <- getHook("sourceTo/onPreprocess") setHook("sourceTo/onPreprocess", preprocessor, action="replace") code <- c( 'x <- 2', '#V1# threshold=-1', '#Vc# A v-comment log message', 'print("Hello world")' ) fh <- textConnection(code) sourceTo(fh) setHook("sourceTo/onPreprocess", oldHooks, action="replace")
Splits a single character string by pattern. The main difference compared to strsplit
()
is that this method also returns the part of the string that matched
the pattern. Also, it only takes a single character string.
## Default S3 method: splitByPattern(str, pattern, ...)
## Default S3 method: splitByPattern(str, pattern, ...)
str |
A single |
pattern |
A regular expression |
... |
Not used. |
Returns a named character
vector
with names equal to "TRUE"
if element is a pattern part and "FALSE"
otherwise.
Henrik Bengtsson
Compare to strsplit
().
rspCode <- "<body>Hello <%=\"world\"%></body>" rspParts <- splitByPattern(rspCode, pattern="<%.*%>") cat(rspCode, "\n") print(rspParts)
rspCode <- "<body>Hello <%=\"world\"%></body>" rspParts <- splitByPattern(rspCode, pattern="<%.*%>") cat(rspCode, "\n") print(rspParts)
Writes text in the margin along the sides of a plot.
## Default S3 method: stext(text, side=1, line=0, pos=0.5, margin=c(0.2, 0.2), charDim=c(strwidth("M", cex = cex), strheight("M", cex = cex)), cex=par("cex"), ...)
## Default S3 method: stext(text, side=1, line=0, pos=0.5, margin=c(0.2, 0.2), charDim=c(strwidth("M", cex = cex), strheight("M", cex = cex)), cex=par("cex"), ...)
text |
The text to be written. See |
side |
An |
line |
A |
pos |
A |
margin |
|
charDim |
A |
cex |
A |
... |
Additional arguments passed to |
Returns what mtext
returns.
Henrik Bengtsson
Internally mtext
is used.
Creates a grid of subplots in the current figure. If arguments
nrow
and ncol
are given a nrow
-by-ncol
grid of subplots are created. If only argument n
is given
then a r-by-s grid is created where |r-s| <= 1, i.e. a square or almost
a square of subplots is created. If n
and nrow
is
given then a grid with nrow
rows and at least n
subplots
are created. Similar if n
and ncol
is given.
The argument byrow
specifies if the order of the subplots
should be rowwise (byrow=TRUE
) or columnwise.
## Default S3 method: subplots(n=1, nrow=NULL, ncol=NULL, byrow=TRUE, ...)
## Default S3 method: subplots(n=1, nrow=NULL, ncol=NULL, byrow=TRUE, ...)
n |
If given, the minimum number of subplots. |
nrow |
If given, the number of rows the grid of subplots should contain. |
ncol |
If given, the number of columns the grid of subplots should contain. |
byrow |
If |
... |
Not used. |
Returns the matrix
containing the order of plots.
Henrik Bengtsson
layout
and layout.show
().
subplots(nrow=2, ncol=3) # 2-by-3 grid of subplots subplots(n=6, nrow=2) # 2-by-3 grid of subplots subplots(n=5, ncol=2) # 3-by-2 grid of subplots subplots(1) # (Reset) to a 1-by-1 grid of subplots subplots(2) # 1-by-2 grid of subplots subplots(3) # 2-by-2 grid of subplots l <- subplots(8) # 3-by-3 grid of subplots layout.show(length(l))
subplots(nrow=2, ncol=3) # 2-by-3 grid of subplots subplots(n=6, nrow=2) # 2-by-3 grid of subplots subplots(n=5, ncol=2) # 3-by-2 grid of subplots subplots(1) # (Reset) to a 1-by-1 grid of subplots subplots(2) # 1-by-2 grid of subplots subplots(3) # 2-by-2 grid of subplots l <- subplots(8) # 3-by-3 grid of subplots layout.show(length(l))
Package: R.utils
Class System
Object
~~|
~~+--
System
Directly known subclasses:
public static class System
extends Object
The System class contains several useful class fields and methods. It cannot be instantiated.
Methods:
currentTimeMillis |
- | |
findGhostscript |
- | |
findGraphicsDevice |
- | |
getHostname |
- | |
getMappedDrivesOnWindows |
- | |
getUsername |
- | |
mapDriveOnWindows |
- | |
openBrowser |
- | |
parseDebian |
- | |
unmapDriveOnWindows |
- | |
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
Launches another R process from within R via system
() by automatically locating the
R executable, cf [1].
## Default S3 method: systemR(command="", ..., Rcommand="R", verbose=FALSE)
## Default S3 method: systemR(command="", ..., Rcommand="R", verbose=FALSE)
command |
A |
... |
Additional arguments passed to |
Rcommand |
A |
verbose |
Returns what system
() returns.
Henrik Bengtsson
[1] R-devel thread 'Best way to locate R executable from within R?', May 22, 2012.
The R executable is located using R.home
(), which
is then launched using system
().
res <- systemR(paste("--slave -e", shQuote("cat(runif(1))")), intern=TRUE) cat("A random number: ", res, "\n", sep="")
res <- systemR(paste("--slave -e", shQuote("cat(runif(1))")), intern=TRUE) cat("A random number: ", res, "\n", sep="")
Package: R.utils
Class TextStatusBar
Object
~~|
~~+--
TextStatusBar
Directly known subclasses:
public static class TextStatusBar
extends Object
A status bar at the R prompt that can be updated.
TextStatusBar(fmt=paste("%-", getOption("width") - 1, "s", sep = ""), ...)
TextStatusBar(fmt=paste("%-", getOption("width") - 1, "s", sep = ""), ...)
fmt |
A |
... |
Named arguments to be passed to |
A label with name hfill
can be used for automatic horizontal
filling. It must be numeric
and be immediate before a string
label such that a hfill
label and the following string label
together specifies an sprintf format such as "%*-s"
.
The value of hfill
will be set such that the resulting status
bar has width equal to getOption("width")-1
(the reason for the
-1 is to prevent the text status bar from writing into the next line).
If more than one hfill
label is used their widths will be
uniformly distributed. Left over spaces will be distributed between
hfill
labels with initial values of one.
Methods:
flush |
- | |
getLabel |
- | |
newline |
- | |
popMessage |
- | |
setLabel |
- | |
setLabels |
- | |
update |
- | |
updateLabels |
- | |
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Read all HTML files in the base package # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - path <- system.file(package="base") files <- list.files(path, recursive=TRUE, full.names=TRUE) files <- files[sapply(files, FUN=isFile)] nfiles <- length(files) cat(sprintf("Reading %d files in %s:\n", nfiles, path)) # Create a status bar with four labels sb <- TextStatusBar("File: %-*s [%3.0f%% %7.0f bytes %-8s]", hfill=1, file="", progress=0, nbytes=0L, time="") nbytes <- 0L for (kk in seq_len(nfiles)) { file <- files[kk] # Update the status bar if (sb) { setLabel(sb, "progress", 100*kk/nfiles) if (kk %% 10 == 1 || kk == nfiles) setLabel(sb, "file", substr(basename(file), 1, 44)) size <- file.info(file)$size # popMessage() calls update() too popMessage(sb, sprintf("Processing %s (%.2fkB)", basename(file), size/1024)) flush(sb) } # Read the file bfr <- readBin(file, what="raw", n=size) nbytes <- nbytes + size # Emulate a slow process if (interactive()) Sys.sleep(rexp(1, rate=60)) # Update the status bar if (sb) { setLabel(sb, "nbytes", nbytes) setLabel(sb, "time", format(Sys.time(), "%H:%M:%S")) update(sb) } } setLabel(sb, "file", "<done>") update(sb) cat("\n")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Read all HTML files in the base package # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - path <- system.file(package="base") files <- list.files(path, recursive=TRUE, full.names=TRUE) files <- files[sapply(files, FUN=isFile)] nfiles <- length(files) cat(sprintf("Reading %d files in %s:\n", nfiles, path)) # Create a status bar with four labels sb <- TextStatusBar("File: %-*s [%3.0f%% %7.0f bytes %-8s]", hfill=1, file="", progress=0, nbytes=0L, time="") nbytes <- 0L for (kk in seq_len(nfiles)) { file <- files[kk] # Update the status bar if (sb) { setLabel(sb, "progress", 100*kk/nfiles) if (kk %% 10 == 1 || kk == nfiles) setLabel(sb, "file", substr(basename(file), 1, 44)) size <- file.info(file)$size # popMessage() calls update() too popMessage(sb, sprintf("Processing %s (%.2fkB)", basename(file), size/1024)) flush(sb) } # Read the file bfr <- readBin(file, what="raw", n=size) nbytes <- nbytes + size # Emulate a slow process if (interactive()) Sys.sleep(rexp(1, rate=60)) # Update the status bar if (sb) { setLabel(sb, "nbytes", nbytes) setLabel(sb, "time", format(Sys.time(), "%H:%M:%S")) update(sb) } } setLabel(sb, "file", "<done>") update(sb) cat("\n")
Package: R.utils
Class TimeoutException
Object
~~|
~~+--
try-error
~~~~~~~|
~~~~~~~+--
condition
~~~~~~~~~~~~|
~~~~~~~~~~~~+--
error
~~~~~~~~~~~~~~~~~|
~~~~~~~~~~~~~~~~~+--
simpleError
~~~~~~~~~~~~~~~~~~~~~~|
~~~~~~~~~~~~~~~~~~~~~~+--
Exception
~~~~~~~~~~~~~~~~~~~~~~~~~~~|
~~~~~~~~~~~~~~~~~~~~~~~~~~~+--
TimeoutException
Directly known subclasses:
public static class TimeoutException
extends Exception
TimeoutException represents timeout errors occurring when a set of R expressions executed did not finish in time.
TimeoutException(..., cpu=NA, elapsed=NA)
TimeoutException(..., cpu=NA, elapsed=NA)
... |
Any arguments accepted by |
.
cpu , elapsed
|
The maximum time the R expressions were allowed to be running before the timeout occurred as measured in CPU time and (physically) elapsed time. |
Methods:
getMessage |
- | |
Methods inherited from Exception:
as.character, getCall, getCalls, getLastException, getMessage, getStackTrace, getWhen, print, printStackTrace, throw
Methods inherited from error:
as.character, throw
Methods inherited from condition:
abort, as.character, conditionCall, conditionMessage, print
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
For detailed information about exceptions see Exception
.
Updates the timestamp of a file. Currently, it is only possible to change the timestamp specifying when the file was last modified, and time can only be set to the current time.
## Default S3 method: touchFile(pathname, ...)
## Default S3 method: touchFile(pathname, ...)
pathname |
|
... |
Not used. |
Returns (invisibly) a vector
of the old timestamps.
Henrik Bengtsson
[1] R-devel mailing list thread
Unix-like touch to update modification timestamp of file?,
started on 2008-02-26.
https://stat.ethz.ch/pipermail/r-devel/2008-February/048542.html
Internally, Sys.setFileTime
() (iff available) and
file.info
() are utilized.
# 1. Create a file pathname <- tempfile() cat(file=pathname, "Hello world!") md5a <- digest::digest(pathname, file=TRUE) # 2. Current time stamp ta <- file.info(pathname)$mtime print(ta) # 3. Update time stamp Sys.sleep(1.2) touchFile(pathname) tb <- file.info(pathname)$mtime print(tb) # 4. Verify that the timestamp got updated stopifnot(tb > ta) # 5. Verify that the contents did not change md5b <- digest::digest(pathname, file=TRUE) stopifnot(identical(md5a, md5b))
# 1. Create a file pathname <- tempfile() cat(file=pathname, "Hello world!") md5a <- digest::digest(pathname, file=TRUE) # 2. Current time stamp ta <- file.info(pathname)$mtime print(ta) # 3. Update time stamp Sys.sleep(1.2) touchFile(pathname) tb <- file.info(pathname)$mtime print(tb) # 4. Verify that the timestamp got updated stopifnot(tb > ta) # 5. Verify that the contents did not change md5b <- digest::digest(pathname, file=TRUE) stopifnot(identical(md5a, md5b))
Converts a pathname into a URL starting with file://
.
## Default S3 method: toUrl(pathname, safe=TRUE, ...)
## Default S3 method: toUrl(pathname, safe=TRUE, ...)
pathname |
|
safe |
If |
... |
Not used. |
Henrik Bengtsson
Unwrap an array, matrix or a vector to an array of more dimensions. This is done by splitting up each dimension into several dimension based on the names of that dimension.
## S3 method for class 'array' unwrap(x, split=rep("[.]", length(dim(x))), drop=FALSE, ...)
## S3 method for class 'array' unwrap(x, split=rep("[.]", length(dim(x))), drop=FALSE, ...)
x |
|
split |
A |
drop |
If |
... |
Arguments passed to the |
Although not tested thoroughly, unwrap()
should be the inverse
of wrap()
such that identical(unwrap(wrap(x)), x)
holds.
Returns an array
.
Henrik Bengtsson
*wrap()
.
## Not run: See ?wrap.array for an example
## Not run: See ?wrap.array for an example
Sets package repositories.
useRepos(repos=NULL, where=c("before", "after", "replace"), unique=TRUE, fallback=TRUE, ...)
useRepos(repos=NULL, where=c("before", "after", "replace"), unique=TRUE, fallback=TRUE, ...)
repos |
A |
where |
A |
unique |
If |
fallback |
If |
... |
Not used. |
Returns a list
with element 'repos' reflecting options("repos")
as the options where prior to calling this function.
Henrik Bengtsson
withRepos
().
Package: R.utils
Class VComments
Object
~~|
~~+--
SmartComments
~~~~~~~|
~~~~~~~+--
VComments
Directly known subclasses:
LComments
public static class VComments
extends SmartComments
The VComments class.
VComments(letter="V", verboseName="verbose", ...)
VComments(letter="V", verboseName="verbose", ...)
letter |
The smart letter. |
verboseName |
The name of the verbose object. |
... |
Not used. |
The 'v' in VComments stands for 'verbose', because of its relationship
to the Verbose
class.
Here is a list of VComments and the R code that replaces each of them by the compiler:
Constructors
[<args>] - NullVerbose(<args>)
[<args>] - Verbose(<args>)
Controls
[<variable>] - Sets the name of the <verbose> object. Default is 'verbose'.
<threshold> - setThreshold(<verbose>, <threshold>)
<expression> - if (isVisible(<verbose>)) { <expression> }
<level> - setDefaultLevel(<verbose>, <level>)
<method> <args> - <method>(<verbose>, <args>)
Enters and exits
[<message>] - enter(<verbose>, <message>)
[<message>] - exit(<verbose>, <message>)
[<message>] - pushState(<verbose>)
on.exit(popState(<verbose>))
If <message>, enter(<verbose>, <message>)
Simple output
<ignored> - newline(<verbose>)
<ignored> - ruler(<verbose>)
<ignored> - timestamp(<verbose>)
[<title>] - warnings(<verbose>, <title>)
Output messages
[<message>] - cat(<verbose>, <message>)
<expression> - eval(<verbose>, <expression>)
<message> - header(<verbose>, <message>)
<object> - print(<verbose>, <object>)
<object> - summary(<verbose>, <object>)
<object> - str(<verbose>, <object>)
Methods:
convertComment |
- | |
reset |
- | |
validate |
- | |
Methods inherited from SmartComments:
compile, convertComment, parse, reset, validate
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
Henrik Bengtsson
filename <- system.file("data-ex/exampleVComments.R", package="R.utils") lines <- readLines(filename) cat("Code before preprocessing:\n") displayCode(code=lines, pager="console") lines <- VComments$compile(lines) cat("Code after preprocessing:\n") displayCode(code=lines, pager="console")
filename <- system.file("data-ex/exampleVComments.R", package="R.utils") lines <- readLines(filename) cat("Code before preprocessing:\n") displayCode(code=lines, pager="console") lines <- VComments$compile(lines) cat("Code after preprocessing:\n") displayCode(code=lines, pager="console")
Package: R.utils
Class Verbose
Object
~~|
~~+--
Verbose
Directly known subclasses:
MultiVerbose, NullVerbose
public static class Verbose
extends Object
Class to writing verbose messages to a connection or file.
Verbose(con=stderr(), on=TRUE, threshold=0, asGString=TRUE, timestamp=FALSE, removeFile=TRUE, core=TRUE, ...)
Verbose(con=stderr(), on=TRUE, threshold=0, asGString=TRUE, timestamp=FALSE, removeFile=TRUE, core=TRUE, ...)
con |
A |
on |
A |
threshold |
A |
timestamp |
If |
removeFile |
If |
asGString |
If |
core |
Internal use only. |
... |
Not used. |
Methods:
as.character |
- | |
as.double |
- | |
as.logical |
- | |
capture |
- | |
cat |
- | |
enter |
- | |
enterf |
- | |
equals |
- | |
evaluate |
- | |
exit |
- | |
getThreshold |
- | |
getTimestampFormat |
- | |
header |
- | |
isOn |
- | |
isVisible |
- | |
less |
- | |
more |
- | |
newline |
- | |
off |
- | |
on |
- | |
popState |
- | |
print |
- | |
printWarnings |
- | |
printf |
- | |
pushState |
- | |
ruler |
- | |
setDefaultLevel |
- | |
setThreshold |
- | |
setTimestampFormat |
- | |
str |
- | |
summary |
- | |
timestamp |
- | |
timestampOff |
- | |
timestampOn |
- | |
writeRaw |
- | |
Methods inherited from Object:
$, $<-, [[, [[<-, as.character, attach, attachLocally, clearCache, clearLookupCache, clone, detach, equals, extend, finalize, getEnvironment, getFieldModifier, getFieldModifiers, getFields, getInstantiationTime, getStaticInstance, hasField, hashCode, ll, load, names, objectSize, print, save
As a guideline, use the following levels when outputting verbose/debug message using the Verbose class. For a message to be shown, the output level must be greater than (not equal to) current threshold. Thus, the lower the threshold is set, the more messages will be seen.
Only for debug messages, i.e. messages containing all necessary information for debugging purposes and to find bugs in the code. Normally these messages are so detailed so they will be a pain for the regular user, but very useful for bug reporting and bug tracking by the developer.
Detailed verbose messages. These will typically be useful for the user to understand what is going on and do some simple debugging fixing problems typically due to themselves and not due to bugs in the code.
Verbose messages. For example, these will typically report the name of the file to be read, the current step in a sequence of analysis steps and so on. These message are not very useful for debugging.
Default level in all output methods and default threshold. Thus, by default, messages at level 0 are not shown.
Message that are always outputted (if threshold is kept at 0). We recommend not to output message at this level, because methods should be quiet by default (at the default threshold 0).
If you want to include calls to Verbose in a package of yours in order
to debug code, but not use it otherwise, you might not want to load
R.utils all the time, but only for debugging.
To achieve this, the value of a reference variable to a Verbose class
is always set to TRUE
, cf. typically an Object reference has value NA
.
This makes it possible to use the reference variable as a first test
before calling Verbose methods. Example:
foo <- function(..., verbose=FALSE) { # enter() will never be called if verbose==FALSE, thus no error. verbose && enter(verbose, "Loading") }
Thus, R.utils is not required for foo()
, but for
foo(verbose==Verbose(level=-1))
it is.
Moreover, if using the NullVerbose
class for ignoring all verbose
messages, the above trick will indeed speed up the code, because
the value of a NullVerbose reference variable is always FALSE
.
If extending this class, make sure to output messages via
*writeRaw()
or one of the other output methods (which in
turn all call the former).
This guarantees that *writeRaw()
has full control of the
output, e.g. this makes it possible to split output to standard
output and to file.
Henrik Bengtsson
verbose <- Verbose(threshold=-1) header(verbose, "A verbose writer example", padding=0) enter(verbose, "Analysis A") for (kk in 1:10) { printf(verbose, "step %d\n", kk) if (kk == 2) { cat(verbose, "Turning ON automatic timestamps") timestampOn(verbose) } else if (kk == 4) { timestampOff(verbose) cat(verbose, "Turned OFF automatic timestamps") cat(verbose, "Turning OFF verbose messages for steps ", kk, "-6") off(verbose) } else if (kk == 6) { on(verbose) cat(verbose, "Turned ON verbose messages just before step ", kk+1) } if (kk %in% c(5,8)) { enterf(verbose, "Sub analysis #%d", kk) for (jj in c("i", "ii", "iii")) { cat(verbose, "part ", jj) } exit(verbose) } } cat(verbose, "All steps completed!") exit(verbose) ruler(verbose) cat(verbose, "Demo of some other methods:") str(verbose, c(a=1, b=2, c=3)) print(verbose, c(a=1, b=2, c=3)) summary(verbose, c(a=1, b=2, c=3)) evaluate(verbose, rnorm, n=3, mean=2, sd=3) ruler(verbose) newline(verbose)
verbose <- Verbose(threshold=-1) header(verbose, "A verbose writer example", padding=0) enter(verbose, "Analysis A") for (kk in 1:10) { printf(verbose, "step %d\n", kk) if (kk == 2) { cat(verbose, "Turning ON automatic timestamps") timestampOn(verbose) } else if (kk == 4) { timestampOff(verbose) cat(verbose, "Turned OFF automatic timestamps") cat(verbose, "Turning OFF verbose messages for steps ", kk, "-6") off(verbose) } else if (kk == 6) { on(verbose) cat(verbose, "Turned ON verbose messages just before step ", kk+1) } if (kk %in% c(5,8)) { enterf(verbose, "Sub analysis #%d", kk) for (jj in c("i", "ii", "iii")) { cat(verbose, "part ", jj) } exit(verbose) } } cat(verbose, "All steps completed!") exit(verbose) ruler(verbose) cat(verbose, "Demo of some other methods:") str(verbose, c(a=1, b=2, c=3)) print(verbose, c(a=1, b=2, c=3)) summary(verbose, c(a=1, b=2, c=3)) evaluate(verbose, rnorm, n=3, mean=2, sd=3) ruler(verbose) newline(verbose)
Evaluates an expression and captures the code and/or the output.
withCapture(expr, replace=getOption("withCapture/substitute", ".x."), code=TRUE, output=code, ..., max.deparse.length=getOption("max.deparse.length", 10000), trim=TRUE, newline=getOption("withCapture/newline", TRUE), collapse="\n", envir=parent.frame())
withCapture(expr, replace=getOption("withCapture/substitute", ".x."), code=TRUE, output=code, ..., max.deparse.length=getOption("max.deparse.length", 10000), trim=TRUE, newline=getOption("withCapture/newline", TRUE), collapse="\n", envir=parent.frame())
expr |
The R expression to be evaluated. |
replace |
An optional named |
code |
If |
output |
If |
... |
Additional arguments passed to |
max.deparse.length |
A positive |
trim |
If |
newline |
If |
collapse |
A |
envir |
The |
Returns a character
string class 'CapturedEvaluation'.
Henrik Bengtsson
Internally, eval
() is used to evaluate the expression.
print(withCapture({ n <- 3 n for (kk in 1:3) { printf("Iteration #%d\n", kk) } print(Sys.time()) type <- "horse" type })) ## > n <- 3 ## > n ## [1] 3 ## > for (kk in 1:3) { ## + printf("Iteration #%d\n", kk) ## + } ## Iteration #1 ## Iteration #2 ## Iteration #3 ## > print(Sys.time()) ## [1] "2011-11-06 11:06:32 PST" ## > type <- "horse" ## > type ## [1] "horse" # Automatic "variable" substitute # (disable with relabel=NULL) a <- 2 b <- "Hello world!" print(withCapture({ x <- .a. s <- .b. x s })) ## > x <- 2 ## > s <- "Hello world!" ## > x ## [1] 2 ## > s ## [1] "Hello world!"
print(withCapture({ n <- 3 n for (kk in 1:3) { printf("Iteration #%d\n", kk) } print(Sys.time()) type <- "horse" type })) ## > n <- 3 ## > n ## [1] 3 ## > for (kk in 1:3) { ## + printf("Iteration #%d\n", kk) ## + } ## Iteration #1 ## Iteration #2 ## Iteration #3 ## > print(Sys.time()) ## [1] "2011-11-06 11:06:32 PST" ## > type <- "horse" ## > type ## [1] "horse" # Automatic "variable" substitute # (disable with relabel=NULL) a <- 2 b <- "Hello world!" print(withCapture({ x <- .a. s <- .b. x s })) ## > x <- 2 ## > s <- "Hello world!" ## > x ## [1] 2 ## > s ## [1] "Hello world!"
Evaluate an R expression with locale set temporarily.
withLocale(expr, category, locale, ..., substitute=TRUE, envir=parent.frame())
withLocale(expr, category, locale, ..., substitute=TRUE, envir=parent.frame())
expr |
The R expression to be evaluated. |
category |
A |
locale |
|
... |
Not used. |
substitute |
If |
envir |
The |
Returns the results of the expression evaluated.
Henrik Bengtsson
Internally, eval
() is used to evaluate the expression.
and Sys.setlocale
() to set locale.
# Vector cat("Original vector:\n") x <- c(letters[1:8], LETTERS[1:8]) print(x) cat("Sorting with 'C' locale:\n") y1 <- withLocale(sort(x), "LC_COLLATE", "C") print(y1) cat("Sorting with an 'English' locale:\n") y2 <- withLocale(sort(x), "LC_COLLATE", c("en_US", "en_US.UTF8", "English_United States.1252")) print(y2)
# Vector cat("Original vector:\n") x <- c(letters[1:8], LETTERS[1:8]) print(x) cat("Sorting with 'C' locale:\n") y1 <- withLocale(sort(x), "LC_COLLATE", "C") print(y1) cat("Sorting with an 'English' locale:\n") y2 <- withLocale(sort(x), "LC_COLLATE", c("en_US", "en_US.UTF8", "English_United States.1252")) print(y2)
Evaluate an R expression with options set temporarily.
withOptions(expr, ..., args=list(), substitute=TRUE, envir=parent.frame())
withOptions(expr, ..., args=list(), substitute=TRUE, envir=parent.frame())
expr |
The R expression to be evaluated. |
... |
Named options to be used. |
args |
(optional) Additional named options specified as a named |
substitute |
If |
envir |
The |
Upon exit (also on errors), this function will reset all
options to the state of options available upon entry. This means
any options modified but also those added when
evaluating expr
will also be undone upon exit.
Returns the results of the expression evaluated.
Henrik Bengtsson
Internally, eval
() is used to evaluate the expression.
and options
() to set options.
print(pi) # Same, i.e. using default withOptions({ print(pi) }) # Printing with two digits withOptions({ print(pi) }, digits=2) # Printing with two digits then with three more withOptions({ print(pi) withOptions({ print(pi) }, digits=getOption("digits")+3) }, digits=2) # Still printing with the default print(pi)
print(pi) # Same, i.e. using default withOptions({ print(pi) }) # Printing with two digits withOptions({ print(pi) }, digits=2) # Printing with two digits then with three more withOptions({ print(pi) withOptions({ print(pi) }, digits=getOption("digits")+3) }, digits=2) # Still printing with the default print(pi)
Evaluate an R expression with repositories set temporarily.
withRepos(expr, repos="[[mainstream]]", ..., substitute=TRUE, envir=parent.frame())
withRepos(expr, repos="[[mainstream]]", ..., substitute=TRUE, envir=parent.frame())
expr |
The R expression to be evaluated. |
repos |
|
... |
Additional arguments passed to |
substitute |
If |
envir |
The |
Returns the results of the expression evaluated.
Henrik Bengtsson
Internally, eval
() is used to evaluate the expression.
See also options
() and install.packages
.
## Not run: # Install from BioC related repositories only withRepos(install.packages("edgeR"), repos="[[BioC]]") # Install from CRAN or BioC related repositories only withRepos(install.packages("edgeR"), repos=c("CRAN", "[[BioC]]")) # Install from mainstream repositories only (same as previous) withRepos(install.packages("edgeR"), repos="[[mainstream]]") # Install from R-Forge and mainstream repositories only withRepos(install.packages("R.utils"), repos="[[R-Forge]]") # Update only CRAN packages withRepos(update.packages(ask=FALSE), repos="[[CRAN]]") # Update only Bioconductor packages withRepos(update.packages(ask=FALSE), repos="[[BioC]]") ## End(Not run)
## Not run: # Install from BioC related repositories only withRepos(install.packages("edgeR"), repos="[[BioC]]") # Install from CRAN or BioC related repositories only withRepos(install.packages("edgeR"), repos=c("CRAN", "[[BioC]]")) # Install from mainstream repositories only (same as previous) withRepos(install.packages("edgeR"), repos="[[mainstream]]") # Install from R-Forge and mainstream repositories only withRepos(install.packages("R.utils"), repos="[[R-Forge]]") # Update only CRAN packages withRepos(update.packages(ask=FALSE), repos="[[CRAN]]") # Update only Bioconductor packages withRepos(update.packages(ask=FALSE), repos="[[BioC]]") ## End(Not run)
Evaluate an R expression with a temporarily set random set.
withSeed(expr, seed, ..., substitute=TRUE, envir=parent.frame())
withSeed(expr, seed, ..., substitute=TRUE, envir=parent.frame())
expr |
The R expression to be evaluated. |
seed , ...
|
Arguments passed to |
substitute |
If |
envir |
The |
Upon exit (also on errors), this function will restore
.Random.seed
in the global environment to the value
it had upon entry. If it did not exist, it will be removed.
Returns the results of the expression evaluated.
Henrik Bengtsson
Internally, set.seed
() is used to set the random seed.
# Generate a random number y0 <- runif(1) print(y0) # Generate a random number using the same seed over and over yp <- NULL for (ii in 1:10) { y <- withSeed({ runif(1) }, seed=0x42) print(y) # Assert identical if (!is.null(yp)) stopifnot(identical(y, yp)) yp <- y } # Generate a random number y <- runif(1) print(y)
# Generate a random number y0 <- runif(1) print(y0) # Generate a random number using the same seed over and over yp <- NULL for (ii in 1:10) { y <- withSeed({ runif(1) }, seed=0x42) print(y) # Assert identical if (!is.null(yp)) stopifnot(identical(y, yp)) yp <- y } # Generate a random number y <- runif(1) print(y)
Evaluate an R expression while temporarily diverting output.
withSink(expr, file, append=FALSE, type=c("output", "message"), substitute=TRUE, envir=parent.frame())
withSink(expr, file, append=FALSE, type=c("output", "message"), substitute=TRUE, envir=parent.frame())
expr |
The R expression to be evaluated. |
file |
A writable |
append |
If |
type |
A |
substitute |
If |
envir |
The |
Upon exit (also on errors), this function will close the requested "sink". If additional sinks (of any type) where also opened during the evaluation, those will also be closed with a warning.
Returns the results of the expression evaluated.
Henrik Bengtsson
Internally, sink
() is used to divert any output.
# Divert standard output pathname <- tempfile(fileext=".output.txt") res <- withSink(file=pathname, { print(letters) }) mcat(readLines(pathname), sep="\n") # Divert standard error/messages pathname <- tempfile(fileext=".message.txt") res <- withSink(file=pathname, type="message", { mprint(LETTERS) }) mcat(readLines(pathname), sep="\n")
# Divert standard output pathname <- tempfile(fileext=".output.txt") res <- withSink(file=pathname, { print(letters) }) mcat(readLines(pathname), sep="\n") # Divert standard error/messages pathname <- tempfile(fileext=".message.txt") res <- withSink(file=pathname, type="message", { mprint(LETTERS) }) mcat(readLines(pathname), sep="\n")
Evaluate an R expression and interrupts it if it takes too long.
withTimeout(expr, substitute=TRUE, envir=parent.frame(), timeout, cpu=timeout, elapsed=timeout, onTimeout=c("error", "warning", "silent"), ...)
withTimeout(expr, substitute=TRUE, envir=parent.frame(), timeout, cpu=timeout, elapsed=timeout, onTimeout=c("error", "warning", "silent"), ...)
expr |
The R expression to be evaluated. |
substitute |
If |
envir |
The |
timeout , cpu , elapsed
|
A |
onTimeout |
A |
... |
Not used. |
This method utilizes setTimeLimit
() by first setting the
timeout limits, then evaluating the expression that may or may not
timeout. The method is guaranteed to reset the timeout limits to be
infinitely long upon exiting, regardless whether it returns normally
or preemptively due to a timeout or an error.
Returns the results of the expression evaluated.
If timed out, NULL
is returned if onTimeout
was
"warning"
or "silent"
.
If "error"
a TimeoutException
is thrown.
In order to understand when this function works and when it does not,
it is useful to know that it utilizes R's built-in time-out mechanism,
which sets the limits on what is possible and not.
From setTimeLimit
(), we learn that:
"Time limits are checked whenever a user interrupt could occur. This will happen frequently in R code and during Sys.sleep(*), but only at points in compiled C and Fortran code identified by the code author."
More precisely, if a function is implemented in native code (e.g. C) and the developer of that function does not check for user interrupts, then you cannot interrupt that function neither via a user interrupt (e.g. Ctrl-C) nor via the built-in time out mechanism. To change this, you need to contact the developer of that piece of code and ask them to check for R user interrupts in their native code.
Furthermore, it is not possible to interrupt/break out of a "readline"
prompt (e.g. readline
() and readLines
()) using
timeouts; the timeout exception will not be thrown until after the user
completes the prompt (i.e. after pressing ENTER).
System calls via system
() and system2()
cannot be
timed out via the above mechanisms. However, in R (>= 3.5.0) these
functions have argument timeout
providing their own independent
timeout mechanism.
Other examples of calls that do not support timeout are "atomic"
calls that may take very long such as large object allocation and
rnorm(n)
where n
is very large.
(*) Note that on Unix and macOS, Sys.sleep(time)
will signal a
timeout error only after time
seconds passed,
regardless of timeout
limit (< time
).
withTimeout()
does not handle the case when the expression
evaluated temporarily switches the language used by R, e.g.
assume we run in a non-French locale and call:
withTimeout({ olang <- Sys.getenv("LANGUAGE") on.exit(Sys.setenv(LANGUAGE=olang)) Sys.setenv(LANGUAGE="fr") repeat Sys.sleep(0.1) }, timeout = 1.0, onTimeout = "warning")
In this case, the error message produced by setTimeLimit
() is
in French, i.e. 'la limite de temps est atteinte'. However, when
withTimeout()
inspects this message, it can not know that
French was used, and will therefore not check against the French template
message for timeout errors. Because of this, withTimeout()
fails
to detect the timeout error (and therefore also deescalate it to a
warning in this example).
Comment: This appears to only fail on MS Windows and macOS,
whereas on Linux, withTimeout()
appears to work, but it is
unknown why there is a difference between operating systems in this
case.
Henrik Bengtsson
[1] R help thread 'Time out for a R Function' on 2010-12-07.
https://stat.ethz.ch/pipermail/r-help/2010-December/262316.html
Internally, eval
() is used to evaluate the expression and
setTimeLimit
() is used to control for timeout events.
# - - - - - - - - - - - - - - - - - - - - - - - - - # Function that takes "a long" time to run # - - - - - - - - - - - - - - - - - - - - - - - - - foo <- function() { print("Tic") for (kk in 1:100) { print(kk) Sys.sleep(0.1) } print("Tac") } # - - - - - - - - - - - - - - - - - - - - - - - - - # Evaluate code, if it takes too long, generate # a timeout by throwing a TimeoutException. # - - - - - - - - - - - - - - - - - - - - - - - - - res <- NULL tryCatch({ res <- withTimeout({ foo() }, timeout = 0.75) }, TimeoutException = function(ex) { message("Timeout. Skipping.") }) # - - - - - - - - - - - - - - - - - - - - - - - - - # Evaluate code, if it takes too long, generate # a timeout returning NULL and generate a warning. # - - - - - - - - - - - - - - - - - - - - - - - - - res <- withTimeout({ foo() }, timeout = 0.75, onTimeout = "warning") # The same using an expression object expr <- quote(foo()) res <- withTimeout(expr, substitute = FALSE, timeout = 0.75, onTimeout = "warning") # - - - - - - - - - - - - - - - - - - - - - - - - - # Evaluate code, if it takes too long, generate # a timeout, and return silently NULL. # - - - - - - - - - - - - - - - - - - - - - - - - - res <- withTimeout({ foo() }, timeout = 0.75, onTimeout = "silent")
# - - - - - - - - - - - - - - - - - - - - - - - - - # Function that takes "a long" time to run # - - - - - - - - - - - - - - - - - - - - - - - - - foo <- function() { print("Tic") for (kk in 1:100) { print(kk) Sys.sleep(0.1) } print("Tac") } # - - - - - - - - - - - - - - - - - - - - - - - - - # Evaluate code, if it takes too long, generate # a timeout by throwing a TimeoutException. # - - - - - - - - - - - - - - - - - - - - - - - - - res <- NULL tryCatch({ res <- withTimeout({ foo() }, timeout = 0.75) }, TimeoutException = function(ex) { message("Timeout. Skipping.") }) # - - - - - - - - - - - - - - - - - - - - - - - - - # Evaluate code, if it takes too long, generate # a timeout returning NULL and generate a warning. # - - - - - - - - - - - - - - - - - - - - - - - - - res <- withTimeout({ foo() }, timeout = 0.75, onTimeout = "warning") # The same using an expression object expr <- quote(foo()) res <- withTimeout(expr, substitute = FALSE, timeout = 0.75, onTimeout = "warning") # - - - - - - - - - - - - - - - - - - - - - - - - - # Evaluate code, if it takes too long, generate # a timeout, and return silently NULL. # - - - - - - - - - - - - - - - - - - - - - - - - - res <- withTimeout({ foo() }, timeout = 0.75, onTimeout = "silent")
Reshape an array or a matrix by permuting and/or joining dimensions.
A useful application of this is to reshape a multidimensional array
to a matrix
, which then can be saved to file using for instance
write.table()
.
## S3 method for class 'array' wrap(x, map=list(NA), sep=".", ...)
## S3 method for class 'array' wrap(x, map=list(NA), sep=".", ...)
x |
|
map |
A |
sep |
A |
... |
Not used. |
If the indices in unlist(map)
is in a non-increasing order,
aperm() will be called, which requires reshuffling
of array elements in memory. In all other cases, the reshaping of the
array does not require this, but only fast modifications of
attributes dim
and dimnames
.
Returns an array
of length(map)
dimensions, where the first
dimension is of size prod(map[[1]])
, the second
prod(map[[2]])
, and so on.
Henrik Bengtsson
# Create a 3x2x3 array dim <- c(3,2,3) ndim <- length(dim) dimnames <- list() for (kk in 1:ndim) dimnames[[kk]] <- sprintf("%s%d", letters[kk], 1:dim[kk]) x <- 1:prod(dim) x <- array(x, dim=dim, dimnames=dimnames) cat("Array 'x':\n") print(x) cat("\nReshape 'x' to its identity:\n") y <- wrap(x, map=list(1, 2, 3)) print(y) # Assert correctness of reshaping stopifnot(identical(y, x)) cat("\nReshape 'x' by swapping dimensions 2 and 3, i.e. aperm(x, perm=c(1,3,2)):\n") y <- wrap(x, map=list(1, 3, 2)) print(y) # Assert correctness of reshaping stopifnot(identical(y, aperm(x, perm=c(1,3,2)))) cat("\nWrap 'x' to a matrix 'y' by keeping dimension 1 and joining the others:\n") y <- wrap(x, map=list(1, NA)) print(y) # Assert correctness of reshaping for (aa in dimnames(x)[[1]]) { for (bb in dimnames(x)[[2]]) { for (cc in dimnames(x)[[3]]) { tt <- paste(bb, cc, sep=".") stopifnot(identical(y[aa,tt], x[aa,bb,cc])) } } } cat("\nUnwrap matrix 'y' back to array 'x':\n") z <- unwrap(y) print(z) stopifnot(identical(z,x)) cat("\nWrap a matrix 'y' to a vector and back again:\n") x <- matrix(1:8, nrow=2, dimnames=list(letters[1:2], 1:4)) y <- wrap(x) z <- unwrap(y) print(z) stopifnot(identical(z,x)) cat("\nWrap and unwrap a randomly sized and shaped array 'x2':\n") maxdim <- 5 dim <- sample(1:maxdim, size=sample(2:maxdim, size=1)) ndim <- length(dim) dimnames <- list() for (kk in 1:ndim) dimnames[[kk]] <- sprintf("%s%d", letters[kk], 1:dim[kk]) x2 <- 1:prod(dim) x2 <- array(x, dim=dim, dimnames=dimnames) cat("\nArray 'x2':\n") print(x) # Number of dimensions of wrapped array ndim2 <- sample(1:(ndim-1), size=1) # Create a random map for joining dimensions splits <- NULL if (ndim > 2) splits <- sort(sample(2:(ndim-1), size=ndim2-1)) splits <- c(0, splits, ndim) map <- list() for (kk in 1:ndim2) map[[kk]] <- (splits[kk]+1):splits[kk+1] cat("\nRandom 'map':\n") print(map) cat("\nArray 'y2':\n") y2 <- wrap(x2, map=map) print(y2) cat("\nArray 'x2':\n") z2 <- unwrap(y2) print(z2) stopifnot(identical(z2,x2))
# Create a 3x2x3 array dim <- c(3,2,3) ndim <- length(dim) dimnames <- list() for (kk in 1:ndim) dimnames[[kk]] <- sprintf("%s%d", letters[kk], 1:dim[kk]) x <- 1:prod(dim) x <- array(x, dim=dim, dimnames=dimnames) cat("Array 'x':\n") print(x) cat("\nReshape 'x' to its identity:\n") y <- wrap(x, map=list(1, 2, 3)) print(y) # Assert correctness of reshaping stopifnot(identical(y, x)) cat("\nReshape 'x' by swapping dimensions 2 and 3, i.e. aperm(x, perm=c(1,3,2)):\n") y <- wrap(x, map=list(1, 3, 2)) print(y) # Assert correctness of reshaping stopifnot(identical(y, aperm(x, perm=c(1,3,2)))) cat("\nWrap 'x' to a matrix 'y' by keeping dimension 1 and joining the others:\n") y <- wrap(x, map=list(1, NA)) print(y) # Assert correctness of reshaping for (aa in dimnames(x)[[1]]) { for (bb in dimnames(x)[[2]]) { for (cc in dimnames(x)[[3]]) { tt <- paste(bb, cc, sep=".") stopifnot(identical(y[aa,tt], x[aa,bb,cc])) } } } cat("\nUnwrap matrix 'y' back to array 'x':\n") z <- unwrap(y) print(z) stopifnot(identical(z,x)) cat("\nWrap a matrix 'y' to a vector and back again:\n") x <- matrix(1:8, nrow=2, dimnames=list(letters[1:2], 1:4)) y <- wrap(x) z <- unwrap(y) print(z) stopifnot(identical(z,x)) cat("\nWrap and unwrap a randomly sized and shaped array 'x2':\n") maxdim <- 5 dim <- sample(1:maxdim, size=sample(2:maxdim, size=1)) ndim <- length(dim) dimnames <- list() for (kk in 1:ndim) dimnames[[kk]] <- sprintf("%s%d", letters[kk], 1:dim[kk]) x2 <- 1:prod(dim) x2 <- array(x, dim=dim, dimnames=dimnames) cat("\nArray 'x2':\n") print(x) # Number of dimensions of wrapped array ndim2 <- sample(1:(ndim-1), size=1) # Create a random map for joining dimensions splits <- NULL if (ndim > 2) splits <- sort(sample(2:(ndim-1), size=ndim2-1)) splits <- c(0, splits, ndim) map <- list() for (kk in 1:ndim2) map[[kk]] <- (splits[kk]+1):splits[kk+1] cat("\nRandom 'map':\n") print(map) cat("\nArray 'y2':\n") y2 <- wrap(x2, map=map) print(y2) cat("\nArray 'x2':\n") z2 <- unwrap(y2) print(z2) stopifnot(identical(z2,x2))
Writes binary data to disjoint sections of a connection or a file.
## Default S3 method: writeBinFragments(con, object, idxs, size=NA, ...)
## Default S3 method: writeBinFragments(con, object, idxs, size=NA, ...)
con |
A |
object |
A |
idxs |
A |
size |
The size of the data type to be read. If |
... |
Additional arguments passed to
|
Returns nothing.
Henrik Bengtsson
## Not run: # See example(readBinFragments.connection)
## Not run: # See example(readBinFragments.connection)
Writes a data.frame to tabular text file with an optional header.
## S3 method for class 'data.frame' writeDataFrame(data, file, path=NULL, sep="\t", quote=FALSE, row.names=FALSE, col.names=!append, ..., header=list(), createdBy=NULL, createdOn=format(Sys.time(), format = "%Y-%m-%d %H:%M:%S %Z"), nbrOfRows=nrow(data), headerPrefix="# ", headerSep=": ", append=FALSE, overwrite=FALSE)
## S3 method for class 'data.frame' writeDataFrame(data, file, path=NULL, sep="\t", quote=FALSE, row.names=FALSE, col.names=!append, ..., header=list(), createdBy=NULL, createdOn=format(Sys.time(), format = "%Y-%m-%d %H:%M:%S %Z"), nbrOfRows=nrow(data), headerPrefix="# ", headerSep=": ", append=FALSE, overwrite=FALSE)
data |
A |
file |
A |
path |
The directory where the file will be written. |
sep , quote , row.names , col.names , ...
|
Additional arguments
passed to |
header |
An optional named |
createdBy , createdOn , nbrOfRows
|
If non- |
headerPrefix |
A |
headerSep |
A |
append |
If |
overwrite |
If |
Returns (invisibly) the pathname to the file written
(or the connection
written to).
Henrik Bengtsson
write.table
.
readTable
().