Version: | 2.13.0 |
Depends: | R (≥ 2.14.0), R.oo |
Imports: | methods, utils, tools, R.methodsS3 |
Suggests: | datasets, digest (≥ 0.6.10) |
Title: | Various Programming Utilities |
Author: | Henrik Bengtsson [aut, cre, cph] |
Maintainer: | Henrik Bengtsson <henrikb@braju.com> |
Description: | Utility functions useful when programming and developing R packages. |
License: | LGPL-2.1 | LGPL-3 [expanded from: LGPL (≥ 2.1)] |
LazyLoad: | TRUE |
URL: | https://henrikbengtsson.github.io/R.utils/, https://github.com/HenrikBengtsson/R.utils |
BugReports: | https://github.com/HenrikBengtsson/R.utils/issues |
NeedsCompilation: | no |
Packaged: | 2025-02-24 19:44:20 UTC; henrik |
Repository: | CRAN |
Date/Publication: | 2025-02-24 21:20:02 UTC |
Package R.utils
Description
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)
.
Requirements
This package requires the R.oo package [1].
Installation and updates
To install this package do:
install.packages("R.utils")
To get started
- Arguments
[alpha] Methods for common argument processing.
- Assert
[alpha] Methods for assertion of values and states.
- GString
[alpha] A character string class with methods for simple substitution.
- Java
[beta] Reads and writes Java streams.
- Options
[alpha] Tree-structured options queried in a file-system like manner.
- Settings
[alpha] An Options class for reading and writing package settings.
- ProgressBar
[beta] Text-based progress bar.
- FileProgressBar
[beta] A ProgressBar that reports progress as file size.
- System
[alpha] Methods for access to system.
- Verbose
[alpha] A class for verbose and log output. Utilized by the VComments and LComments classes.
- SmartComments, VComments, LComments
[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.
How to cite this package
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
Wishlist
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!
License
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.
References
[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/
Author(s)
Henrik Bengtsson
Undo changed done by this package when detached
Description
Undo changed done by this package when detached.
Reverts .Last()
to the function that existed before this package
was attached.
Usage
.Last.lib(libpath)
Arguments
libpath |
a character string giving the complete path to the package. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
Static class to validate and process arguments
Description
Package: R.utils
Class Arguments
Object
~~|
~~+--
Arguments
Directly known subclasses:
public static class Arguments
extends Object
Fields and Methods
Methods:
getCharacter | - | |
getCharacters | Coerces to a character vector and validates. | |
getDirectory | - | |
getDouble | - | |
getDoubles | Coerces to a double vector and validates. | |
getEnvironment | Gets an existing environment. | |
getFilename | Gets and validates a filename. | |
getIndex | - | |
getIndices | Coerces to a integer vector and validates. | |
getInstanceOf | Gets an instance of the object that is of a particular class. | |
getInteger | - | |
getIntegers | Coerces to a integer vector and validates. | |
getLogical | - | |
getLogicals | Coerces to a logical vector and validates. | |
getNumeric | - | |
getNumerics | Coerces to a numeric vector and validates. | |
getReadablePath | - | |
getReadablePathname | Gets a readable pathname. | |
getReadablePathnames | Gets a readable pathname. | |
getRegularExpression | Gets a valid regular expression pattern. | |
getVector | Validates a vector. | |
getVerbose | Coerces to Verbose object. | |
getWritablePath | - | |
getWritablePathname | Gets a writable pathname. | |
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
Author(s)
Henrik Bengtsson
Coerces to a character vector and validates
Description
Coerces to a character vector and validates.
Usage
## Static method (use this):
## Arguments$getCharacters(s, length=NULL, trim=FALSE, nchar=NULL, useNames=TRUE,
## asGString=getOption("Arguments$getCharacters/args/asGString", TRUE), .name=NULL,
## ...)
## Don't use the below:
## S3 method for class 'Arguments'
getCharacters(static, s, length=NULL, trim=FALSE, nchar=NULL, useNames=TRUE,
asGString=getOption("Arguments$getCharacters/args/asGString", TRUE), .name=NULL, ...)
Arguments
s |
A |
nchar |
A |
useNames |
If |
asGString |
|
.name |
A |
... |
Not used. |
Value
Returns a character
vector
, if it is valid. Otherwise an exception is
thrown.
Missing values
If s
contains missing values, and nchar
is not NULL
,
then an exception is thrown.
Author(s)
Henrik Bengtsson
See Also
For more information see Arguments
.
Coerces to a double vector and validates
Description
Coerces to a double vector and validates.
Usage
## Static method (use this):
## Arguments$getDoubles(..., disallow=c("NA", "NaN"))
## Don't use the below:
## S3 method for class 'Arguments'
getDoubles(static, ..., disallow=c("NA", "NaN"))
Arguments
... |
Arguments passed to @method "getNumeric". |
disallow |
Disallowed values. See @method "getNumerics" for details. |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see Arguments
.
Gets an existing environment
Description
Gets an existing environment.
Usage
## Static method (use this):
## Arguments$getEnvironment(envir=NULL, .name=NULL, ...)
## Don't use the below:
## S3 method for class 'Arguments'
getEnvironment(static, envir=NULL, .name=NULL, ...)
Arguments
envir |
An |
.name |
A |
... |
Not used. |
Value
Returns an environment
.
Author(s)
Henrik Bengtsson
See Also
For more information see Arguments
.
Gets and validates a filename
Description
Gets and validates a filename.
Usage
## Static method (use this):
## Arguments$getFilename(filename, nchar=c(1, 128), class=c("safe"), .name=NULL,
## .type="filename", ...)
## Don't use the below:
## S3 method for class 'Arguments'
getFilename(static, filename, nchar=c(1, 128), class=c("safe"), .name=NULL,
.type="filename", ...)
Arguments
filename |
A |
nchar |
An |
class |
A |
.name |
The name of the argument validated. |
.type |
Not used. |
... |
Not used. |
Details
When argument class="safe"
, the following 86 ASCII characters
are allowed in filenames:
#$ @ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_ (31) `abcdefghijklmnopqrstuvwxyz{|}~ (31)
This class of filenames has been extensively tested on for cross-platform support on Microsoft Windows, macOS, and various Unix flavors.
Value
Returns a character
string if filename is valid,
otherwise an exception is thrown.
Missing values
If filename
is a missing value, then an exception is thrown.
Author(s)
Henrik Bengtsson
References
[1] Microsoft, Naming Files, Paths, and Namespaces, 2018. https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file.
See Also
For more information see Arguments
.
Coerces to a integer vector and validates
Description
Coerces to a integer vector and validates.
Usage
## Static method (use this):
## Arguments$getIndices(x, ..., max=Inf, range=c(1 * (max > 0L), max), .name=NULL)
## Don't use the below:
## S3 method for class 'Arguments'
getIndices(static, x, ..., max=Inf, range=c(1 * (max > 0L), max), .name=NULL)
Arguments
x |
|
... |
Arguments passed to @method "getIntegers". |
range |
Allowed range. See @method "getNumerics" for details. |
max |
The maximum of the default range. |
.name |
A |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see Arguments
.
Gets an instance of the object that is of a particular class
Description
Gets an instance of the object that is of a particular class.
Usage
## Static method (use this):
## Arguments$getInstanceOf(object, class, coerce=FALSE, ..., .name=NULL)
## Don't use the below:
## S3 method for class 'Arguments'
getInstanceOf(static, object, class, coerce=FALSE, ..., .name=NULL)
Arguments
object |
The object that should be returned as an instance of
class |
class |
A |
coerce |
If |
... |
Not used. |
.name |
A |
Value
Returns an object inheriting from class class
.
Author(s)
Henrik Bengtsson
See Also
For more information see Arguments
.
Coerces to a integer vector and validates
Description
Coerces to a integer vector and validates.
Usage
## Static method (use this):
## Arguments$getIntegers(..., disallow=c("NA", "NaN"))
## Don't use the below:
## S3 method for class 'Arguments'
getIntegers(static, ..., disallow=c("NA", "NaN"))
Arguments
... |
Arguments passed to @method "getNumeric". |
disallow |
Disallowed values. See @method "getNumerics" for details. |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see Arguments
.
Coerces to a logical vector and validates
Description
Coerces to a logical vector and validates.
Usage
## Static method (use this):
## Arguments$getLogicals(x, ..., disallow=c("NA", "NaN"), coerce=FALSE, .name=NULL)
## Don't use the below:
## S3 method for class 'Arguments'
getLogicals(static, x, ..., disallow=c("NA", "NaN"), coerce=FALSE, .name=NULL)
Arguments
x |
A |
disallow |
A |
... |
Arguments passed to @method "getVector". |
.name |
A |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see Arguments
.
Coerces to a numeric vector and validates
Description
Coerces to a numeric vector and validates.
Usage
## Static method (use this):
## Arguments$getNumerics(x, range=NULL, asMode=NULL, disallow=NULL, ..., .name=NULL)
## Don't use the below:
## S3 method for class 'Arguments'
getNumerics(static, x, range=NULL, asMode=NULL, disallow=NULL, ..., .name=NULL)
Arguments
x |
A |
range |
Two |
asMode |
A |
disallow |
A |
... |
Arguments passed to @method "getVector". |
.name |
A |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see Arguments
.
Gets a readable pathname
Description
Gets a readable pathname.
Usage
## Static method (use this):
## Arguments$getReadablePathname(file=NULL, path=NULL, mustExist=TRUE, absolute=FALSE,
## adjust=c("none", "url"), ...)
## Don't use the below:
## S3 method for class 'Arguments'
getReadablePathname(static, file=NULL, path=NULL, mustExist=TRUE, absolute=FALSE,
adjust=c("none", "url"), ...)
Arguments
file |
A |
path |
A |
mustExist |
If |
absolute |
If |
... |
Not used. |
Value
Returns a character
string of the absolute pathname of the file.
Missing values
If file
or path
is NA
and mustExist
is FALSE
,
then (character) NA
is returned, otherwise an exception is thrown.
Windows
If a too long pathname is detected on Windows, an informative warning is given. The maximum number of symbols in a Windows pathname is 256, including file separators '/' or '\', but excluding the drive letter, and initial file separator (e.g. 'C:/'), and the string terminator ('\0'), cf. 'MSDN - Naming a File or Directory', Microsoft. In R, the limit is one symbol less, i.e. 255.
Author(s)
Henrik Bengtsson
See Also
*getWritablePathname()
filePath
.
For more information see Arguments
.
Gets a readable pathname
Description
Gets a readable pathname.
Usage
## Static method (use this):
## Arguments$getReadablePathnames(files=NULL, paths=NULL, ...)
## Don't use the below:
## S3 method for class 'Arguments'
getReadablePathnames(static, files=NULL, paths=NULL, ...)
Arguments
files |
|
paths |
|
... |
Arguments passed to |
Value
Returns a character
vector
of the pathnames for the files.
Author(s)
Henrik Bengtsson
See Also
*getReadablePathname()
filePath
.
For more information see Arguments
.
Gets a valid regular expression pattern
Description
Gets a valid regular expression pattern.
Usage
## Static method (use this):
## Arguments$getRegularExpression(pattern=NULL, ..., .name=NULL)
## Don't use the below:
## S3 method for class 'Arguments'
getRegularExpression(static, pattern=NULL, ..., .name=NULL)
Arguments
pattern |
A |
.name |
A |
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
grep
().
For more information see Arguments
.
Validates a vector
Description
Validates a vector by checking its length (number of elements).
Usage
## Static method (use this):
## Arguments$getVector(x, length=NULL, .name=NULL, ...)
## Don't use the below:
## S3 method for class 'Arguments'
getVector(static, x, length=NULL, .name=NULL, ...)
Arguments
x |
A single |
length |
A |
.name |
A |
... |
Not used. |
Value
Returns the same vector
, if it is valid. Otherwise an exception is
thrown.
Author(s)
Henrik Bengtsson
See Also
For more information see Arguments
.
Coerces to Verbose object
Description
Coerces to Verbose object.
Usage
## Static method (use this):
## Arguments$getVerbose(verbose, defaultThreshold=-1, useNullVerbose=TRUE, ...,
## .name=NULL)
## Don't use the below:
## S3 method for class 'Arguments'
getVerbose(static, verbose, defaultThreshold=-1, useNullVerbose=TRUE, ..., .name=NULL)
Arguments
verbose |
A single object. If a |
defaultThreshold |
A |
useNullVerbose |
If |
... |
Passed to the constructor of |
.name |
A |
Value
Returns a Verbose
(or a NullVerbose
) object.
Author(s)
Henrik Bengtsson
See Also
For more information see Arguments
.
Gets a writable pathname
Description
Gets a writable pathname.
Usage
## Static method (use this):
## Arguments$getWritablePathname(..., mustExist=FALSE, mustNotExist=FALSE, mkdirs=TRUE,
## maxTries=5L)
## Don't use the below:
## S3 method for class 'Arguments'
getWritablePathname(static, ..., mustExist=FALSE, mustNotExist=FALSE, mkdirs=TRUE,
maxTries=5L)
Arguments
... |
Arguments passed to |
mustExist |
If |
mustNotExist |
If the file exists, and |
mkdirs |
If |
maxTries |
A positive |
Value
Returns a character
string of the pathname of the file.
If the argument was invalid an Exception
is thrown.
Missing values
If any argument in ...
is NA
, an exception is thrown.
Author(s)
Henrik Bengtsson
See Also
*getReadablePathname()
.
filePath
.
mkdirs
.
For more information see Arguments
.
The Assert class
Description
Package: R.utils
Class Assert
Object
~~|
~~+--
Assert
Directly known subclasses:
public static class Assert
extends Object
Usage
Assert(...)
Arguments
... |
Not used. |
Fields and Methods
Methods:
check | Static method asserting that a generic condition is true. | |
inheritsFrom | Static method asserting that an object inherits from of a certain class. | |
isMatrix | Static method asserting that an object is a matrix. | |
isScalar | Static method asserting that an object is a single value. | |
isVector | Static method asserting that an object is a vector. | |
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
Author(s)
Henrik Bengtsson
Static method asserting that a generic condition is true
Description
Static method asserting that a generic condition is true.
Usage
## Static method (use this):
## Assert$check(condition, message=NULL, ...)
## Don't use the below:
## S3 method for class 'Assert'
check(static, condition, message=NULL, ...)
Arguments
condition |
A condition that should return |
message |
The error message to be reported on failure. If |
... |
Not used. |
Value
Returns (invisibly) TRUE
, or throws an exception.
Author(s)
Henrik Bengtsson
See Also
For more information see Assert
.
Static method asserting that an object inherits from of a certain class
Description
Static method asserting that an object inherits from of a certain class.
Usage
## Static method (use this):
## Assert$inheritsFrom(object, class, ...)
## Don't use the below:
## S3 method for class 'Assert'
inheritsFrom(static, object, class, ...)
Arguments
object |
Object to be checked. |
class |
Name of class. |
... |
Not used. |
Value
Returns (invisibly) TRUE
, or throws an exception.
Author(s)
Henrik Bengtsson
See Also
For more information see Assert
.
Static method asserting that an object is a matrix
Description
Static method asserting that an object is a matrix.
Usage
## Static method (use this):
## Assert$isMatrix(x, nrow=NULL, ncol=NULL, ...)
## Don't use the below:
## S3 method for class 'Assert'
isMatrix(static, x, nrow=NULL, ncol=NULL, ...)
Arguments
x |
Object to be checked. |
nrow |
Required number of rows. If |
ncol |
Required number of columns. If |
... |
Not used. |
Value
Returns (invisibly) TRUE
, or throws an exception.
Author(s)
Henrik Bengtsson
See Also
For more information see Assert
.
Static method asserting that an object is a single value
Description
Static method asserting that an object is a single value.
Usage
## Static method (use this):
## Assert$isScalar(x, ...)
## Don't use the below:
## S3 method for class 'Assert'
isScalar(static, x, ...)
Arguments
x |
Object to be checked. |
... |
Not used. |
Value
Returns (invisibly) TRUE
, or throws an exception.
Author(s)
Henrik Bengtsson
See Also
For more information see Assert
.
Static method asserting that an object is a vector
Description
Static method asserting that an object is a vector.
Usage
## Static method (use this):
## Assert$isVector(x, length=NULL, ...)
## Don't use the below:
## S3 method for class 'Assert'
isVector(static, x, length=NULL, ...)
Arguments
x |
Object to be checked. |
length |
Required length. If |
... |
Not used. |
Value
Returns (invisibly) TRUE
, or throws an exception.
Author(s)
Henrik Bengtsson
See Also
For more information see Assert
.
A progress bar that sets the size of a file accordingly
Description
Package: R.utils
Class FileProgressBar
Object
~~|
~~+--
ProgressBar
~~~~~~~|
~~~~~~~+--
FileProgressBar
Directly known subclasses:
public static class FileProgressBar
extends ProgressBar
Usage
FileProgressBar(pathname=NULL, ...)
Arguments
pathname |
The pathname of the output file. |
... |
Other arguments accepted by the |
Details
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.
Fields and Methods
Methods:
cleanup | Removes the progress file for a file progress bar. | |
update | Updates file progress bar. | |
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
Author(s)
Henrik Bengtsson
Examples
## 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)
Character string with advanced substitutions
Description
Package: R.utils
Class GString
character
~~|
~~+--
GString
Directly known subclasses:
public static class GString
extends character
Usage
GString(..., sep="")
Arguments
... |
one or more objects, to be coerced to |
sep |
A |
Fields and Methods
Methods:
as.character | Gets the processed character string. | |
evaluate | Parses and evaluates a GString. | |
gcat | - | |
getBuiltinDate | Gets the current date. | |
getBuiltinDatetime | Gets the current date and time. | |
getBuiltinHostname | Gets the hostname of the system running R. | |
getBuiltinOs | Gets the operating system of the running machine. | |
getBuiltinPid | Gets the process id of the current R session. | |
getBuiltinRhome | Gets the path where R is installed. | |
getBuiltinRversion | Gets the current R version. | |
getBuiltinTime | Gets the current time. | |
getBuiltinUsername | Gets the username of the user running R. | |
getRaw | Gets the unprocessed GString. | |
getVariableValue | Gets a variable value given a name and attributes. | |
gstring | - | |
parse | Parses a GString. | |
print | Prints the processed GString. | |
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, toAsciiRegExprPattern, toFileListTree, uses
Author(s)
Henrik Bengtsson
See Also
For convenience, see functions gstring
() and gcat
().
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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")
Gets the current date
Description
Gets the current date.
Usage
## Static method (use this):
## GString$getBuiltinDate(format="%Y-%m-%d", ...)
## Don't use the below:
## S3 method for class 'GString'
getBuiltinDate(static, format="%Y-%m-%d", ...)
Arguments
format |
A |
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Gets the current date and time
Description
Gets the current date and time.
Usage
## Static method (use this):
## GString$getBuiltinDatetime(format=NULL, ...)
## Don't use the below:
## S3 method for class 'GString'
getBuiltinDatetime(static, format=NULL, ...)
Arguments
format |
A |
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Gets the hostname of the system running R
Description
Gets the hostname of the system running R.
Usage
## Static method (use this):
## GString$getBuiltinHostname(...)
## Don't use the below:
## S3 method for class 'GString'
getBuiltinHostname(static, ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Gets the operating system of the running machine
Description
Gets the operating system of the running machine.
Usage
## Static method (use this):
## GString$getBuiltinOs(...)
## Don't use the below:
## S3 method for class 'GString'
getBuiltinOs(static, ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Gets the process id of the current R session
Description
Gets the process id of the current R session.
Usage
## Static method (use this):
## GString$getBuiltinPid(...)
## Don't use the below:
## S3 method for class 'GString'
getBuiltinPid(static, ...)
Arguments
... |
Not used. |
Value
Returns an integer
.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Gets the path where R is installed
Description
Gets the path where R is installed.
Usage
## Static method (use this):
## GString$getBuiltinRhome(...)
## Don't use the below:
## S3 method for class 'GString'
getBuiltinRhome(static, ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Gets the current R version
Description
Gets the current R version.
Usage
## Static method (use this):
## GString$getBuiltinRversion(...)
## Don't use the below:
## S3 method for class 'GString'
getBuiltinRversion(static, ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Gets the current time
Description
Gets the current time.
Usage
## Static method (use this):
## GString$getBuiltinTime(format="%H:%M:%S", ...)
## Don't use the below:
## S3 method for class 'GString'
getBuiltinTime(static, format="%H:%M:%S", ...)
Arguments
format |
A |
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Gets the username of the user running R
Description
Gets the username of the user running R.
Usage
## Static method (use this):
## GString$getBuiltinUsername(...)
## Don't use the below:
## S3 method for class 'GString'
getBuiltinUsername(static, ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Gets a variable value given a name and attributes
Description
Gets a variable value given a name and attributes.
Usage
## Static method (use this):
## GString$getVariableValue(name, attributes="", where=c("builtin", "envir",
## "parent", "Sys.getenv", "getOption"), envir=parent.frame(), inherits=TRUE,
## missingValue=NA, ...)
## Don't use the below:
## S3 method for class 'GString'
getVariableValue(static, name, attributes="", where=c("builtin", "envir",
"parent", "Sys.getenv", "getOption"), envir=parent.frame(), inherits=TRUE,
missingValue=NA, ...)
Arguments
name |
The name of the variable or function to be queried. |
attributes |
A |
where |
A |
envir |
An |
inherits |
A |
missingValue |
The value returned if not found. |
... |
Not used. |
Value
Returns a (vector
of) objects.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Static class for Java related methods
Description
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
.
Usage
Java()
Fields and Methods
Methods:
asByte | Converts a numeric to a Java byte. | |
asInt | Converts an numeric to a Java integer. | |
asLong | Converts a numeric to a Java long. | |
asShort | Converts a numeric to a Java short. | |
readByte | Reads a Java formatted byte (8 bits) from a connection. | |
readInt | Reads a Java formatted int (32 bits) from a connection. | |
readShort | Reads a Java formatted short (16 bits) from a connection. | |
readUTF | Reads a Java (UTF-8) formatted string from a connection. | |
writeByte | Writes a byte (8 bits) to a connection in Java format. | |
writeInt | Writes a integer (32 bits) to a connection in Java format. | |
writeShort | Writes a short (16 bits) to a connection in Java format. | |
writeUTF | Writes a string to a connection in Java format (UTF-8). | |
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
Author(s)
Henrik Bengtsson
Examples
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)
Converts a numeric to a Java byte
Description
Converts a numeric to a Java byte.
Usage
## Static method (use this):
## Java$asByte(x, ...)
## Don't use the below:
## S3 method for class 'Java'
asByte(static, x, ...)
Arguments
x |
|
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see Java
.
Converts an numeric to a Java integer
Description
Converts an numeric to a Java integer.
Usage
## Static method (use this):
## Java$asInt(x, ...)
## Don't use the below:
## S3 method for class 'Java'
asInt(static, x, ...)
Arguments
x |
|
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see Java
.
Converts a numeric to a Java long
Description
Converts a numeric to a Java long.
Usage
## Static method (use this):
## Java$asLong(x, ...)
## Don't use the below:
## S3 method for class 'Java'
asLong(static, x, ...)
Arguments
x |
|
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see Java
.
Converts a numeric to a Java short
Description
Converts a numeric to a Java short.
Usage
## Static method (use this):
## Java$asShort(x, ...)
## Don't use the below:
## S3 method for class 'Java'
asShort(static, x, ...)
Arguments
x |
|
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see Java
.
Reads a Java formatted byte (8 bits) from a connection
Description
Reads one or several Java formatted byte's (8 bits) from a connection. All data types in Java are signed, i.e. a byte can hold a value in the range [-128,127].
Usage
## Static method (use this):
## Java$readByte(con, n=1, ...)
## Don't use the below:
## S3 method for class 'Java'
readByte(static, con, n=1, ...)
Arguments
con |
Binary connection to be read from. |
n |
Number of byte's to be read. |
... |
Not used. |
Details
This method is included for consistency reasons only.
Value
Author(s)
Henrik Bengtsson
See Also
readBin
().
For more information see Java
.
Reads a Java formatted int (32 bits) from a connection
Description
Reads one or several Java formatted int's (32 bits) from a connection. All data types in Java are signed, i.e. a byte can hold a value in the range [-2147483648,2147483647].
Usage
## Static method (use this):
## Java$readInt(con, n=1, ...)
## Don't use the below:
## S3 method for class 'Java'
readInt(static, con, n=1, ...)
Arguments
con |
Binary connection to be read from. |
n |
Number of int's to be read. |
... |
Not used. |
Value
Returns a vector
of double
s. Note that R integer
s gives
NA is as.integer(-2147483648), which is the smallest Java int
available.
Author(s)
Henrik Bengtsson
See Also
readBin
().
For more information see Java
.
Reads a Java formatted short (16 bits) from a connection
Description
Reads one or several Java formatted short's (16 bits) from a connection. All data types in Java are signed, i.e. a byte can hold a value in the range [-32768,32767].
Usage
## Static method (use this):
## Java$readShort(con, n=1, ...)
## Don't use the below:
## S3 method for class 'Java'
readShort(static, con, n=1, ...)
Arguments
con |
Binary connection to be read from. |
n |
Number of short's to be read. |
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
readBin
().
For more information see Java
.
Reads a Java (UTF-8) formatted string from a connection
Description
Reads a Java (UTF-8) formatted string from a connection.
Usage
## Static method (use this):
## Java$readUTF(con, as.character=TRUE, ...)
## Don't use the below:
## S3 method for class 'Java'
readUTF(static, con, as.character=TRUE, ...)
Arguments
con |
Binary connection to be read from. |
as.character |
If |
... |
Not used. |
Details
Currently only 8-bit UTF-8 byte sequences are supported, i.e. plain ASCII sequences, i.e. characters that take up more than one byte are read incorrectly without any warnings.
Value
Returns a character
string or an integer
vector
.
Author(s)
Henrik Bengtsson
See Also
readBin
().
For more information see Java
.
Writes a byte (8 bits) to a connection in Java format
Description
Writes one or several byte's (8 bits) to a connection in Java format so they will be readable by Java. All data types in Java are signed, i.e. a byte can hold a value in the range [-128,127]. Trying to write a value outside this range will automatically be truncated without a warning.
Usage
## Static method (use this):
## Java$writeByte(con, b, ...)
## Don't use the below:
## S3 method for class 'Java'
writeByte(static, con, b, ...)
Arguments
con |
Binary connection to be written to. |
b |
Vector of bytes to be written. |
Details
This method is included for consistency reasons only.
Author(s)
Henrik Bengtsson
See Also
For more information see Java
.
Writes a integer (32 bits) to a connection in Java format
Description
Writes one or several integer's (32 bits) to a connection in Java format so they will be readable by Java. All data types in Java are signed, i.e. a byte can hold a value in the range [-2147483648,2147483647]. Trying to write a value outside this range will automatically be truncated without a warning.
Usage
## Static method (use this):
## Java$writeInt(con, i, ...)
## Don't use the below:
## S3 method for class 'Java'
writeInt(static, con, i, ...)
Arguments
con |
Binary connection to be written to. |
i |
Vector of integers to be written. |
Author(s)
Henrik Bengtsson
See Also
For more information see Java
.
Writes a short (16 bits) to a connection in Java format
Description
Writes one or several short's (16 bits) to a connection in Java format so they will be readable by Java. All data types in Java are signed, i.e. a byte can hold a value in the range [-32768,32767]. Trying to write a value outside this range will automatically be truncated without a warning.
Usage
## Static method (use this):
## Java$writeShort(con, s, ...)
## Don't use the below:
## S3 method for class 'Java'
writeShort(static, con, s, ...)
Arguments
con |
Binary connection to be written to. |
s |
Vector of shorts to be written. |
Author(s)
Henrik Bengtsson
See Also
For more information see Java
.
Writes a string to a connection in Java format (UTF-8)
Description
Writes a string to a connection in Java format (UTF-8) so it will be readable by Java. At the beginning of each UTF-8 sequence there is a short integer telling how many bytes (characters?) follows.
Usage
## Static method (use this):
## Java$writeUTF(con, str, ...)
## Don't use the below:
## S3 method for class 'Java'
writeUTF(static, con, str, ...)
Arguments
con |
Binary connection to be written to. |
str |
String to be written. |
Author(s)
Henrik Bengtsson
See Also
For more information see Java
.
The LComments class
Description
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.
Usage
LComments(letter="L", verboseName="log", ...)
Arguments
letter |
The smart letter. |
verboseName |
The name of the verbose object. |
... |
Not used. |
Fields and Methods
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
Author(s)
Henrik Bengtsson
A Verbose class ignoring everything
Description
Package: R.utils
Class MultiVerbose
Object
~~|
~~+--
Verbose
~~~~~~~|
~~~~~~~+--
MultiVerbose
Directly known subclasses:
public static class MultiVerbose
extends Verbose
A Verbose class ignoring everything.
This is a trial class.
Usage
MultiVerbose(verboseList=NULL, ...)
Arguments
verboseList |
|
... |
Ignored. |
Fields and Methods
Methods:
as.list | Gets a list of Verbose objects. | |
writeRaw | Writes to each of the Verbose objects. | |
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
Author(s)
Henrik Bengtsson
Examples
# Output to both standard output and to log file
stdoutLog <- Verbose(threshold=-1)
fileLog <- Verbose(file.path(tempdir(), "foo.log"), threshold=-1)
verbose <- MultiVerbose(list(stdoutLog, fileLog), 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)) {
enter(verbose, "Sub analysis ", 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)
Non-documented objects
Description
This page contains aliases for all "non-documented" objects that
R CMD check
detects in this package.
Almost all of them are generic functions that have specific
document for the corresponding method coupled to a specific class.
Other functions are re-defined by setMethodS3()
to
default methods. Neither of these two classes are non-documented
in reality.
The rest are deprecated methods.
Author(s)
Henrik Bengtsson
A Verbose class ignoring everything
Description
Package: R.utils
Class NullVerbose
Object
~~|
~~+--
Verbose
~~~~~~~|
~~~~~~~+--
NullVerbose
Directly known subclasses:
public static class NullVerbose
extends Verbose
A Verbose class ignoring everything.
Usage
NullVerbose(...)
Arguments
... |
Ignored. |
Fields and Methods
Methods:
cat | - | |
enter | - | |
evaluate | - | |
exit | - | |
header | - | |
isOn | Checks if the output is on. | |
isVisible | Checks if a certain verbose level will be shown or not. | |
newline | - | |
print | - | |
printf | - | |
ruler | - | |
str | - | |
summary | - | |
writeRaw | All output methods. | |
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
Author(s)
Henrik Bengtsson
Examples
verbose <- Verbose()
cat(verbose, "A verbose messages")
verbose <- NullVerbose()
cat(verbose, "A verbose messages") # Ignored
The Options class
Description
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.
Usage
Options(options=list(), ...)
Arguments
options |
A tree |
... |
Not used. |
Details
Note, this class and its methods do not operate on the global options structure defined in R (options).
Value
The constructor returns an Options object.
Fields and Methods
Methods:
as.character | Returns a character string version of this object. | |
as.list | Gets a list representation of the options. | |
equals | Checks if this object is equal to another Options object. | |
getLeaves | Gets all (non-list) options in a flat list. | |
getOption | Gets an option. | |
hasOption | Checks if an option exists. | |
names | Gets the full pathname of all (non-list) options. | |
nbrOfOptions | Gets the number of options set. | |
setOption | Sets an option. | |
str | Prints the structure of the options. | |
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
Author(s)
Henrik Bengtsson
Examples
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)
Provides text based counting progress bar
Description
Package: R.utils
Class ProgressBar
Object
~~|
~~+--
ProgressBar
Directly known subclasses:
FileProgressBar
public static class ProgressBar
extends Object
Usage
ProgressBar(max=100, ticks=10, stepLength=1, newlineWhenDone=TRUE)
Arguments
max |
The maximum number of steps. |
ticks |
Put visual "ticks" every |
stepLength |
The default length for each increase. |
newlineWhenDone |
If |
Fields and Methods
Methods:
as.character | Gets a string description of the progress bar. | |
getBarString | Gets the progress bar string to be displayed. | |
increase | Increases (steps) progress bar. | |
isDone | Checks if progress bar is completed. | |
reset | Reset progress bar. | |
setMaxValue | Sets maximum value. | |
setProgress | Sets current progress. | |
setStepLength | Sets default step length. | |
setTicks | Sets values for which ticks should be visible. | |
setValue | Sets current value. | |
update | Updates progress bar. | |
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
Author(s)
Henrik Bengtsson
Examples
# 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")
Class for applicational settings
Description
Package: R.utils
Class Settings
Object
~~|
~~+--
Options
~~~~~~~|
~~~~~~~+--
Settings
Directly known subclasses:
public static class Settings
extends Options
Class for applicational settings.
Usage
Settings(basename=NULL, ...)
Arguments
basename |
A |
... |
Arguments passed to constructor of superclass Options. |
Fields and Methods
Methods:
findSettings | Searches for the settings file in one or several directories. | |
getLoadedPathname | Gets the pathname of the settings file loaded. | |
isModified | Checks if settings has been modified compared to whats on file. | |
loadAnywhere | Loads settings from file. | |
promptAndSave | Prompt user to save modified settings. | |
saveAnywhere | Saves settings to file. | |
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
Load settings with package and save on exit
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()
Author(s)
Henrik Bengtsson
Examples
# 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))
Searches for the settings file in one or several directories
Description
Searches for the settings file in one or several directories.
Usage
## Static method (use this):
## Settings$findSettings(basename, paths=c(".", "~"), ...)
## Don't use the below:
## S3 method for class 'Settings'
findSettings(static, basename, paths=c(".", "~"), ...)
Arguments
basename |
A |
paths |
A |
... |
Not used. |
Value
Returns the absolute pathname (character
string) of the first settings
file found, otherwise NULL
.
Author(s)
Henrik Bengtsson
See Also
For more information see Settings
.
Abstract class SmartComments
Description
Package: R.utils
Class SmartComments
Object
~~|
~~+--
SmartComments
Directly known subclasses:
LComments, VComments
public abstract static class SmartComments
extends Object
Abstract class SmartComments.
Usage
SmartComments(letter=NA, ...)
Arguments
letter |
A single |
... |
Not used. |
Details
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")
Fields and Methods
Methods:
compile | Preprocess a vector of code lines. | |
convertComment | Converts a single smart comment to R code. | |
parse | Parses one single smart comment. | |
reset | Resets a SmartComments compiler. | |
validate | Validates the compiled lines. | |
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
Author(s)
Henrik Bengtsson
See Also
Read File Symbolic Links (also on Windows)
Description
Read File Symbolic Links (also on Windows) and returns the target of each link.
This implementation is fully compatible with the
Sys.readlink
() implementation in the base package.
Usage
Sys.readlink2(paths, what=c("asis", "corrected"))
Arguments
paths |
A |
what |
A |
Value
A character
vector
of the the same length as paths
.
Author(s)
Henrik Bengtsson
Static class to query information about the system
Description
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.
Fields and Methods
Methods:
currentTimeMillis | Get the current time in milliseconds. | |
findGhostscript | Searches for a Ghostview executable on the current system. | |
findGraphicsDevice | Searches for a working PNG device. | |
getHostname | Retrieves the computer name of the current host. | |
getMappedDrivesOnWindows | - | |
getUsername | Retrieves the name of the user running R. | |
mapDriveOnWindows | - | |
openBrowser | Opens an HTML document using the OS default HTML browser. | |
parseDebian | Parses a string, file or connection for Debian formatted parameters. | |
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
Author(s)
Henrik Bengtsson
Get the current time in milliseconds
Description
Get the current time in milliseconds.
Usage
## Static method (use this):
## System$currentTimeMillis(...)
## Don't use the below:
## S3 method for class 'System'
currentTimeMillis(this, ...)
Value
Returns an integer
.
Author(s)
Henrik Bengtsson
See Also
Sys.time
().
proc.time
().
For more information see System
.
Searches for a Ghostview executable on the current system
Description
Searches for a Ghostview executable on the current system.
Usage
## Static method (use this):
## System$findGhostscript(updateRGSCMD=TRUE, firstOnly=TRUE, force=FALSE, ...)
## Don't use the below:
## S3 method for class 'System'
findGhostscript(static, updateRGSCMD=TRUE, firstOnly=TRUE, force=FALSE, ...)
Arguments
updateRGSCMD |
If |
firstOnly |
If |
force |
|
... |
Not used. |
Value
Returns a character
vector
of full and normalized pathnames
where Ghostscript executables are found.
Author(s)
Henrik Bengtsson
References
[1] How to use Ghostscript, Ghostscript, 2022
https://ghostscript.com/docs/9.55.0/Use.htm
[2] Environment variable, Wikipedia, 2013.
https://en.wikipedia.org/wiki/Environment_variable
[3] Environment.SpecialFolder Enumeration,
Microsoft, 2013.
https://learn.microsoft.com/en-us/dotnet/api/system.environment.specialfolder
See Also
For more information see System
.
Examples
## Not run:
print(System$findGhostscript())
## End(Not run)
Searches for a working PNG device
Description
Searches for a working PNG device.
On Unix, the png device requires that X11 is available, which it is not
when running batch scripts or running R remotely. In such cases, an
alternative is to use the bitmap()
device, which generates an
EPS file and the uses Ghostscript to transform it to a PNG file.
Moreover, if identical looking bitmap and vector graphics (EPS) files
are wanted for the same figures, in practice, bitmap()
has
to be used.
By default, this method tests a list of potential graphical devices and
returns the first that successfully creates an image file.
By default, it tries to create a PNG image file via the built-in
png()
device.
Usage
## Static method (use this):
## System$findGraphicsDevice(devices=list(png), maxCount=100, sleepInterval=0.1,
## findGhostscript=TRUE, ...)
## Don't use the below:
## S3 method for class 'System'
findGraphicsDevice(static, devices=list(png), maxCount=100, sleepInterval=0.1,
findGhostscript=TRUE, ...)
Arguments
devices |
|
maxCount |
The maximum number of subsequent tests for the
the existences of |
sleepInterval |
The time in seconds between above subsequent tests. |
findGhostscript |
If |
... |
Not used. |
Value
Returns a function
that generates images, or NULL
.
Author(s)
Henrik Bengtsson
See Also
For supported graphical devices, see capabilities
().
png
,
bitmap()
and dev2bitmap
.
*findGhostscript()
.
For more information see System
.
Examples
fcn <- System$findGraphicsDevice()
if (identical(fcn, png)) {
cat("PNG device found: png()")
} else if (identical(fcn, bitmap)) {
cat("PNG device found: bitmap()")
} else {
cat("PNG device not found.")
}
Retrieves the computer name of the current host
Description
Retrieves the computer name of the current host.
Usage
## Static method (use this):
## System$getHostname(...)
## Don't use the below:
## S3 method for class 'System'
getHostname(static, ...)
Details
First, this function checks the system environment variables HOST
,
HOSTNAME
, and COMPUTERNAME
.
Second, it checks Sys.info()["nodename"]
for host name details.
Finally, it tries to query the system command uname -n
.
Value
Returns a character
string.
See Also
*getUsername()
.
Retrieves the name of the user running R
Description
Retrieves the name of the user running R.
Usage
## Static method (use this):
## System$getUsername(...)
## Don't use the below:
## S3 method for class 'System'
getUsername(static, ...)
Details
First, this function checks the system environment variables USER
,
and USERNAME
.
Second, it checks Sys.info()["user"]
for user name details.
Finally, it tries to query the system command whoami
.
Value
Returns a character
string.
See Also
*getHostname()
.
Opens an HTML document using the OS default HTML browser
Description
Opens an HTML document using the OS default HTML browser. Note that this
call is dependent on the operating system (currently only Windows and
Unix are supported).
The document given by query
can either be a local file or a
web page. If the query
was given as non-url string, i.e. as a
standard file pathname, the method will automatically check if the
file exists and conform the query to a correct url starting with
file:
. The used url will be returned as a string.
Any suggestion how implement this on Apple system are welcome!
Usage
## Static method (use this):
## System$openBrowser(query, ...)
## Don't use the below:
## S3 method for class 'System'
openBrowser(this, query, ...)
Arguments
query |
The path to document to be opened by the browser. |
Details
It is hard to create a good cross-platform openBrowser()
method,
but here is one try.
In the following text <browser>
is the value returned by
getOption("browser")
and <url>
is the URL conformed
query, which starts with either file:
or http:
.
On a Windows system, if <browser>
is not NULL
,
first
shell.exec(<browser> <url>)
is tried. If this fails, then
shell.exec(<url>)
is tried. Using this latter approach will not guarantee that
an HTML browser will open the url, e.g. depending on the Windows file
associations, a *.txt
file might be opened by NotePad. However,
it will most likely open something.
If <browser>
contains spaces, make sure it is quoted.
On Unix systems, system()
will be used to call:
<browser> -remote "openURL(<url>)" 2> /dev/null || <browser> <url> &
Value
Returns the url of the query
.
Author(s)
Henrik Bengtsson
See Also
For more information see System
.
Examples
## Not run:
System$openBrowser("https://www.r-project.org/")
## End(Not run)
Parses a string, file or connection for Debian formatted parameters
Description
Parses a text, file or a connection for Debian formatted parameters.
A file in Debian format contains rows with parameters of the form
KEY=VALUE
. It is allowed to have duplicated keys.
Usage
## Static method (use this):
## System$parseDebian(text=NULL, file=NULL, keys=NULL, ...)
## Don't use the below:
## S3 method for class 'System'
parseDebian(this, text=NULL, file=NULL, keys=NULL, ...)
Arguments
text |
The text to be parsed. Default value is |
file |
Name file, a |
keys |
The keys (names of the parameters) to be retrieved.
If |
Either, text
or file
must be given.
Value
Returns a named list
of parameter values.
Author(s)
Henrik Bengtsson
See Also
For more information see System
.
Examples
file <- file.path(Package("R.utils")$path, "DESCRIPTION")
l <- System$parseDebian(file=file)
print(l)
A status bar at the R prompt that can be updated
Description
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.
Usage
TextStatusBar(fmt=paste("%-", getOption("width") - 1, "s", sep = ""), ...)
Arguments
fmt |
A |
... |
Named arguments to be passed to |
Details
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.
Fields and Methods
Methods:
flush | Flushes the output. | |
getLabel | Gets the current value of a label. | |
newline | Writes a newline. | |
popMessage | Adds a message above the status bar. | |
setLabel | Sets the value of a label. | |
setLabels | Sets new values of given labels. | |
update | Updates the status bar (visually). | |
updateLabels | Sets the new values of given labels and updates the status bar. | |
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
Author(s)
Henrik Bengtsson
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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")
TimeoutException represents timeout errors
Description
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.
Usage
TimeoutException(..., cpu=NA, elapsed=NA)
Arguments
... |
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. |
Fields and Methods
Methods:
getMessage | Gets the message of the exception. | |
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
Author(s)
Henrik Bengtsson
See Also
For detailed information about exceptions see Exception
.
The VComments class
Description
Package: R.utils
Class VComments
Object
~~|
~~+--
SmartComments
~~~~~~~|
~~~~~~~+--
VComments
Directly known subclasses:
LComments
public static class VComments
extends SmartComments
The VComments class.
Usage
VComments(letter="V", verboseName="verbose", ...)
Arguments
letter |
The smart letter. |
verboseName |
The name of the verbose object. |
... |
Not used. |
Details
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
- #V0#
[<args>] - NullVerbose(<args>)
- #V1#
[<args>] - Verbose(<args>)
Controls
- #V=#
[<variable>] - Sets the name of the <verbose> object. Default is 'verbose'.
- #V^#
<threshold> - setThreshold(<verbose>, <threshold>)
- #V?#
<expression> - if (isVisible(<verbose>)) { <expression> }
- #V@#
<level> - setDefaultLevel(<verbose>, <level>)
- #Vm#
<method> <args> - <method>(<verbose>, <args>)
Enters and exits
- #V+#
[<message>] - enter(<verbose>, <message>)
- #V-#
[<message>] - exit(<verbose>, <message>)
- #V!#
[<message>] - pushState(<verbose>)
on.exit(popState(<verbose>))
If <message>, enter(<verbose>, <message>)
Simple output
- #Vn#
<ignored> - newline(<verbose>)
- #Vr#
<ignored> - ruler(<verbose>)
- #Vt#
<ignored> - timestamp(<verbose>)
- #Vw#
[<title>] - warnings(<verbose>, <title>)
Output messages
- #Vc#
[<message>] - cat(<verbose>, <message>)
- #Ve#
<expression> - eval(<verbose>, <expression>)
- #Vh#
<message> - header(<verbose>, <message>)
- #Vp#
<object> - print(<verbose>, <object>)
- #Vs#
<object> - summary(<verbose>, <object>)
- #Vz#
<object> - str(<verbose>, <object>)
Fields and Methods
Methods:
convertComment | Converts a verbose comment to R code. | |
reset | Resets a VComments compiler. | |
validate | Validates the compiled lines. | |
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
Author(s)
Henrik Bengtsson
Examples
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")
Class to writing verbose messages to a connection or file
Description
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.
Usage
Verbose(con=stderr(), on=TRUE, threshold=0, asGString=TRUE, timestamp=FALSE,
removeFile=TRUE, core=TRUE, ...)
Arguments
con |
A |
on |
A |
threshold |
A |
timestamp |
If |
removeFile |
If |
asGString |
If |
core |
Internal use only. |
... |
Not used. |
Fields and Methods
Methods:
as.character | Returns a character string version of this object. | |
as.double | Gets a numeric value of this object. | |
as.logical | Gets a logical value of this object. | |
capture | Captures output of a function. | |
cat | Concatenates and prints objects if above threshold. | |
enter | Writes a message and indents the following output. | |
enterf | - | |
equals | Checks if this object is equal to another. | |
evaluate | Evaluates a function and prints its results if above threshold. | |
exit | Writes a message and unindents the following output. | |
getThreshold | Gets current verbose threshold. | |
getTimestampFormat | Gets the default timestamp format. | |
header | Writes a header. | |
isOn | Checks if the output is on. | |
isVisible | Checks if a certain verbose level will be shown or not. | |
less | Creates a cloned instance with a higher threshold. | |
more | Creates a cloned instance with a lower threshold. | |
newline | Writes one or several empty lines. | |
off | Turn off the output. | |
on | Turn on the output. | |
popState | - | |
print | Prints objects if above threshold. | |
printWarnings | Outputs any warnings recorded. | |
printf | Formats and prints object if above threshold. | |
pushState | Pushes the current indentation state of the Verbose object. | |
ruler | Writes a ruler. | |
setDefaultLevel | Sets the current default verbose level. | |
setThreshold | Sets verbose threshold. | |
setTimestampFormat | Sets the default timestamp format. | |
str | Prints the structure of an object if above threshold. | |
summary | Generates a summary of an object if above threshold. | |
timestamp | Writes a timestamp. | |
timestampOff | - | |
timestampOn | Turns automatic timestamping on and off. | |
writeRaw | Writes objects if above threshold. | |
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
Output levels
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.
- <= -100
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.
- -99 – -11
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.
- -10 – -1
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.
- 0
Default level in all output methods and default threshold. Thus, by default, messages at level 0 are not shown.
- >= +1
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).
A compatibility trick and a speed-up trick
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
.
Extending the Verbose class
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.
Author(s)
Henrik Bengtsson
See Also
Examples
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)
Modifies .Last() to call 'finalizeSession()
Description
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.
Usage
## Default S3 method:
addFinalizerToLast(...)
Arguments
... |
Not used. |
Value
Returns (invisibly) TRUE
if .Last()
was modified,
otherwise FALSE
.
Author(s)
Henrik Bengtsson
See Also
Gets the processed character string
Description
Gets the processed character string.
Usage
## S3 method for class 'GString'
as.character(x, envir=parent.frame(), ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Returns a character string version of this object
Description
Returns a character string version of this object.
Usage
## S3 method for class 'Options'
as.character(x, ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see Options
.
Gets a string description of the progress bar
Description
Gets a string description of the progress bar.
Usage
## S3 method for class 'ProgressBar'
as.character(x, ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see ProgressBar
.
Returns a character string version of this object
Description
Returns a character string version of this object.
Usage
## S3 method for class 'Verbose'
as.character(x, ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Gets a numeric value of this object
Description
Gets a numeric value of this object. Returns what *getThreshold()
returns.
Usage
## S3 method for class 'Verbose'
as.double(x, ...)
Arguments
... |
Not used. |
Value
Returns a numeric
value.
Author(s)
Henrik Bengtsson
See Also
*getThreshold()
and *getThreshold()
.
For more information see Verbose
.
Gets a list of Verbose objects
Description
Gets a list of Verbose objects.
Usage
## S3 method for class 'MultiVerbose'
as.list(x, ...)
Arguments
... |
Not used. |
Value
Returns a list
of Verbose
objects.
Author(s)
Henrik Bengtsson
See Also
For more information see MultiVerbose
.
Gets a list representation of the options
Description
Gets a list representation of the options.
Usage
## S3 method for class 'Options'
as.list(x, ...)
Arguments
... |
Not used. |
Value
Returns a tree list
structure.
Author(s)
Henrik Bengtsson
See Also
For more information see Options
.
Gets a logical value of this object
Description
Gets a logical value of this object. Returns isVisible(this, level=this$defaultLevel)
.
Usage
## S3 method for class 'Verbose'
as.logical(x, ...)
Arguments
... |
Not used. |
Value
Returns a logical
value.
Author(s)
Henrik Bengtsson
See Also
*isVisible()
.
For more information see Verbose
.
Assigns an objects elements locally
Description
Assigns an objects elements locally.
Usage
## S3 method for class 'list'
attachLocally(object, fields=NULL, excludeFields=NULL, overwrite=TRUE,
envir=parent.frame(), ...)
Arguments
object |
An object with named elements such as an |
fields |
A |
excludeFields |
A |
overwrite |
If |
envir |
The |
... |
Not used. |
Value
Returns (invisibly) a character
vector
of the fields copied.
Author(s)
Henrik Bengtsson
See Also
attachLocally()
of class Object.
attach
().
Examples
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
Description
Call hook functions by hook name.
Usage
## Default S3 method:
callHooks(hookName, ..., removeCalledHooks=FALSE)
Arguments
hookName |
A |
... |
Argument passed to each hook function. |
removeCalledHooks |
If |
Value
Returns (invisibly) whatever callHooks.list
() returns.
Author(s)
Henrik Bengtsson
See Also
Internally, after retrieving hook functions, callHooks.list
() is
called.
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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
Description
Call hook functions.
Usage
## S3 method for class 'function'
callHooks(hooks, ...)
Arguments
hooks |
|
... |
Argument passed to each hook function. |
Value
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
.
Author(s)
Henrik Bengtsson
See Also
See callHooks
() to call hook function by name.
Capitalizes/decapitalizes each character string in a vector
Description
Capitalizes/decapitalized (making the first letter upper/lower case) of each character string in a vector.
Usage
## Default S3 method:
capitalize(str, ...)
## Default S3 method:
decapitalize(str, ...)
Arguments
str |
|
... |
Not used. |
Value
Returns a vector
of character
strings of the same length as the input
vector.
Author(s)
Henrik Bengtsson
See Also
Examples
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")
Captures output of a function
Description
Captures output of a function. Evaluates its arguments with the output being verbosed.
Usage
## S3 method for class 'Verbose'
capture(this, ..., level=this$defaultLevel)
Arguments
... |
Arguments to be captured. |
level |
A |
Value
Returns a vector
of character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Evaluate an R expression and captures the output
Description
Evaluate an R expression and captures the output.
Usage
captureOutput(expr, file=NULL, append=FALSE, collapse=NULL, envir=parent.frame())
Arguments
expr |
The R expression to be evaluated. |
file |
A file name or a |
append |
If |
collapse |
A |
envir |
The |
Details
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].
Value
Returns captured output as a character
vector
.
Author(s)
Henrik Bengtsson
References
[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/
See Also
Internally, eval
() is used to evaluate the expression.
and capture.output
to capture the output.
Examples
# 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 ...)
Concatenates and prints objects if above threshold
Description
Concatenates and prints objects if above threshold.
The output is indented according to *enter()
/*exit()
calls.
Usage
## S3 method for class 'Verbose'
cat(this, ..., sep="", newline=TRUE, level=this$defaultLevel, timestamp=this$.timestamp)
Arguments
... |
Objects to be passed to |
sep |
The default separator |
newline |
If |
level |
A |
timestamp |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
*timestampOn()
and timestampOff
().
For more information see Verbose
.
Removes the progress file for a file progress bar
Description
Removes the progress file for a file progress bar.
Usage
## S3 method for class 'FileProgressBar'
cleanup(object, ...)
Arguments
... |
Not used. |
Value
Returns (invisibly) TRUE
, if there is no progress file afterwards.
Otherwise, FALSE
is returned.
Author(s)
Henrik Bengtsson
See Also
For more information see FileProgressBar
.
Simple access to parsed command-line arguments
Description
Simple access to parsed command-line arguments.
Usage
cmdArgs(args=NULL, names=NULL, unique=TRUE, ..., .args=NULL)
cmdArg(...)
Arguments
args |
A named |
names |
A |
unique |
If |
... |
For |
.args |
(advanced/internal) A named |
Value
cmdArgs()
returns a named list
with command-line arguments.
cmdArg()
return the value of the requested command-line argument.
Coercing to non-character data types
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
.
Author(s)
Henrik Bengtsson
See Also
Internally, commandArgs
() is used.
Examples
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)
Calls an R function passing command-line arguments
Description
Calls an R function passing command-line arguments.
Usage
cmdArgsCall(..., args=cmdArgs(unique = FALSE), .ignoreUnusedArgs=FALSE,
envir=parent.frame())
Arguments
... |
Arguments passed to |
args |
A |
.ignoreUnusedArgs |
Passed to |
envir |
An |
Value
Returns whatever the called function returns.
Author(s)
Henrik Bengtsson
See Also
Internally, cmdArgs
() and doCall
() is used.
Examples
## Not run:
Rscript -e R.utils::cmdArgsCall(rnorm) n=4
## End(Not run)
Creates a vector of column classes used for tabular reading
Description
Creates a vector of column classes used for tabular reading based on a compact format string.
Usage
## Default S3 method:
colClasses(fmt, ...)
Arguments
fmt |
A |
... |
Optional arguments for the |
Value
Returns a vector
of character
strings.
Author(s)
Henrik Bengtsson
See Also
Examples
# 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))
Extract command-line arguments
Description
Provides access to a copy of the command-line arguments supplied when
this R session was invoked. This function is backward compatible with
commandArgs
() of the base package, but adds more
features.
Usage
commandArgs(trailingOnly=FALSE, asValues=FALSE, defaults=NULL, always=NULL, adhoc=FALSE,
unique=FALSE, excludeReserved=FALSE, excludeEnvVars=FALSE, os=NULL, .args=NULL, ...)
Arguments
trailingOnly |
If |
asValues |
If |
defaults |
A |
always |
A |
adhoc |
(ignored if |
unique |
If |
excludeReserved |
If |
excludeEnvVars |
If |
os |
A |
args |
A named |
.args |
|
... |
Passed to |
Value
If asValue
is FALSE
, a character
vector
is returned, which
contains the name of the executable and the non-parsed user-supplied
arguments.
If asValue
is TRUE
, a named list
containing is returned, which
contains the the executable and the parsed user-supplied arguments.
The first returned element is the name of the executable by which
R was invoked. As far as I am aware, the exact form of this element
is platform dependent. It may be the fully qualified name, or simply
the last component (or basename) of the application.
The returned attribute isReserved
is a logical
vector
specifying if the corresponding command-line argument is a reserved
R argument or not.
Backward compatibility
This function should be fully backward compatible with the same function in the base package, except when littler is used (see below).
Compatibility with littler
The littler package provides the r
binary, which parses
user command-line options and assigns them to character vector
argv
in the global environment.
The commandArgs()
of this package recognizes argv
arguments as well.
Coercing to non-character data types
When asValues
is TRUE
, the command-line arguments are
returned as a named list
. By default, the values of these
arguments are character
strings.
However, any command-line argument that share name with one of
the 'always' or 'default' arguments, then its value is coerced to
the corresponding data type (via as
).
This provides a mechanism for specifying data types other than
character
strings.
Furthermore, when asValues
and adhoc
are TRUE
, any
remaining character string command-line arguments are coerced to more
specific data types (via type.convert
), if possible.
Author(s)
Henrik Bengtsson
See Also
For a more user friendly solution, see cmdArgs
().
Internally commandArgs
() is used.
Examples
######################################################################
# Non-parsed command-line arguments
######################################################################
# Display how this instance of R was invoked.
cmd <- paste(commandArgs(), collapse=" ")
cat("How R was invoked:\n");
cat(cmd, "\n")
# Get all arguments
args <- commandArgs()
print(args)
# Get only "private" arguments and not the name of the R executable.
args <- commandArgs(excludeReserved=TRUE)[-1]
print(args)
# Assert backward compatibility
args0 <- base::commandArgs()
args <- commandArgs()
stopifnot(all.equal(args, args0, check.attributes=FALSE))
######################################################################
# Parsed command-line arguments
######################################################################
# Get all arguments as a named list, e.g. if R is started as:
#
# R DATAPATH=../data --args --root="do da" --foo bar --details --a=2
#
# then 'args' below will equal
#
# list(R=NA, DATAPATH="../data" args=TRUE, root="do da",
# foo="bar", details=TRUE, a="2")
args <- commandArgs(asValues=TRUE)
str(args)
# Turn arguments into R variables
args <- commandArgs(asValues=TRUE, excludeReserved=TRUE)[-1]
keys <- attachLocally(args)
cat("Command-line arguments attached to global environment:\n");
print(keys);
str(mget(keys, envir=globalenv()))
Preprocess a vector of code lines
Description
Preprocess a vector of code lines.
Usage
## S3 method for class 'SmartComments'
compile(this, lines, trim=TRUE, excludeComments=FALSE, ...)
Arguments
lines |
|
trim |
If |
excludeComments |
If |
... |
Not used. |
Details
When called, the compiler is reset.
Just before trimming is done, the validate() method is called. In the current class, this does nothing, but can be overridden in subclasses.
Value
Author(s)
Henrik Bengtsson
See Also
For more information see SmartComments
.
Compressing and decompressing files
Description
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.
Usage
## 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)
Arguments
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 |
Details
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.
Value
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.
Author(s)
Henrik Bengtsson
Examples
## 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)
Description
Compresses a PDF (into a new PDF).
Usage
## Default S3 method:
compressPDF(filename, path=NULL, outFilename=basename(pathname),
outPath="compressedPDFs", skip=FALSE, overwrite=FALSE, compression="gs(ebook)+qpdf",
...)
Arguments
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 |
Value
Returns the pathname of the generated PDF.
Author(s)
Henrik Bengtsson
See Also
Internally compactPDF
is utilized.
Examples
## Not run:
pathnameZ <- compressPDF("report.pdf")
## End(Not run)
Converts a single smart comment to R code
Description
Converts a single smart comment to R code.
Usage
## S3 method for class 'SmartComments'
convertComment(...)
Arguments
... |
Not used. |
Value
Should return single character
of valid R code.
Author(s)
Henrik Bengtsson
See Also
For more information see SmartComments
.
Converts a verbose comment to R code
Description
Converts a verbose comment to R code.
Usage
## S3 method for class 'VComments'
convertComment(this, vcomment, .currLine=NA, .line=NA, ...)
Arguments
vcomment |
A vcomment |
.currLine , .line |
A line number and the line currently processed. Used for error message and warnings. |
... |
Not used. |
Value
Returns one character
string of R code.
Author(s)
Henrik Bengtsson
See Also
For more information see VComments
.
Copies a directory
Description
Copies a directory.
Usage
## Default S3 method:
copyDirectory(from, to=".", ..., private=TRUE, recursive=TRUE)
Arguments
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 |
Details
Note that this method does not use copyFile
() to
copy the files, but file.copy
().
Value
Returns (invisibly) a character
vector
of pathnames copied.
Author(s)
Henrik Bengtsson
Copies a file atomically
Description
Copies a file atomically, by first copying to a temporary file and then renaming that file.
Usage
## Default S3 method:
copyFile(srcPathname, destPathname, skip=FALSE, overwrite=FALSE, ..., validate=TRUE,
verbose=FALSE)
Arguments
srcPathname |
The source file to be copied. |
destPathname |
The destination file to be created.
If an existing directory, then the destination file
becomes |
skip , overwrite |
If a destination file does not exist, these
arguments have no effect.
If such a file exists and |
... |
Additional named arguments passed to |
validate |
If |
verbose |
See |
Details
If the source file does not exists (or is not a file), then an informative exception is thrown.
If the source and destination pathnames are the same, it is not safe to copy (which can lead to either corrupt or lost files) and an informative exception is thrown.
If (and only if) the file is successfully copied and argument
validate
is TRUE
, then this method also asserts that the
file size of the destination matches that of the source, otherwise
an informative exception is thrown.
Value
Returns a logical
indicating whether a successful file copy was
completed or not, or equivalently. In other words, TRUE
is returned
if the file was successfully copied, and FALSE
if not.
If an error occurs, an informative exception is thrown.
If the error occurs while renaming the temporary file to the final name,
the temporary file will remain in the destination directory.
Author(s)
Henrik Bengtsson
See Also
file.copy()
.
Counts the number of lines in a text file
Description
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.
Usage
## Default S3 method:
countLines(file, chunkSize=5e+07, ...)
Arguments
file |
A |
chunkSize |
The number of bytes read in each chunk. |
... |
Not used. |
Details
Both compressed and non-compressed files are supported.
Value
Returns an non-negative integer
.
Author(s)
Henrik Bengtsson
References
[1] Page Newline, Wikipedia, July 2008. https://en.wikipedia.org/wiki/Newline
Examples
pathname <- system.file("NEWS.md", package="R.utils");
n <- countLines(pathname);
n2 <- length(readLines(pathname));
stopifnot(n == n2);
Creates a file atomically
Description
Creates a file atomically by first creating and writing to a temporary file which is then renamed.
Usage
## Default S3 method:
createFileAtomically(filename, path=NULL, FUN, ..., skip=FALSE, overwrite=FALSE,
backup=TRUE, verbose=FALSE)
Arguments
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 |
Value
Returns (invisibly) the pathname.
Author(s)
Henrik Bengtsson
See Also
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.
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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
Description
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.
Usage
## Default S3 method:
createLink(link=".", target, skip=!overwrite, overwrite=FALSE,
methods=getOption("createLink/args/methods", c("unix-symlink", "windows-ntfs-symlink",
"windows-shortcut")), ...)
Arguments
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. |
Value
Returns (invisibly) the path or pathname to the link.
If no link was created, NULL
is returned.
Required privileges on Windows
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).
Author(s)
Henrik Bengtsson
References
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/]
See Also
createWindowsShortcut
() and
file.symlink()
Creates a Microsoft Windows Shortcut (.lnk file)
Description
Creates a Microsoft Windows Shortcut (.lnk file).
Usage
## Default S3 method:
createWindowsShortcut(pathname, target, overwrite=FALSE, mustWork=FALSE, ...)
Arguments
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. |
Value
Returns (invisibly) the pathname.
Required privileges on Windows
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).
Author(s)
Henrik Bengtsson
References
[1] Create a windows shortcut (.LNK file), SS64.com,
https://ss64.com/nt/shortcut.html
See Also
Examples
# 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
Description
Allocates a data frame with given column classes.
Usage
## Default S3 method:
dataFrame(colClasses, nrow=1, ...)
Arguments
colClasses |
A |
nrow |
An |
... |
Not used. |
Value
Returns an NxK data.frame
where N equals nrow
and
K equals length(colClasses)
.
See Also
Examples
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
Description
Detaches packages by name, if loaded.
Usage
## Default S3 method:
detachPackage(pkgname, ...)
Arguments
pkgname |
|
... |
Not used. |
Value
Returns (invisibly) a named logical
vector
indicating whether
each package was detached or not.
Author(s)
Henrik Bengtsson
See Also
detach
().
Sets the dimension of an object with the option to infer one dimension automatically
Description
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.
Usage
## Default S3 replacement method:
dimNA(x) <- value
Arguments
x |
An R object. |
value |
Value
Returns (invisibly) what dim<-()
returns
(see dim
() for more details).
Author(s)
Henrik Bengtsson
See Also
dim
().
Examples
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
Description
Displays the contents of a text file with line numbers and more.
Usage
## Default S3 method:
displayCode(con=NULL, code=NULL, numerate=TRUE, lines=-1, wrap=79, highlight=NULL,
pager=getOption("pager"), ...)
Arguments
con |
A |
code |
|
numerate |
If |
lines |
If a single |
wrap |
The (output) column |
highlight |
A |
pager |
If |
... |
Additional arguments passed to |
Value
Returns (invisibly) the formatted code as a character
string.
Author(s)
Henrik Bengtsson
See Also
file.show
().
Examples
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
Description
Executes a function call with option to ignore unused arguments.
Usage
## Default S3 method:
doCall(.fcn, ..., args=NULL, alwaysArgs=NULL, .functions=list(.fcn),
.ignoreUnusedArgs=TRUE, envir=parent.frame())
Arguments
.fcn |
A |
... |
Named arguments to be passed to the function. |
args |
A |
alwaysArgs |
A |
.functions |
A |
.ignoreUnusedArgs |
If |
envir |
An |
Author(s)
Henrik Bengtsson
See Also
do.call
().
Examples
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
Description
Downloads a file.
Usage
## 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)
Arguments
url |
A |
filename , path |
(optional) |
skip |
If |
overwrite |
If |
... |
Additional arguments passed to |
username , password |
|
binary |
If |
dropEmpty |
If |
verbose |
Details
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.
Value
Returns the local pathname to the downloaded filename,
or NULL
if no file was downloaded.
Author(s)
Henrik Bengtsson
See Also
Internally download.file
is used.
That function may generate an empty file if the URL is not available.
Examples
## Not run:
pathname <- downloadFile("https://www.r-project.org/index.html", path="www.r-project.org/")
print(pathname)
## End(Not run)
Draws a density curve
Description
Draws a density curve along one of the sides of the current plotting region.
Usage
## S3 method for class 'density'
draw(object, side=1, height=0.2, offset=0, scale=c("absolute", "relative"), xtrim=NULL,
xpd=TRUE, ...)
Arguments
side |
An |
height |
A |
scale |
A |
xpd |
|
... |
Not used. |
Value
Returns the drawn 'density' object (with the 'x' and 'y' coordinates as plotted).
Author(s)
Henrik Bengtsson
See Also
See density
for estimating densities.
Internally *swapXY()
may be used.
Gets a variable by name
Description
Gets a variable by name. If non-existing, the default value is returned.
Usage
eget(..., coerce=TRUE, envir=parent.frame(), inherits=FALSE, mode="default",
cmdArg=FALSE)
Arguments
... |
Named arguments |
coerce |
If |
envir |
A |
inherits |
A |
mode |
A |
cmdArg |
If |
Details
ecget(...)
is short for eget(..., cmdArg=TRUE)
.
Value
Returns an object.
Author(s)
Henrik Bengtsson
See Also
To retrieve command-line arguments, see cmdArg
.
See also mget
().
Examples
# Get variable 'a' if it exists, otherwise return the default value.
value <- eget("a", default=42L)
print(value) # 42L
# Short version doing the same
value <- eget(a=42L)
print(value) # 42L
# Same, but look for the variable in 'envir' (here a list)
value <- eget("a", default=42L, envir=list(a=1))
print(value) # 1L
# Get variable 'n', which defaults to command-line argument
# 'n' ('-n' or '--n'), which in turn defaults to 42L.
value <- eget(n=cmdArg(n=42L))
print(value)
# Equivalently.
value <- ecget(n=42L)
print(value)
Global substitute of expression using regular expressions
Description
Global substitute of expression using regular expressions.
Usage
egsub(pattern, replacement, x, ..., value=TRUE, envir=parent.frame(), inherits=TRUE)
Arguments
pattern |
A |
replacement |
A |
x |
The |
... |
Additional arguments passed to |
value |
If |
envir , inherits |
An |
Value
Returns an expression
.
Author(s)
Henrik Bengtsson
Examples
# 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)
Writes a message and indents the following output
Description
Writes a message and indents the following output.
The output is indented according to *enter()
/*exit()
calls.
Usage
## S3 method for class 'Verbose'
enter(this, ..., indent=this$indentStep, sep="", suffix="...", level=this$defaultLevel)
## S3 method for class 'Verbose'
enterf(this, fmtstr, ..., indent=this$indentStep, sep="", suffix="...",
level=this$defaultLevel)
Arguments
fmtstr |
An |
... |
|
indent |
The number of characters to add to the indentation. |
sep |
The default separator |
suffix |
A |
level |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Creates a new environment, evaluates an expression therein, and returns the environment
Description
Creates a new environment, evaluates an expression therein, and returns the environment.
Usage
env(..., hash=FALSE, parent=parent.frame(), size=29L)
Arguments
... |
Arguments passed to |
hash , parent , size |
Arguments passed to |
Value
Returns an environment
.
Author(s)
Henrik Bengtsson
References
[1] R-devel thread 'Create an environment and assign objects to it in
one go?' on March 9-10, 2011.
See Also
Internally new.env
() and evalq
() are used.
Examples
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);
Checks if this object is equal to another Options object
Description
Checks if this object is equal to another Options object.
Usage
## S3 method for class 'Options'
equals(this, other, ...)
Arguments
other |
Another Options object. |
... |
Not used. |
Value
Returns TRUE
if they are equal, otherwise FALSE
.
Author(s)
Henrik Bengtsson
See Also
For more information see Options
.
Checks if this object is equal to another
Description
Checks if this object is equal to another.
Usage
## S3 method for class 'Verbose'
equals(this, other, ...)
Arguments
other |
Another Object. |
... |
Not used. |
Value
Returns TRUE
if they are equal, otherwise FALSE
.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Parses and evaluates a GString
Description
Parses and evaluates a GString.
Usage
## S3 method for class 'GString'
evaluate(object, envir=parent.frame(), ...)
Arguments
envir |
The |
... |
Additional arguments passed to |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Evaluates a function and prints its results if above threshold
Description
Evaluates a function and prints its results if above threshold. The output is not indented.
Usage
## S3 method for class 'Verbose'
evaluate(this, fun, ..., level=this$defaultLevel)
Arguments
fun |
A |
... |
Additional arguments passed to the function. |
level |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Writes a message and unindents the following output
Description
Writes a message and unindents the following output.
The output is indented according to *enter()
/*exit()
calls.
Usage
## S3 method for class 'Verbose'
exit(this, ..., indent=-this$indentStep, sep="", suffix="...done", level=NULL)
Arguments
... |
Objects to be passed to |
indent |
The number of characters to be removed from the indentation. |
sep |
The default separator |
suffix |
A |
level |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Extract a subset of an array, matrix or a vector with unknown dimensions
Description
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.
Usage
## S3 method for class 'array'
extract(x, ..., indices=list(...), dims=names(indices), drop=FALSE)
Arguments
x |
|
... |
These arguments are by default put into the
|
indices |
|
dims |
An |
drop |
If |
Value
Returns an array
.
Author(s)
Henrik Bengtsson
See Also
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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))
Extract File Information (acknowledging symbolic file links also on Windows)
Description
Extract File Information (acknowledging symbolic file links also on Windows).
Usage
file.info2(...)
Arguments
... |
A |
Value
A data.frame
. See file.info
() for details.
Author(s)
Henrik Bengtsson
See Also
Internally, file.info
() is used, which does not respect
symbolic links on Windows. Instead, on Windows, Sys.readlink2
()
is used for such link to identify the target file and retrieve the
file information on that instead.
Checks the permission of a file or a directory
Description
Checks the permission of a file or a directory.
Usage
## Default S3 method:
fileAccess(pathname, mode=0, safe=TRUE, ...)
Arguments
pathname |
A |
mode |
An |
safe |
If |
... |
Not used. |
Details
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].
Value
Returns an integer
; 0 if the permission exists, -1 if not.
Symbolic links
This function follows symbolic links (also on Windows) and returns a value based on the link target (rather than the link itself).
Author(s)
Henrik Bengtsson
References
[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
See Also
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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
Description
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.
Usage
## Default S3 method:
filePath(..., fsep=.Platform$file.sep, removeUps=TRUE,
expandLinks=c("none", "any", "local", "relative", "network"), unmap=FALSE,
mustExist=FALSE, verbose=FALSE)
Arguments
... |
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 |
Details
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.
Value
Returns a character
string.
On speed
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.
Author(s)
Henrik Bengtsson
See Also
readWindowsShellLink
().
readWindowsShortcut
().
file.path
().
Examples
# 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)
Function to call for finalizing the R session
Description
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.
Usage
## Default S3 method:
finalizeSession(...)
Arguments
... |
Not used. |
Value
Returns (invisibly) the hooks successfully called.
Author(s)
Henrik Bengtsson
See Also
Finds one or several files in multiple directories
Description
Finds one or several files in multiple directories.
Usage
## Default S3 method:
findFiles(pattern=NULL, paths=NULL, recursive=FALSE, firstOnly=TRUE, allFiles=TRUE, ...)
Arguments
pattern |
A regular expression file name pattern to match. |
paths |
|
recursive |
If |
firstOnly |
If |
allFiles |
If |
... |
Arguments passed to |
Value
Returns a vector
of the full pathnames of the files found.
Search path
The paths
argument may also contain paths specified as
semi-colon (";"
) separated paths, e.g.
"/usr/;usr/bin/;.;"
.
Recursive searching
Recursive searching of directory structure is done breath-first in a lexicographic order.
Windows Shortcut links
Windows Shortcut links (*.lnk) are recognized and can be used
to imitate links to directories elsewhere.
For more details, see filePath
().
Author(s)
Henrik Bengtsson
Finds all 'srcfile' objects generated by source() in all call frames
Description
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
().
Usage
## Default S3 method:
findSourceTraceback(...)
Arguments
... |
Not used. |
Value
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.
Author(s)
Henrik Bengtsson
See Also
See also sourceutils
.
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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)
Flushes the output
Description
Flushes the output.
Usage
## S3 method for class 'TextStatusBar'
flush(con, ...)
Arguments
... |
Arguments passed to |
Details
All this methods does is to call flush.console
, which
flushes the output to the console.
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
flush.console
.
For more information see TextStatusBar
.
Converts a binary/octal/hexadecimal number into a string
Description
Converts a binary/octal/hexadecimal number into a string.
Usage
## S3 method for class 'binmode'
format(x, ...)
Arguments
x |
Object to be converted. |
... |
Not used. |
Value
Returns a character
.
Author(s)
Henrik Bengtsson
See Also
format.octmode()
, cf. octmode
.
intToBin
() (incl. intToOct()
and intToHex()
).
Identifies and removes DLLs of packages already unloaded
Description
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.
Usage
gcDLLs(gc=TRUE, quiet=TRUE)
Arguments
gc |
If |
quiet |
If |
Details
If a library fails to unload, an informative warning is generated.
Value
Returns (invisibly) the set of stray DLLs identified.
How to unload DLLs in package (for package developers)
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) }
Author(s)
Henrik Bengtsson
See Also
Parses, evaluates and outputs a GString
Description
Parses, evaluates and outputs a GString.
Usage
## Default S3 method:
gcat(..., file="", append=FALSE, envir=parent.frame())
Arguments
... |
|
file |
A |
append |
Only applied if |
envir |
The |
Value
Returns (invisibly) a character
string.
Author(s)
Henrik Bengtsson
See Also
gstring
().
Gets the absolute pathname string
Description
Gets the absolute pathname string.
Usage
## Default S3 method:
getAbsolutePath(pathname, workDirectory=getwd(), expandTilde=FALSE, ...)
Arguments
pathname |
A |
workDirectory |
A |
expandTilde |
If |
... |
Not used. |
Details
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.
Value
Returns a character
string of the absolute pathname.
Author(s)
Henrik Bengtsson
See Also
Gets the progress bar string to be displayed
Description
Gets the progress bar string to be displayed.
Usage
## S3 method for class 'ProgressBar'
getBarString(this, ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see ProgressBar
.
Gets the current value of a label
Description
Gets the current value of a label address either by its index or its names.
Usage
## S3 method for class 'TextStatusBar'
getLabel(this, label, ...)
Arguments
label |
The index or the name of the label. |
... |
Not used. |
Value
Returns the value.
Author(s)
Henrik Bengtsson
See Also
*setLabel()
and *setLabels()
.
For more information see TextStatusBar
.
Gets all (non-list) options in a flat list
Description
Gets all (non-list) options in a flat list.
Usage
## S3 method for class 'Options'
getLeaves(this, ...)
Arguments
... |
Not used. |
Value
Returns a flat list
structure.
Author(s)
Henrik Bengtsson
See Also
For more information see Options
.
Gets the pathname of the settings file loaded
Description
Gets the pathname of the settings file loaded.
Usage
## S3 method for class 'Settings'
getLoadedPathname(this, ...)
Arguments
... |
Not used. |
Value
Returns the absolute pathname (character
string) of the settings file
loaded. If no file was read, NULL
is returned.
Author(s)
Henrik Bengtsson
See Also
For more information see Settings
.
Gets the message of the exception
Description
Gets the message of the exception.
Usage
## S3 method for class 'TimeoutException'
getMessage(this, ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see TimeoutException
.
Gets an option
Description
Gets an option in the options tree structure or return a default value.
Usage
## S3 method for class 'Options'
getOption(this, pathname=NULL, defaultValue=NULL, ...)
Arguments
pathname |
A single or a |
defaultValue |
The default value to be returned, if option is
missing. If multiple options are queried at the same times, multiple
default values may be specified as a |
... |
Not used. |
Value
If a single option is queried, a single value is returned.
If a vector
of options are queried, a list
of values are returned.
For non-existing options, the default value is returned.
Author(s)
Henrik Bengtsson
See Also
*hasOption()
.
*setOption()
.
For more information see Options
.
Gets the string of the parent specified by this pathname
Description
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.
Usage
## Default S3 method:
getParent(pathname, depth=1L, fsep=.Platform$file.sep, ...)
Arguments
pathname |
A |
depth |
An |
fsep |
A |
... |
Not used. |
Value
Returns a character
string if the parent exists, otherwise NULL
.
Author(s)
Henrik Bengtsson
Gets the unprocessed GString
Description
Gets the unprocessed GString.
Usage
## S3 method for class 'GString'
getRaw(object, ...)
Arguments
... |
Not used. |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
*as.character()
For more information see GString
.
Gets the relative pathname relative to a directory
Description
Gets the relative pathname relative to a directory.
Usage
## Default S3 method:
getRelativePath(pathname, relativeTo=getwd(), caseSensitive=NULL, ...)
Arguments
pathname |
A |
relativeTo |
A |
caseSensitive |
If |
... |
Not used. |
Details
In case the two paths are on different file systems, for instance,
C:/foo/bar/ and D:/foo/, the method returns pathname
as is.
Value
Returns a character
string of the relative pathname.
Non-case sensitive comparison
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.
Author(s)
Henrik Bengtsson
See Also
getAbsolutePath
().
isAbsolutePath
().
Examples
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"
Gets current verbose threshold
Description
Gets current verbose threshold.
Usage
## S3 method for class 'Verbose'
getThreshold(this, ...)
Arguments
... |
Not used. |
Value
Returns a numeric
value.
Author(s)
Henrik Bengtsson
See Also
*setThreshold()
and *isVisible()
.
For more information see Verbose
.
Gets the default timestamp format
Description
Gets the default timestamp format.
Usage
## S3 method for class 'Verbose'
getTimestampFormat(this, ...)
Arguments
... |
Not used. |
Value
Returns a character
string or a function
.
Author(s)
Henrik Bengtsson
See Also
*setTimestampFormat()
.
*timestampOn()
.
For more information see Verbose
.
Parses and evaluates a GString into a regular string
Description
Parses and evaluates a GString into a regular string.
Usage
## Default S3 method:
gstring(..., file=NULL, path=NULL, envir=parent.frame())
Arguments
... |
|
file , path |
Alternatively, a file, a URL or a |
envir |
The |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
gcat
().
Checks if an option exists
Description
Checks if an option exists.
Usage
## S3 method for class 'Options'
hasOption(this, pathname, ...)
Arguments
pathname |
A single or a |
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
*getOption()
.
*setOption()
.
For more information see Options
.
Checks if one or several pathnames has a URL protocol
Description
Checks if one or several pathnames has a URL protocol.
Usage
## Default S3 method:
hasUrlProtocol(pathname, ...)
Arguments
pathname |
|
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
Writes a header
Description
Writes a header surrounded by a frame.
The output is indented according to *enter()
/*exit()
calls.
Usage
## S3 method for class 'Verbose'
header(this, ..., char="-", padding=0, prefix=paste(char, paste(rep(" ",
max(padding, 1)), collapse = ""), sep = ""), level=this$defaultLevel)
Arguments
... |
The title. |
char |
The |
padding |
The number of rows and character to pad the title above, below, and to the left. |
prefix |
The prefix of all padded lines and the title line. |
level |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Concatenating vectors into human-readable strings
Description
Concatenating vectors into human-readable strings such as "1, 2, 3, ..., 10".
Usage
## 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
... |
Arguments to be pasted. |
sep |
A |
collapse , lastCollapse |
The |
maxHead , maxTail , abbreviate |
Non-negative |
empty |
A |
Details
hpaste(..., sep=" ", maxHead=Inf)
corresponds to
paste(..., sep=" ", collapse=", ")
.
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
Internally paste
() is used.
Examples
# 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))
Convert byte sizes into human-readable byte sizes
Description
Convert byte sizes into human-readable byte sizes.
Usage
## S3 method for class 'numeric'
hsize(sizes, digits=1L, units="auto", standard=getOption("hsize.standard", "IEC"),
bytes=getOption("hsize.bytes", "B"), ...)
## S3 method for class 'object_size'
hsize(sizes, ...)
Arguments
sizes |
|
digits |
Number of digits to be presented in the give unit. |
units |
A |
bytes |
The string used for units of bytes without a prefix.
Applied only if |
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
Examples
sizes <- c(1000^(0:8), 1024^(0:8))
df <- data.frame(size=sizes)
df$SI <- hsize(sizes, standard="SI")
df$TB <- hsize(sizes, units="TB")
df$IEC <- hsize(sizes, standard="IEC")
df$TiB <- hsize(sizes, units="TiB")
print(df)
Checks if a set of values are inside one or more intervals
Description
Checks if a set of values are inside one or more intervals.
Usage
## S3 method for class 'numeric'
inAnyInterval(...)
Arguments
... |
Arguments passed to |
Value
Author(s)
Henrik Bengtsson
See Also
Increases (steps) progress bar
Description
Increases (steps) progress bar.
Usage
## S3 method for class 'ProgressBar'
increase(this, stepLength=this$stepLength, visual=TRUE, ...)
Arguments
stepLength |
Positive or negative step length. |
... |
Not used. |
Value
Returns new value.
Author(s)
Henrik Bengtsson
See Also
*setValue()
.
For more information see ProgressBar
.
Insert values to a vector at certain positions
Description
Insert values to a vector at certain positions.
Usage
## Default S3 method:
insert(x, ats, values=NA, useNames=TRUE, ...)
Arguments
x |
The |
ats |
The indices of |
values |
A |
useNames |
If |
... |
Not used. |
Author(s)
Henrik Bengtsson
See Also
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.
Examples
# 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
Description
Install R packages by name or URL.
Usage
## Default S3 method:
installPackages(pkgs, types="auto", repos=getOption("repos"), ..., destPath=".",
cleanup=TRUE)
Arguments
pkgs |
A |
types |
|
repos |
|
... |
Additional arguments passed to |
destPath |
Path where any downloaded files are saved. |
cleanup |
If |
Value
Returns nothing.
Limitations
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.
Author(s)
Henrik Bengtsson
Examples
## 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)
Converts an integer to a binary/octal/hexadecimal number
Description
Converts an integer to a binary/octal/hexadecimal number.
Usage
intToBin(x)
intToOct(x)
intToHex(x)
Arguments
x |
A |
Details
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 2^31-1
.
This limitation is there such that negative values can be converted too.
Value
Returns a character
string of length length(x)
.
For coercions out of range, NA_character_
is returned for
such elements.
Author(s)
Henrik Bengtsson
Generates a vector of indices from a matrix of intervals
Description
Generates a vector of indices from a matrix of intervals.
Usage
## S3 method for class 'matrix'
intervalsToSeq(fromTo, sort=FALSE, unique=FALSE, ...)
Arguments
fromTo |
|
sort |
If |
unique |
If |
... |
Not used. |
Author(s)
Henrik Bengtsson
See Also
Examples
## Not run: See example(seqToIntervals)
Checks if this pathname is absolute
Description
Checks if this pathname is absolute.
Usage
## Default S3 method:
isAbsolutePath(pathname, ...)
Arguments
pathname |
A |
... |
Not used. |
Value
Returns a TRUE
if the pathname is absolute, otherwise FALSE
.
Author(s)
Henrik Bengtsson
Checks if the file specification is a directory
Description
Checks if the file specification is a directory.
Usage
## Default S3 method:
isDirectory(pathname, ...)
Arguments
pathname |
A |
... |
Not used. |
Value
Returns TRUE
if the file specification is a directory, otherwise
FALSE
is returned.
Symbolic links
This function follows symbolic links (also on Windows) and returns a value based on the link target (rather than the link itself).
Author(s)
Henrik Bengtsson
See Also
To check if it is a file see isFile
().
Internally file.info
() is used.
See also file_test
.
Checks if progress bar is completed
Description
Checks if progress bar is completed.
Usage
## S3 method for class 'ProgressBar'
isDone(this, ...)
Arguments
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see ProgressBar
.
Checks if the current file position for a connection is at the 'End of File'
Description
Checks if the current file position for a connection is at the 'End of File'.
Usage
## S3 method for class 'connection'
isEof(con, ...)
Arguments
con |
A |
... |
Not used. |
Details
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.
Value
Returns a logical
.
Author(s)
Henrik Bengtsson
See Also
For more information see connection
.
Checks if the file specification is a file
Description
Checks if the file specification is a file.
Usage
## Default S3 method:
isFile(pathname, ...)
Arguments
pathname |
A |
... |
Not used. |
Value
Returns TRUE
if the file specification is a file, otherwise
FALSE
is returned.
Symbolic links
This function follows symbolic links (also on Windows) and returns a value based on the link target (rather than the link itself).
Author(s)
Henrik Bengtsson
See Also
To check if it is a directory see isDirectory
().
Internally file.info
() is used.
See also file_test
.
Checks if settings has been modified compared to whats on file
Description
Checks if settings has been modified compared to whats on file.
Usage
## S3 method for class 'Settings'
isModified(this, ...)
Arguments
... |
Not used. |
Value
Returns TRUE
if settings have been modified since lasted loaded, or if
they never have been loaded. Otherwise FALSE
is returned.
Author(s)
Henrik Bengtsson
See Also
For more information see Settings
.
Checks if the output is on
Description
Checks if the output is on.
Usage
## S3 method for class 'NullVerbose'
isOn(this, ...)
Arguments
... |
Not used. |
Value
Returns always FALSE
.
Author(s)
Henrik Bengtsson
See Also
For more information see NullVerbose
.
Checks if the output is on
Description
Checks if the output is on.
Usage
## S3 method for class 'Verbose'
isOn(this, ...)
Arguments
... |
Not used. |
Value
Returns TRUE
if output is on, otherwise FALSE
.
Author(s)
Henrik Bengtsson
See Also
*on()
and *off()
.
For more information see Verbose
.
Checks if there is an open connection to a file
Description
Checks if there is an open connection to a file.
Usage
## S3 method for class 'character'
isOpen(pathname, rw=c("read", "write"), ...)
Arguments
pathname |
|
rw |
A |
... |
Not used. |
Value
Returns a logical
vector
indicating for each file whether there
exists an open file connection
or not.
Author(s)
Henrik Bengtsson
See Also
See isOpen()
in connections
.
showConnections
().
Checks if a package is installed or not
Description
Checks if a package is installed or not.
Usage
## Default S3 method:
isPackageInstalled(package, ...)
Arguments
package |
|
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
Checks if a package is loaded or not
Description
Checks if a package is loaded or not.
Note that, contrary to require()
,
this function does not load the package if not loaded.
Usage
## Default S3 method:
isPackageLoaded(package, version=NULL, ...)
Arguments
package |
The name of the package. |
version |
A |
... |
Not used. |
Value
Returns a logical
.
Author(s)
Henrik Bengtsson
See Also
To check if a package is installed or not, see isPackageInstalled
().
Identifies all entries with replicated values
Description
Identifies all entries with replicated values, that is, with values that exist more than once.
Usage
isReplicated(x, ...)
replicates(x, ...)
Arguments
x |
A |
... |
Additional arguments passed to |
Details
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)])))
Value
A logical
vector
of length K,
where TRUE
indicates that the value exists elsewhere,
otherwise not.
Author(s)
Henrik Bengtsson
See Also
Internally duplicated
() is used.
See also isSingle
().
Examples
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
Description
Identifies all entries that exists exactly once.
Usage
isSingle(x, ...)
singles(x, ...)
Arguments
x |
A |
... |
Additional arguments passed to |
Value
A logical
vector
of length K,
indicating whether the value is unique or not.
Author(s)
Henrik Bengtsson
See Also
Internally isReplicated
() is used.
Checks if one or several pathnames is URLs
Description
Checks if one or several pathnames is URLs.
Usage
## Default S3 method:
isUrl(pathname, ...)
Arguments
pathname |
|
... |
Not used. |
Value
Returns a logical
vector
of either TRUE
or FALSE
.
Author(s)
Henrik Bengtsson
Checks if a certain verbose level will be shown or not
Description
Checks if a certain verbose level will be shown or not.
Usage
## S3 method for class 'NullVerbose'
isVisible(this, ...)
Arguments
... |
Not used. |
Value
Returns always FALSE
.
Author(s)
Henrik Bengtsson
See Also
For more information see NullVerbose
.
Checks if a certain verbose level will be shown or not
Description
Checks if a certain verbose level will be shown or not.
Usage
## S3 method for class 'Verbose'
isVisible(this, level=this$defaultLevel, ...)
Arguments
level |
A |
... |
Not used. |
Value
Returns TRUE
, if given level is greater than (not equal to) the current
threshold, otherwise FALSE
is returned.
Author(s)
Henrik Bengtsson
See Also
*getThreshold()
and *setThreshold()
.
For more information see Verbose
.
Checks if a value is (close to) zero or not
Description
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).
Usage
## Default S3 method:
isZero(x, neps=1, eps=.Machine$double.eps, ...)
Arguments
x |
A |
eps |
The smallest possible floating point. |
neps |
A scale factor of |
... |
Not used. |
Value
Returns a logical
vector
indicating if the elements are zero or not.
Author(s)
Henrik Bengtsson
See Also
all.equal
().
Comparison
.
.Machine
.
Examples
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
Gets the time when the file was last modified
Description
Gets the time when the file was last modified. The time is returned as a POSIXct
object.
Usage
## Default S3 method:
lastModified(pathname, ...)
Arguments
pathname |
A |
... |
Not used. |
Value
Returns POSIXct
object specifying when the file was last modified.
If the file does not exist or it is a directory, 0
is returned.
Symbolic links
This function follows symbolic links (also on Windows) and returns a value based on the link target (rather than the link itself).
Author(s)
Henrik Bengtsson
See Also
Internally file.info
() is used.
Creates a cloned instance with a higher threshold
Description
Creates a cloned instance with a higher threshold.
Usage
## S3 method for class 'Verbose'
less(this, dThreshold=1, ...)
Arguments
dThreshold |
The amount the threshold should be raised. |
... |
Not used. |
Value
Returns a cloned Verbose
object.
Author(s)
Henrik Bengtsson
See Also
*more()
For more information see Verbose
.
Gets the file names in the directory
Description
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.
Usage
## Default S3 method:
listDirectory(path=".", pattern=NULL, recursive=FALSE, allNames=FALSE, fullNames=FALSE,
...)
Arguments
path |
A path to be listed. |
pattern |
A |
recursive |
If |
allNames |
If |
fullNames |
If |
... |
Not used. |
Value
Returns a vector
of file names.
Recursive searching
Recursive searching of directory structure is done breath-first in a lexicographic order.
Author(s)
Henrik Bengtsson
See Also
Internally list.files
() is used.
Loads settings from file
Description
Loads settings from file. If the settings was read from file, they are by default written back to the same file. If this was not the case, it defaults to the settings file in the home directory of the current user.
Usage
## S3 method for class 'Settings'
loadAnywhere(static, file=NULL, ..., verbose=FALSE)
Arguments
file |
A |
... |
Arguments passed to |
verbose |
If |
Value
Returns a Settings object if file was successfully read,
otherwise NULL
.
Author(s)
Henrik Bengtsson
See Also
*saveAnywhere()
.
For more information see Settings
.
Method to load object from a file or a connection
Description
Method to load object from a file or a connection, which previously have been saved using saveObject
().
Usage
## Default S3 method:
loadObject(file, path=NULL, format=c("auto", "xdr", "rds"), ...)
Arguments
file |
A filename or |
path |
The path where the file exists. |
format |
File format. |
... |
Not used. |
Details
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.
Value
Returns the saved object.
Author(s)
Henrik Bengtsson
See Also
saveObject
() to save an object to file.
Internally load
() is used.
See also loadToEnv
().
See also saveRDS
().
Method to load objects to a new environment
Description
Method to load objects to a new environment for objects previously stored by save
().
Usage
## Default S3 method:
loadToEnv(file, ..., envir=new.env())
Arguments
... |
Arguments passed to |
envir |
The |
Value
Returns environment
envir
containing all loaded objects.
Author(s)
Henrik Bengtsson
See Also
Internally load
() is used.
See also loadObject
().
Maps values to intervals
Description
Maps values to intervals by returning an index vector
specifying the (first)
interval that each value maps to, if any.
Usage
## S3 method for class 'numeric'
mapToIntervals(x, intervals, includeLower=TRUE, includeUpper=TRUE, ...)
Arguments
x |
|
intervals |
The N intervals to be matched against.
If an Nx2 |
includeLower , includeUpper |
If |
... |
Not used. |
Value
Returns an integer
vector
of length K.
Values that do not map to any interval have return value NA
.
Author(s)
Henrik Bengtsson
See Also
inAnyInterval
().
match
().
findInterval
().
cut
().
Merges intervals
Description
Merges intervals by returning an index vector
specifying the (first)
interval that each value maps to, if any.
Usage
## S3 method for class 'numeric'
mergeIntervals(intervals, ...)
Arguments
intervals |
The N intervals to be merged.
If an Nx2 |
... |
Not used. |
Details
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}.
Value
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.
Author(s)
Henrik Bengtsson
See Also
inAnyInterval
().
match
().
Creates a directory including any necessary but nonexistent parent directories
Description
Creates a directory including any necessary but nonexistent parent directories.
Usage
## Default S3 method:
mkdirs(pathname, mustWork=FALSE, maxTries=5L, ...)
Arguments
pathname |
A |
mustWork |
If |
maxTries |
A positive |
... |
Not used. |
Value
Returns TRUE
if the directory was successfully created,
otherwise FALSE
.
Note that if the directory already exists, FALSE
is returned.
Slow file systems
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.
Author(s)
Henrik Bengtsson
See Also
Internally dir.create
() is used.
Creates a cloned instance with a lower threshold
Description
Creates a cloned instance with a lower threshold.
Usage
## S3 method for class 'Verbose'
more(this, dThreshold=1, ...)
Arguments
dThreshold |
The amount the threshold should be lowered. |
... |
Not used. |
Value
Returns a cloned Verbose
object.
Author(s)
Henrik Bengtsson
See Also
*less()
For more information see Verbose
.
Miscellaneous functions for outputting via message()
Description
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()))
.
Usage
mout(..., appendLF=FALSE)
Arguments
... |
Arguments passed to the underlying output method. |
appendLF |
A |
Value
Returns what the message
() returns.
Author(s)
Henrik Bengtsson
Examples
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)
Moves a environment in the search path to another position
Description
Moves a environment in the search path to another position.
Usage
## Default S3 method:
moveInSearchPath(from, to, where=c("before", "after"), ...)
Arguments
from |
An |
to |
The destination position like the |
where |
A |
... |
Not used. |
Details
It is not possible to move the first environment in the search path, i.e. the so called global environment.
Value
Returns (invisibly) the name of the environment moved, if it was
moved, otherwise NULL
.
Author(s)
Henrik Bengtsson
See Also
search
().
Examples
# Make package 'utils' come behind 'datasets' in the search path
moveInSearchPath("package:utils", "package:datasets", where="after")
A \"pager\" function that outputs to standard error
Description
A \"pager\" function that outputs to standard error and is compatible with file.show
().
Usage
mpager(files, header=NULL, title="R Information", delete.file=FALSE)
Arguments
files |
|
header |
|
title |
A |
delete.file |
If |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
file.show
() and argument pager
.
Gets the full pathname of all (non-list) options
Description
Gets the full pathname of all (non-list) options.
Usage
## S3 method for class 'Options'
names(x, ...)
Arguments
... |
Not used. |
Value
Returns a vector
of character
strings.
Author(s)
Henrik Bengtsson
See Also
For more information see Options
.
Gets the number of options set
Description
Gets the number of options set.
Usage
## S3 method for class 'Options'
nbrOfOptions(this, ...)
Arguments
... |
Not used. |
Value
Returns an integer
.
Author(s)
Henrik Bengtsson
See Also
For more information see Options
.
Writes a newline
Description
Writes a newline.
Usage
## S3 method for class 'TextStatusBar'
newline(this, ...)
Arguments
... |
Not used. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see TextStatusBar
.
Writes one or several empty lines
Description
Writes one or several empty lines.
Usage
## S3 method for class 'Verbose'
newline(this, n=1, ..., level=this$defaultLevel)
Arguments
n |
The number of empty lines to write. |
... |
Not used. |
level |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Gets the pathname or a connection to the NULL device on the current platform
Description
Gets the pathname or a connection to the NULL device on the current platform.
Usage
nullfile()
nullcon()
Value
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.
Author(s)
Henrik Bengtsson
See Also
In R (>= 3.6.0), there exists base::nullfile()
, which is
identical to R.utils::nullfile()
.
Turn off the output
Description
Turn off the output.
Usage
## S3 method for class 'Verbose'
off(this, ...)
Arguments
... |
Not used. |
Value
Returns (invisibly) FALSE
.
Author(s)
Henrik Bengtsson
See Also
*on()
and *isOn()
.
For more information see Verbose
.
Turn on the output
Description
Turn on the output.
Usage
## S3 method for class 'Verbose'
on(this, ...)
Arguments
... |
Not used. |
Value
Returns (invisibly) TRUE
.
Author(s)
Henrik Bengtsson
See Also
*off()
and *isOn()
.
For more information see Verbose
.
Registers a function to be called when the R garbage collector is (detected to be) running
Description
Registers a function to be called when the R garbage collector is (detected to be) running.
Usage
## Default S3 method:
onGarbageCollect(fcn, action=c("prepend", "append", "replace"), ...)
Arguments
fcn |
A |
action |
A |
... |
Not used. |
Value
Returns (invisibly) the hooks successfully called.
Author(s)
Henrik Bengtsson
Examples
## 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
Description
Registers a function to be called when the R session finishes.
Usage
## Default S3 method:
onSessionExit(fcn, action=c("prepend", "append", "replace"), ...)
Arguments
fcn |
A |
action |
A |
... |
Not used. |
Details
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.
Value
Returns (invisibly) the hooks successfully called.
Author(s)
Henrik Bengtsson
See Also
.Last()
.
finalizeSession
().
Examples
## Not run:
onSessionExit(function(...) {
message("Bye bye world!")
})
quit()
## End(Not run)
Parses a GString
Description
Parses a GString.
Usage
## S3 method for class 'GString'
parse(object, ...)
Arguments
... |
Not used. |
Value
Returns a list
structure.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Parses one single smart comment
Description
Parses one single smart comment.
Usage
## S3 method for class 'SmartComments'
parse(this, lines, currLine, ..., letter=this$letter, pattern=NULL)
Arguments
lines |
A |
currLine |
The line number on which to smart smart comment begins. |
... |
Not used. |
letter |
The letter of the smart comment. Available to avoid lookup at every line. |
pattern |
The pattern of the smart comment. |
Value
Returns a list
structure.
Author(s)
Henrik Bengtsson
See Also
For more information see SmartComments
.
Patches installed and loaded packages and more
Description
Patches installed and loaded packages and more.
Usage
## Default S3 method:
patchCode(paths=NULL, recursive=TRUE, suppressWarnings=TRUE,
knownExtensions=c("R", "r", "S", "s"), verbose=FALSE, ...)
Arguments
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. |
Details
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.
Value
Returns (invisibly) the number of files sourced.
Author(s)
Henrik Bengtsson
See Also
Examples
## 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
Description
Drops a backup suffix from the backup pathname and, by default, restores an existing backup file accordingly by renaming it.
Usage
## Default S3 method:
popBackupFile(filename, path=NULL, suffix=".bak", isFile=TRUE,
onMissing=c("ignore", "error"), drop=TRUE, ..., verbose=FALSE)
Arguments
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 |
Value
Returns the pathname with the backup suffix dropped.
Author(s)
Henrik Bengtsson
See Also
See pushBackupFile
() for more details and an example.
Adds a message above the status bar
Description
Adds a message above the status bar by scrolling up previous messages popped.
Usage
## S3 method for class 'TextStatusBar'
popMessage(this, ..., collapse="", sep="")
Arguments
... |
Arguments passed to |
collapse , sep |
Default values to |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see TextStatusBar
.
Drops a temporary suffix from the temporary pathname
Description
Drops a temporary suffix from the temporary pathname and, by default, renames an existing temporary file accordingly.
Usage
## Default S3 method:
popTemporaryFile(filename, path=NULL, suffix=".tmp", isFile=TRUE, ..., verbose=FALSE)
Arguments
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 |
Details
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.
Value
Returns the pathname with the temporary suffix dropped.
Author(s)
Henrik Bengtsson
See Also
See pushTemporaryFile
() for more details and an example.
Prints the processed GString
Description
Prints the processed GString.
Usage
## S3 method for class 'GString'
print(x, ...)
Arguments
... |
Arguments passed to |
Value
Returns (invisibly) the process GString character
string.
Author(s)
Henrik Bengtsson
See Also
For more information see GString
.
Prints objects if above threshold
Description
Prints objects if above threshold. The output is not indented.
Usage
## S3 method for class 'Verbose'
print(x, ..., level=this$defaultLevel)
Arguments
... |
Objects to be passed to |
level |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Outputs any warnings recorded
Description
Outputs any warnings recorded.
The output is indented according to *enter()
/*exit()
calls.
Usage
## S3 method for class 'Verbose'
printWarnings(this, title="Warnings detected:", ..., level=this$defaultLevel)
Arguments
title |
A |
... |
Arguments passed to |
level |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
C-style formatted output
Description
C-style formatted output.
Usage
## Default S3 method:
printf(fmt, ..., sep="", file="")
Arguments
fmt |
A |
... |
Additional arguments |
sep |
|
file |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For C-style formatting of character
strings, see sprintf
().
Examples
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))
Formats and prints object if above threshold
Description
Formats and prints object if above threshold.
The output is indented according to *enter()
/*exit()
calls.
Usage
## S3 method for class 'Verbose'
printf(this, fmtstr, ..., level=this$defaultLevel, timestamp=this$.timestamp)
Arguments
... |
Objects to be passed to |
fmtstr |
A |
level |
A |
timestamp |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Prompt user to save modified settings
Description
Prompt user to save modified settings.
Usage
## S3 method for class 'Settings'
promptAndSave(this, saveOption="saveSettings", settingsName=NULL, ...)
Arguments
saveOption |
A |
... |
Arguments passed to |
Details
If settings has been modified since loaded, the user is by default
prompted to save the settings (if R runs interactively).
To save or not save without asking or when R runs non-interactively,
set option "saveSettings"
to "yes" or "no", respectively.
For prompting the user, use "prompt".
Value
Returns TRUE
if settings were successfully written to file,
otherwise FALSE
is returned. An exception may also be thrown.
Author(s)
Henrik Bengtsson
See Also
*isModified()
.
interactive
().
For more information see Settings
.
Appends a backup suffix to the pathname
Description
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.
Usage
## Default S3 method:
pushBackupFile(filename, path=NULL, suffix=".bak", isFile=TRUE,
onMissing=c("ignore", "error"), copy=FALSE, overwrite=TRUE, ..., verbose=FALSE)
Arguments
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 |
Value
Returns the pathname with the suffix appended.
Author(s)
Henrik Bengtsson
See Also
Examples
# 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)
Pushes the current indentation state of the Verbose object
Description
Pushes the current indentation state of the Verbose object, which is controlled by *enter()
and
*exit()
. By pushing the state when entering a function and
using on.exit
() to pop the state, the correct state will
set regardless of if the functions returned naturally or via an error.
Usage
## S3 method for class 'Verbose'
pushState(this, ...)
Arguments
... |
Not used. |
Value
Returns (invisibly) TRUE
.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Appends a temporary suffix to the pathname
Description
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.
Usage
## Default S3 method:
pushTemporaryFile(filename, path=NULL, suffix=".tmp", isFile=FALSE, ..., verbose=FALSE)
Arguments
filename |
The filename of the file. |
path |
The path of the file. |
suffix |
The suffix to be appended. |
isFile |
If |
... |
Not used. |
verbose |
Details
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.
Value
Returns the pathname with the suffix appended.
Author(s)
Henrik Bengtsson
See Also
Examples
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
Description
Gets the on R CMD check if the current R session was launched by it.
Usage
queryRCmdCheck(...)
Arguments
... |
Not used. |
Value
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.
Limitations
This function only works if the working directory has not been changed.
Author(s)
Henrik Bengtsson
Examples
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
Description
Reads binary data from disjoint sections of a connection or a file.
Usage
## Default S3 method:
readBinFragments(con, what, idxs=1, origin=c("current", "start"), size=NA, ...,
verbose=FALSE)
Arguments
con |
A |
what |
A |
idxs |
A |
origin |
A |
size |
The size of the data type to be read. If |
... |
Additional arguments passed to |
verbose |
Value
Returns a vector
of the requested mode
().
Author(s)
Henrik Bengtsson
See Also
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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
Description
Reads one or more Rd help files in a certain format.
Usage
## Default S3 method:
readRdHelp(..., format=c("text", "html", "latex", "rd"), drop=TRUE)
Arguments
... |
Arguments passed to |
format |
A |
drop |
If |
Value
Returns a list
of character
strings or a single character
string.
Author(s)
Henrik Bengtsson
Reads a file in table format
Description
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.
Usage
## 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)
Arguments
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 |
Value
Returns a data.frame
.
Author(s)
Henrik Bengtsson
See Also
readTableIndex
().
read.table
.
colClasses
().
Reads a single column from file in table format
Description
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
().
Usage
## Default S3 method:
readTableIndex(..., indexColumn=1, colClass="character", verbose=FALSE)
Arguments
indexColumn |
An single |
colClass |
A single |
... |
Arguments passed to |
verbose |
Value
Returns a vector
.
Author(s)
Henrik Bengtsson
See Also
readTable
().
Examples
## 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)
Description
Reads a Microsoft Windows Shortcut (.lnk file).
Usage
## Default S3 method:
readWindowsShellLink(con, clean=TRUE, verbose=FALSE, ...)
Arguments
con |
A |
clean |
If |
verbose |
If |
... |
Not used. |
Details
This function is implemented based on the official file format
specification [1].
It is intended to replace readWindowsShortcut
(), which was
written based on reverse engineering (before [1] was made available).
Value
Returns a list
structure.
Author(s)
Henrik Bengtsson
References
[1] [MS-SHLLINK]: Shell Link (.LNK) Binary File Format, Microsoft Inc.,
September 25, 2009.
See Also
readWindowsShortcut
()
filePath
Examples
pathname <- system.file("data-ex/HISTORY.LNK", package="R.utils")
lnk <- readWindowsShellLink(pathname)
str(lnk)
str(lnk$pathname)
lnk0 <- readWindowsShortcut(pathname)
str(lnk0$pathname)
Reads a Microsoft Windows Shortcut (.lnk file)
Description
Reads a Microsoft Windows Shortcut (.lnk file).
Usage
## Default S3 method:
readWindowsShortcut(con, verbose=FALSE, ...)
Arguments
con |
A |
verbose |
If |
... |
Not used. |
Details
The MIME type for a Windows Shortcut file is
application/x-ms-shortcut
.
Value
Returns a list
structure.
Author(s)
Henrik Bengtsson
References
[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.
See Also
createWindowsShortcut
() and
filePath()
Examples
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")
Re-assigns a new value to an existing object in a loaded package
Description
Re-assigns a new value to an existing object in a loaded package.
Usage
## Default S3 method:
reassignInPackage(name, pkgName, value, keepOld=TRUE, ...)
Arguments
name |
The name of the object to be replaced." |
pkgName |
The name of the package where the object lives." |
value |
The new value to be assigned. |
keepOld |
If |
... |
Not used. |
Value
Returns (invisibly) the new object.
Author(s)
Henrik Bengtsson
See Also
See assignInNamespace()
in getFromNamespace
.
Removes a directory
Description
Removes a directory, and if requested, also its contents.
Usage
## Default S3 method:
removeDirectory(path, recursive=FALSE, mustExist=TRUE, ...)
Arguments
path |
A |
recursive |
If |
mustExist |
If |
... |
Not used. |
Value
Returns (invisibly) TRUE
, the directory was successfully removed,
otherwise FALSE
, unless an exception is thrown.
Symbolic links
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.
Author(s)
Henrik Bengtsson
See Also
Internally unlink
() is used.
Renames a file (or a directory) atomically/safely
Description
Renames a file (or a directory) atomically/safely, by also asserting that it was successfully renamed without side effects. If failing to rename and overwrite an existing file, the original file is kept.
Usage
## Default S3 method:
renameFile(pathname, newPathname, overwrite=FALSE, ..., verbose=FALSE)
Arguments
pathname |
The pathname of the file to be renamed. |
newPathname |
The new pathname.
If an existing directory and the source is a file, then the
destination becomes |
overwrite |
If |
... |
Not used. |
verbose |
See |
Value
Returns TRUE
if the file was successfully renamed.
If it failed, an exception is thrown.
Author(s)
Henrik Bengtsson
See Also
file.rename()
.
Sample values from a set of elements
Description
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.
Usage
## Default S3 method:
resample(x, ...)
Arguments
x |
A |
... |
Additional arguments passed to |
Value
Returns a sampled vector
of the same data types as argument x
.
Author(s)
Henrik Bengtsson
References
[1] Henrik Bengtsson,
Using sample() to sample one value from a single value?,
R-devel mailing list, 2010-11-03.
See Also
Internally sample.int
() is used.
Reset progress bar
Description
Reset progress bar by setting the value to zero and updating the display.
Usage
## S3 method for class 'ProgressBar'
reset(this, visual=TRUE, ...)
Arguments
visual |
If |
... |
Not used. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
*setValue()
.
For more information see ProgressBar
.
Resets a SmartComments compiler
Description
Resets a SmartComments compiler.
Usage
## S3 method for class 'SmartComments'
reset(this, ...)
Arguments
... |
Not used. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see SmartComments
.
Resets a VComments compiler
Description
Resets a VComments compiler.
Usage
## S3 method for class 'VComments'
reset(this, ...)
Arguments
... |
Not used. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see VComments
.
Writes a ruler
Description
Writes a ruler.
Usage
## S3 method for class 'Verbose'
ruler(this, char="-", toColumn=this$rightMargin, length=toColumn - this$indentPos,
level=this$defaultLevel, ...)
Arguments
char |
A |
toColumn |
The column number where the ruler should finish. |
length |
The length of the ruler. |
... |
Not used. |
level |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Saves settings to file
Description
Saves settings to file. If the settings was read from file, they are by default written back to the same file. If this was not the case, it defaults to the settings file in the home directory of the current user.
Usage
## S3 method for class 'Settings'
saveAnywhere(this, file=NULL, path="~", ...)
Arguments
file |
A |
path |
The default path, if no settings files are specified. This defaults to the current user's home directory. |
... |
Arguments passed to
|
Value
Returns (invisibly) the pathname to the save settings file.
Author(s)
Henrik Bengtsson
See Also
*loadAnywhere()
.
For more information see Settings
.
Saves an object to a file or a connection
Description
Saves an object to a file or a connection.
Usage
## Default S3 method:
saveObject(object, file=NULL, path=NULL, format=c("auto", "xdr", "rds"), compress=TRUE,
..., safe=TRUE)
Arguments
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 |
Value
Returns (invisibly) the pathname or the connection
.
Author(s)
Henrik Bengtsson
See Also
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
Description
Gets a short human readable string representation of an vector of indices.
Usage
## Default S3 method:
seqToHumanReadable(idx, tau=2L, delimiter="-", collapse=", ", ...)
Arguments
idx |
|
tau |
A non-negative |
delimiter |
A |
collapse |
A |
... |
Not used. |
Author(s)
Henrik Bengtsson
See Also
Internally, seqToIntervals
() is used.
Examples
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
Description
Gets all contiguous intervals of a vector of indices.
Usage
## Default S3 method:
seqToIntervals(idx, ...)
Arguments
idx |
|
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
*intervalsToSeq()
.
To identify sequences of equal values, see rle
().
Examples
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 the current default verbose level
Description
Sets the current default verbose level.
Usage
## S3 method for class 'Verbose'
setDefaultLevel(this, level, ...)
Arguments
level |
A |
... |
Not used. |
Value
Returns old default level.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Sets the value of a label
Description
Sets the value of a label address either by its index or its names.
Usage
## S3 method for class 'TextStatusBar'
setLabel(this, label, value, ...)
Arguments
label |
The index or the name of the label. |
value |
The value of the label. |
... |
Not used. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
*setLabels()
*getLabel()
For more information see TextStatusBar
.
Sets new values of given labels
Description
Sets new values of given labels.
Usage
## S3 method for class 'TextStatusBar'
setLabels(this, ...)
Arguments
... |
A set of named arguments. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
*setLabel()
.
*updateLabels()
.
For more information see TextStatusBar
.
Sets maximum value
Description
Sets maximum value.
Usage
## S3 method for class 'ProgressBar'
setMaxValue(this, maxValue, ...)
Arguments
maxValue |
New maximum value. |
... |
Not used. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see ProgressBar
.
Sets a option in R
Description
Sets a option in R by specifying its name as a character
string.
Usage
## Default S3 method:
setOption(x, value, ...)
Arguments
x |
The name of the option to be set. |
value |
The new value of the option. |
... |
Not used. |
Value
Returns (invisibly) the previous value of the option.
Author(s)
Henrik Bengtsson
See Also
See getOption
() and "base::options".
Sets an option
Description
Sets an option in the options tree structure.
Usage
## S3 method for class 'Options'
setOption(this, pathname, value, overwrite=TRUE, ...)
Arguments
pathname |
A single |
value |
The value to be assigned to the option. |
overwrite |
If |
... |
Not used. |
Value
Returns (invisibly) the old option value.
Author(s)
Henrik Bengtsson
See Also
*hasOption()
.
*setOption()
.
For more information see Options
.
Sets current progress
Description
Sets current progress.
Usage
## S3 method for class 'ProgressBar'
setProgress(this, progress, visual=TRUE, ...)
Arguments
progress |
A |
visual |
If |
... |
Not used. |
Value
Returns old value.
Author(s)
Henrik Bengtsson
See Also
*setValue()
.
*increase()
.
*reset()
.
For more information see ProgressBar
.
Sets default step length
Description
Sets default step length.
Usage
## S3 method for class 'ProgressBar'
setStepLength(this, stepLength, ...)
Arguments
stepLength |
New default step length. |
... |
Not used. |
Value
Returns on step length.
Author(s)
Henrik Bengtsson
See Also
For more information see ProgressBar
.
Sets verbose threshold
Description
Sets verbose threshold. Output requests below this threshold will be ignored.
Usage
## S3 method for class 'Verbose'
setThreshold(this, threshold, ...)
Arguments
threshold |
A |
... |
Not used. |
Value
Returns old threshold.
Author(s)
Henrik Bengtsson
See Also
*getThreshold()
and *isVisible()
.
For more information see Verbose
.
Sets values for which ticks should be visible
Description
Sets values for which ticks should be visible.
Usage
## S3 method for class 'ProgressBar'
setTicks(this, ticks=10, ...)
Arguments
ticks |
Tick positions (values). |
... |
Not used. |
Value
Returns old tick positions.
Author(s)
Henrik Bengtsson
See Also
For more information see ProgressBar
.
Sets the default timestamp format
Description
Sets the default timestamp format.
Usage
## S3 method for class 'Verbose'
setTimestampFormat(this, format="%Y%m%d %H:%M:%S|", ...)
Arguments
format |
If a |
... |
Not used. |
Value
Returns (invisibly) the old timestamp format.
Author(s)
Henrik Bengtsson
See Also
*getTimestampFormat()
.
*timestampOn()
.
For more information see Verbose
.
Sets current value
Description
Sets current value. Note that this method does not update the bar visually.
Usage
## S3 method for class 'ProgressBar'
setValue(this, value, ...)
Arguments
value |
A |
... |
Not used. |
Value
Returns old value.
Author(s)
Henrik Bengtsson
See Also
*setProgress()
.
*increase()
.
*reset()
.
For more information see ProgressBar
.
Open a file or URL using Windows File Associations
Description
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.
Usage
shell.exec2(file)
Arguments
file |
A |
Details
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).
Value
Returns nothing.
Setting on startup
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.
Author(s)
Henrik Bengtsson
Sources files recursively to either local or global environment
Description
Sources files recursively to either local or global environment.
Usage
## 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)
Arguments
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 |
Value
Returns a vector
of the full pathnames of the files sourced.
Details
Subdirectories and files in each (sub-)directory are sourced in lexicographic order.
Hooks
This method does not provide hooks, but the internally used
sourceTo
() does.
Author(s)
Henrik Bengtsson
See Also
sourceTo
() and compare to source
().
Parses and evaluates code from a file or a connection
Description
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.
Usage
## Default S3 method:
sourceTo(file, path=NULL, chdir=FALSE, ..., local=TRUE, envir=parent.frame(),
modifiedOnly=FALSE)
Arguments
file |
A |
path |
An optional |
chdir |
If |
... |
Arguments to |
local |
If |
envir |
An |
modifiedOnly |
If |
Value
Return the result of source
().
Hooks
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.
Author(s)
Henrik Bengtsson
See Also
sourceDirectory
().
sys.source
() and source
().
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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
Description
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.
Usage
## Default S3 method:
splitByPattern(str, pattern, ...)
Arguments
str |
A single |
pattern |
A regular expression |
... |
Not used. |
Value
Returns a named character
vector
with names equal to "TRUE"
if element is a pattern part and "FALSE"
otherwise.
Author(s)
Henrik Bengtsson
See Also
Compare to strsplit
().
Examples
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
Description
Writes text in the margin along the sides of a plot.
Usage
## 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"), ...)
Arguments
text |
The text to be written. See |
side |
An |
line |
A |
pos |
A |
margin |
|
charDim |
A |
cex |
A |
... |
Additional arguments passed to |
Value
Returns what mtext
returns.
Author(s)
Henrik Bengtsson
See Also
Internally mtext
is used.
Prints the structure of the options
Description
Prints the structure of the options.
Usage
## S3 method for class 'Options'
str(object, header=paste(class(this)[1], ":\n", sep = ""), ...)
Arguments
header |
A |
... |
Not used. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Options
.
Prints the structure of an object if above threshold
Description
Prints the structure of an object if above threshold. The output is not indented.
Usage
## S3 method for class 'Verbose'
str(object, ..., level=this$defaultLevel)
Arguments
... |
Objects to be passed to |
level |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Creates a grid of subplots
Description
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.
Usage
## Default S3 method:
subplots(n=1, nrow=NULL, ncol=NULL, byrow=TRUE, ...)
Arguments
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. |
Value
Returns the matrix
containing the order of plots.
Author(s)
Henrik Bengtsson
See Also
layout
and layout.show
().
Examples
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))
Generates a summary of an object if above threshold
Description
Generates a summary of an object if above threshold. The output is not indented.
Usage
## S3 method for class 'Verbose'
summary(object, ..., level=this$defaultLevel)
Arguments
... |
Objects to be passed to |
level |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Swaps x and y coordinates of a density object
Description
Swaps x and y coordinates of a density object returned by density
.
Usage
## S3 method for class 'density'
swapXY(object, ...)
Arguments
... |
Not used. |
Value
Returns a 'density' object of the same class with elements 'x' and 'y' swapped.
Author(s)
Henrik Bengtsson
See Also
See density
for estimating densities.
See *draw()
for plotting a density along one of the sides.
Launches another R process from within R
Description
Launches another R process from within R via system
() by automatically locating the
R executable, cf [1].
Usage
## Default S3 method:
systemR(command="", ..., Rcommand="R", verbose=FALSE)
Arguments
command |
A |
... |
Additional arguments passed to |
Rcommand |
A |
verbose |
Value
Returns what system
() returns.
Author(s)
Henrik Bengtsson
References
[1] R-devel thread 'Best way to locate R executable from within R?', May 22, 2012.
See Also
The R executable is located using R.home
(), which
is then launched using system
().
Examples
res <- systemR(paste("--slave -e", shQuote("cat(runif(1))")), intern=TRUE)
cat("A random number: ", res, "\n", sep="")
Gets a unique non-existing temporary variable name
Description
Gets a unique non-existing temporary variable name, and optionally assigns it an initial value.
Usage
tempvar(prefix="var", value, envir=parent.frame(), inherits=FALSE)
Arguments
prefix |
A |
value |
(optional) If given, a variable with the temporary
name is assigned this value. Only works if |
envir |
An |
inherits |
A |
Value
Returns a character
string.
Author(s)
Henrik Bengtsson
See Also
Examples
# Get a temporary variable
name <- tempvar()
print(name)
# Get and assign a temporary variable
name <- tempvar(value=base::letters)
print(name)
str(get(name))
# Get a temporary variable with custom prefix
name <- tempvar(prefix=".hidden")
print(name)
# Get a temporary variable for a data.frame
name <- tempvar(envir = datasets::mtcars)
print(name)
Writes a timestamp
Description
Writes a timestamp with default format [2005-06-23 21:20:03].
Usage
## S3 method for class 'Verbose'
timestamp(this, format=getTimestampFormat(this), ...)
Arguments
format |
A |
... |
Not used. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.
Turns automatic timestamping on and off
Description
Turns automatic timestamping on and off.
Usage
## S3 method for class 'Verbose'
timestampOn(this, ...)
Arguments
... |
Not used. |
Value
Returns (invisibly) the old timestamp status.
Author(s)
Henrik Bengtsson
See Also
*setTimestampFormat()
.
*timestampOn()
.
For more information see Verbose
.
Creates a temporary file with content
Description
Creates a temporary file with content that will auto delete as soon as there is no longer any references to it.
Usage
tmpfile(content=NULL, ...)
Arguments
content |
A |
... |
Optional arguments passed to |
Value
The absolute pathname to the temporary file.
Author(s)
Henrik Bengtsson
See Also
tempfile
().
Examples
md5 <- tools::md5sum(tmpfile("Hello world!"))
print(md5)
Converts a string of words into a merged camel-cased word
Description
Converts a string of words into a merged camel-cased word, e.g. "a single espresso" is converted to "aSingleEspresso".
Usage
## Default S3 method:
toCamelCase(s, capitalize=FALSE, preserveSameCase=FALSE, split="[ \t]+", ...)
Arguments
s |
|
capitalize |
If |
preserveSameCase |
If |
split |
A pattern used to identify words. See |
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
capitalize
.
chartr
().
Examples
s <- "hello world"
print(toCamelCase(s)) # helloWorld
print(toCamelCase(s, capitalize=TRUE)) # HelloWorld
stopifnot(toCamelCase(s) == toCamelCase(toCamelCase(s)))
s <- "GEO Accession"
print(toCamelCase(s)) # gEOAccession
print(toCamelCase(s, preserveSameCase=TRUE)) # geoAccession
print(toCamelCase(s, capitalize=TRUE)) # GEOAccession
print(toCamelCase(s, capitalize=TRUE, preserveSameCase=TRUE)) # GEOAccession
stopifnot(toCamelCase(s) == toCamelCase(toCamelCase(s)))
Converts a pathname into a URL
Description
Converts a pathname into a URL starting with file://
.
Usage
## Default S3 method:
toUrl(pathname, safe=TRUE, ...)
Arguments
pathname |
|
safe |
If |
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
Updates the timestamp of a file
Description
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.
Usage
## Default S3 method:
touchFile(pathname, ...)
Arguments
pathname |
|
... |
Not used. |
Value
Returns (invisibly) a vector
of the old timestamps.
Author(s)
Henrik Bengtsson
References
[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
See Also
Internally, Sys.setFileTime
() (iff available) and
file.info
() are utilized.
Examples
# 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))
Unwrap an array, matrix or a vector to an array of more dimensions
Description
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.
Usage
## S3 method for class 'array'
unwrap(x, split=rep("[.]", length(dim(x))), drop=FALSE, ...)
Arguments
x |
|
split |
A |
drop |
If |
... |
Arguments passed to the |
Details
Although not tested thoroughly, unwrap()
should be the inverse
of wrap()
such that identical(unwrap(wrap(x)), x)
holds.
Value
Returns an array
.
Author(s)
Henrik Bengtsson
See Also
*wrap()
.
Examples
## Not run: See ?wrap.array for an example
Updates file progress bar
Description
Updates file progress bar.
Usage
## S3 method for class 'FileProgressBar'
update(object, visual=TRUE, ...)
Arguments
visual |
If |
... |
Not used. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see FileProgressBar
.
Updates progress bar
Description
Updates progress bar.
Usage
## S3 method for class 'ProgressBar'
update(object, visual=TRUE, ...)
Arguments
visual |
If |
... |
Not used. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see ProgressBar
.
Updates the status bar (visually)
Description
Updates the status bar (visually).
Usage
## S3 method for class 'TextStatusBar'
update(object, ...)
Arguments
... |
Not used. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see TextStatusBar
.
Sets the new values of given labels and updates the status bar
Description
Sets the new values of given labels and updates the status bar.
Usage
## S3 method for class 'TextStatusBar'
updateLabels(this, ...)
Arguments
... |
A set of named arguments. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
*setLabels()
.
For more information see TextStatusBar
.
Attaches or loads packages
Description
Attaches or loads packages. If a package is not installed, it (and its dependencies) will be installed from one of the (known) repositories.
Usage
## Default S3 method:
use(pkg="R.utils", version=NULL, how=c("attach", "load"), quietly=TRUE,
warn.conflicts=!quietly, install=getOption("R.utils.use.install",
Sys.getenv("R_R_UTILS_USE_INSTALL", "TRUE")), repos=getOption("use/repos",
c("[[current]]", "[[mainstream]]")), ..., verbose=FALSE)
Arguments
pkg |
|
version |
(optional) Version constraint(s) on requested package(s). |
how |
A |
quietly |
If |
warn.conflicts |
If |
install |
If |
repos |
(optional) A |
... |
Additional named arguments passed to
|
verbose |
If |
Value
Returns a vector
of package_version
() for each package
attached/loaded.
If one of the requested packages/package versions is not available
and could not be installed, an error is thrown.
See Also
library
() and "base::install.packages".
To modify the set of known repositories, set option repos
(see options
()),
which can also be done via setRepositories
.
Examples
## Not run:
use("digest")
use("digest (>= 0.6.3)")
use("digest (>= 0.6.3)", repos=c("CRAN", "R-Forge"))
use("(CRAN|R-Forge)::digest (>= 0.6.3)")
use("BioCsoft::ShortRead")
use("digest, R.rsp (>= 0.9.17)")
## End(Not run)
Sets package repositories
Description
Sets package repositories.
Usage
useRepos(repos=NULL, where=c("before", "after", "replace"), unique=TRUE, fallback=TRUE,
...)
Arguments
repos |
A |
where |
A |
unique |
If |
fallback |
If |
... |
Not used. |
Value
Returns a list
with element 'repos' reflecting options("repos")
as the options where prior to calling this function.
Author(s)
Henrik Bengtsson
See Also
withRepos
().
Validates the compiled lines
Description
Validates the compiled lines
Usage
## S3 method for class 'SmartComments'
validate(this, lines, ...)
Arguments
lines |
|
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see SmartComments
.
Validates the compiled lines
Description
Validates the compiled lines
Usage
## S3 method for class 'VComments'
validate(this, lines, ...)
Arguments
lines |
|
... |
Not used. |
Value
Author(s)
Henrik Bengtsson
See Also
For more information see VComments
.
Identifies TRUE elements in a logical vector
Description
Identifies TRUE elements in a logical vector.
NOTE: which
() should be used instead of this method
unless you are running R (< 2.11.0), for which this method is faster
than which
() for logical
vector
s, especially when there
are no missing values.
Usage
## S3 method for class 'logical'
whichVector(x, na.rm=TRUE, use.names=TRUE, ...)
Arguments
x |
|
na.rm |
If |
use.names |
If |
... |
Not used. |
Value
Returns an integer
vector
of length less or equal to N.
Benchmarking
In R v2.11.0 which
() was made approx. 10 times
faster via a native implementation. Because of this, this
method is of little use and approximately 3 times slower.
However, for earlier version of R, this method is still
significantly faster. For example,
simple comparison on R v2.7.1 on Windows XP, show that
this implementation can be more than twice as fast as
which
(), especially when there are no missing
value (and na.rm=FALSE
) is used.
Author(s)
Henrik Bengtsson
See Also
which
()
Examples
## Not run:
# - - - - - - - - - - - - - - - - - - - - - - - - - -
# Simulate two large named logical vectors,
# one with missing values one without
# - - - - - - - - - - - - - - - - - - - - - - - - - -
N <- 1e6
# Vector #1
x <- sample(c(TRUE, FALSE), size=N, replace=TRUE)
names(x) <- seq_along(x)
# Vector #2
y <- x
y[sample(N, size=0.1*N)] <- NA
# - - - - - - - - - - - - - - - - - - - - - - - - - -
# Validate consistency
# - - - - - - - - - - - - - - - - - - - - - - - - - -
stopifnot(identical(which(x), whichVector(x)))
stopifnot(identical(which(y), whichVector(y)))
# - - - - - - - - - - - - - - - - - - - - - - - - - -
# Benchmarking
# - - - - - - - - - - - - - - - - - - - - - - - - - -
# Number of iterations
K <- 5
t1 <- 0
for (kk in 1:K) {
t1 <- t1 + system.time({ idxs1 <- which(x) })
}
t2 <- 0
for (kk in 1:K) {
t2 <- t2 + system.time({ idxs2 <- whichVector(x, na.rm=FALSE) })
}
cat(sprintf("whichVector(x, na.rm=FALSE)/which(x): %.2f\n", (t2/t1)[3]))
stopifnot(identical(idxs1, idxs2))
t1 <- 0
for (kk in 1:K) {
t1 <- t1 + system.time({ idxs1 <- which(y) })
}
t2 <- 0
for (kk in 1:K) {
t2 <- t2 + system.time({ idxs2 <- whichVector(y) })
}
cat(sprintf("whichVector(y)/which(y): %.2f\n", (t2/t1)[3]))
stopifnot(identical(idxs1, idxs2))
## End(Not run)
Evaluates an expression and captures the code and/or the output
Description
Evaluates an expression and captures the code and/or the output.
Usage
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())
Arguments
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 |
Value
Returns a character
string class 'CapturedEvaluation'.
Author(s)
Henrik Bengtsson
See Also
Internally, eval
() is used to evaluate the expression.
Examples
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
Description
Evaluate an R expression with locale set temporarily.
Usage
withLocale(expr, category, locale, ..., substitute=TRUE, envir=parent.frame())
Arguments
expr |
The R expression to be evaluated. |
category |
A |
locale |
|
... |
Not used. |
substitute |
If |
envir |
The |
Value
Returns the results of the expression evaluated.
Author(s)
Henrik Bengtsson
See Also
Internally, eval
() is used to evaluate the expression.
and Sys.setlocale
() to set locale.
Examples
# 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
Description
Evaluate an R expression with options set temporarily.
Usage
withOptions(expr, ..., args=list(), substitute=TRUE, envir=parent.frame())
Arguments
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 |
Details
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.
Value
Returns the results of the expression evaluated.
Author(s)
Henrik Bengtsson
See Also
Internally, eval
() is used to evaluate the expression.
and options
() to set options.
Examples
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
Description
Evaluate an R expression with repositories set temporarily.
Usage
withRepos(expr, repos="[[mainstream]]", ..., substitute=TRUE, envir=parent.frame())
Arguments
expr |
The R expression to be evaluated. |
repos |
|
... |
Additional arguments passed to |
substitute |
If |
envir |
The |
Value
Returns the results of the expression evaluated.
Author(s)
Henrik Bengtsson
See Also
Internally, eval
() is used to evaluate the expression.
See also options
() and install.packages
.
Examples
## 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
Description
Evaluate an R expression with a temporarily set random set.
Usage
withSeed(expr, seed, ..., substitute=TRUE, envir=parent.frame())
Arguments
expr |
The R expression to be evaluated. |
seed , ... |
Arguments passed to |
substitute |
If |
envir |
The |
Details
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.
Value
Returns the results of the expression evaluated.
Author(s)
Henrik Bengtsson
See Also
Internally, set.seed
() is used to set the random seed.
Examples
# 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
Description
Evaluate an R expression while temporarily diverting output.
Usage
withSink(expr, file, append=FALSE, type=c("output", "message"), substitute=TRUE,
envir=parent.frame())
Arguments
expr |
The R expression to be evaluated. |
file |
A writable |
append |
If |
type |
A |
substitute |
If |
envir |
The |
Details
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.
Value
Returns the results of the expression evaluated.
Author(s)
Henrik Bengtsson
See Also
Internally, sink
() is used to divert any output.
Examples
# 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
Description
Evaluate an R expression and interrupts it if it takes too long.
Usage
withTimeout(expr, substitute=TRUE, envir=parent.frame(), timeout, cpu=timeout,
elapsed=timeout, onTimeout=c("error", "warning", "silent"), ...)
Arguments
expr |
The R expression to be evaluated. |
substitute |
If |
envir |
The |
timeout , cpu , elapsed |
A |
onTimeout |
A |
... |
Not used. |
Details
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.
Value
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.
Known limitation: Not everything can be timed out
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
).
Known limitation: May fail when temporarily switching language
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.
Author(s)
Henrik Bengtsson
References
[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
See Also
Internally, eval
() is used to evaluate the expression and
setTimeLimit
() is used to control for timeout events.
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - -
# 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
Description
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()
.
Usage
## S3 method for class 'array'
wrap(x, map=list(NA), sep=".", ...)
Arguments
x |
|
map |
A |
sep |
A |
... |
Not used. |
Details
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
.
Value
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.
Author(s)
Henrik Bengtsson
See Also
Examples
# 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
Description
Writes binary data to disjoint sections of a connection or a file.
Usage
## Default S3 method:
writeBinFragments(con, object, idxs, size=NA, ...)
Arguments
con |
A |
object |
A |
idxs |
A |
size |
The size of the data type to be read. If |
... |
Additional arguments passed to
|
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
Examples
## Not run: # See example(readBinFragments.connection)
Writes a data.frame to tabular text file
Description
Writes a data.frame to tabular text file with an optional header.
Usage
## 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)
Arguments
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 |
Value
Returns (invisibly) the pathname to the file written
(or the connection
written to).
Author(s)
Henrik Bengtsson
See Also
write.table
.
readTable
().
Writes to each of the Verbose objects
Description
Writes to each of the Verbose objects.
Usage
## S3 method for class 'MultiVerbose'
writeRaw(this, ...)
Arguments
... |
Additional objects to be passed to |
Value
Returns (invisibly) TRUE
.
Author(s)
Henrik Bengtsson
See Also
For more information see MultiVerbose
.
All output methods
Description
All output methods of this class ignores their input arguments and outputs nothing.
Usage
## S3 method for class 'NullVerbose'
writeRaw(...)
Arguments
... |
Ignored. |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see NullVerbose
.
Writes objects if above threshold
Description
Writes objects if above threshold. This method is used by all other methods of this class for output.
Usage
## S3 method for class 'Verbose'
writeRaw(this, ..., sep="", level=this$defaultLevel)
Arguments
... |
Objects to be passed to |
sep |
The default separator |
level |
A |
Value
Returns nothing.
Author(s)
Henrik Bengtsson
See Also
For more information see Verbose
.