Skip to content

Commit 2a50458

Browse files
authored
Merge pull request #11 from KWB-R/dev
Add some new functions (moved from other packages)
2 parents dcbe1b7 + 049d5de commit 2a50458

28 files changed

+407
-51
lines changed

DESCRIPTION

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
Package: kwb.utils
22
Title: General Utility Functions Developed at KWB
3-
Version: 0.4.4
3+
Version: 0.5.0
44
Authors@R:
55
c(person(given = "Hauke",
66
family = "Sonnenberg",

NAMESPACE

+2
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ export(arglist)
2020
export(asColumnList)
2121
export(asNoFactorDataFrame)
2222
export(asRowList)
23+
export(assertFinalSlash)
2324
export(assertRowsAndColumns)
2425
export(assignAll)
2526
export(assignArgumentDefaults)
@@ -237,6 +238,7 @@ export(toLookupClass)
237238
export(toLookupList)
238239
export(toLookupTable)
239240
export(toNamedList)
241+
export(toPdf)
240242
export(toPositiveIndices)
241243
export(underscoreToPercent)
242244
export(unmerge)

NEWS.md

+13
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
1+
# [kwb.utils 0.5.0](https://github.com/KWB-R/kwb.utils/releases/tag/v0.5.0) <small>2019-12-17</small>
2+
3+
* new: toPdf()
4+
* new: assertFinalSlash()
5+
* new private functions:
6+
+ cache_and_return()
7+
+ clear_cache()
8+
+ get_cached()
9+
+ get_cached_file()
10+
+ run_cached()
11+
+ objectToText()
12+
+ textToObject()
13+
114
# [kwb.utils 0.4.4](https://github.com/KWB-R/kwb.utils/releases/tag/v0.4.4) <small>2019-08-10</small>
215

316
* improved documentation (deploy docu also from "dev" branch, include NEWS.md)

R/array.R

+3-3
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ mergeNamedArrays <- function(x, check_dim = TRUE)
3535
}
3636

3737
# Stop if not all dimensions are of the same length
38-
stopifnot(kwb.utils::allAreEqual(sapply(dimnames_list, length)))
38+
stopifnot(allAreEqual(sapply(dimnames_list, length)))
3939

4040
# Merge the dimension lists
4141
dim_names <- lapply(seq_along(dimnames_list[[1]]), function(i) {
@@ -71,7 +71,7 @@ mergeNamedArrays <- function(x, check_dim = TRUE)
7171
{
7272
# Define helper functions
7373
get_lengths <- function(x) sapply(x, length)
74-
print_with_caption <- function(x) kwb.utils::printIf(TRUE, x)
74+
print_with_caption <- function(x) printIf(TRUE, x)
7575

7676
dim_a <- get_lengths(dimnames_a)
7777
dim_b <- get_lengths(dimnames_b)
@@ -94,7 +94,7 @@ mergeNamedArrays <- function(x, check_dim = TRUE)
9494

9595
stop(
9696
"There are labels in a that are not in b in dimension ", i, ", e.g.:\n",
97-
kwb.utils::stringList(utils::head(dimnames_a[[i]][! a_in_b]))
97+
stringList(utils::head(dimnames_a[[i]][! a_in_b]))
9898
)
9999
}
100100
}

R/assertFinalSlash.R

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# assertFinalSlash -------------------------------------------------------------
2+
3+
#' Make Sure that Strings End With Slash
4+
#'
5+
#' @param x vector of character
6+
#' @param method integer value specifying the implementation method. \code{1}
7+
#' (default): Find strings without ending slash and append slash to these
8+
#' strings. \code{2}: Remove one or more slashes at the end and append slash
9+
#' to all strings. \code{3}: Append slash to all strings and replace multiple
10+
#' occurrences of slash at the end with one slash. Method 1 is the fastest but
11+
#' does not replace multiple trailing slashes with only one trailing slash
12+
#' (see examples).
13+
#' @export
14+
#' @examples
15+
#' assertFinalSlash(c("a", "b", "c"))
16+
#' assertFinalSlash(c("a/", "b/", "c/"))
17+
#' assertFinalSlash(c("a//", "b", "c/"))
18+
#'
19+
#' # Use method 2 or 3 to replace multiple slashes with one slash
20+
#' assertFinalSlash(c("a//", "b", "c/"), method = 2)
21+
#' assertFinalSlash(c("a//", "b", "c/"), method = 3)
22+
assertFinalSlash <- function(x, method = 1L)
23+
{
24+
stopifnot(method %in% 1:3)
25+
26+
if (method == 1L) {
27+
# 1. Find strings without ending slash
28+
# 2. Append slash at the end to these strings
29+
endpos <- nchar(x)
30+
no_slash <- substr(x, endpos, endpos) != "/"
31+
`[<-`(x, no_slash, paste0(x[no_slash], "/"))
32+
33+
} else if (method == 2L) {
34+
35+
# 1. Remove one or more slashes at the end
36+
# 2. Append slash at the end
37+
paste0(gsub("/+$", "", x), "/")
38+
39+
} else if (method == 3L) {
40+
41+
# 1. Append slash at the end
42+
# 2. Replace multiple occurrences of slash at the end with one slash
43+
gsub("/+$", "/", paste0(x, "/"))
44+
}
45+
}

R/cache.R

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# cache_and_return -------------------------------------------------------------
2+
cache_and_return <- function(x, name = deparse(substitute(x)))
3+
{
4+
save(x, file = get_cached_file(name))
5+
x
6+
}
7+
8+
# clear_cache ------------------------------------------------------------------
9+
clear_cache <- function()
10+
{
11+
files <- get_cached_file()
12+
13+
if (length(files)) {
14+
15+
catAndRun(messageText = sprintf(
16+
"Clearing %d files from cache:\n %s",
17+
length(files), stringList(basename(files))
18+
), expr = {
19+
unlink(files)
20+
})
21+
22+
} else {
23+
24+
cat("No cached files to clear.\n")
25+
}
26+
}
27+
28+
# get_cached -------------------------------------------------------------------
29+
get_cached <- function(name)
30+
{
31+
if (file.exists(file <- get_cached_file(name))) {
32+
loadObject(file, "x")
33+
} else {
34+
NULL
35+
}
36+
}
37+
38+
# get_cached_file --------------------------------------------------------------
39+
get_cached_file <- function(name = "")
40+
{
41+
cache_dir <- file.path(tempdir(), "cache")
42+
43+
createDirectory(cache_dir, dbg = FALSE)
44+
45+
if (name == "") {
46+
return(dir(cache_dir, "\\.RData", full.names = TRUE))
47+
}
48+
49+
file.path(cache_dir, paste0(name, ".RData"))
50+
}
51+
52+
# run_cached -------------------------------------------------------------------
53+
run_cached <- function(name, expr)
54+
{
55+
if (! is.null(object <- get_cached(name))) {
56+
return(object)
57+
}
58+
59+
object <- eval(expr, envir = -1)
60+
61+
cache_and_return(object, name = name)
62+
63+
object
64+
}

R/column.R

+5-4
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,9 @@ checkForMissingColumns <- function(
101101
#'
102102
columnToDate <- function(df, column, dbg = TRUE)
103103
{
104-
df[[column]] <- kwb.utils::catAndRun(
104+
df[[column]] <- catAndRun(
105105
sprintf("Converting column '%s' to Date", column), dbg = dbg,
106-
as.Date(as.character(kwb.utils::selectColumns(df, column)))
106+
as.Date(as.character(selectColumns(df, column)))
107107
)
108108

109109
df
@@ -250,6 +250,7 @@ hsDelEmptyCols <- function(
250250
#'
251251
hsRenameColumns <- function(dframe, renames)
252252
{
253+
warningDeprecated("hsRenameColumns", "renameColumns")
253254
renameColumns(x = dframe, renamings = renames)
254255
}
255256

@@ -584,9 +585,9 @@ removeEmptyColumns <- function(
584585
#'
585586
renameAndSelect <- function(data, renames, columns = unlist(renames))
586587
{
587-
data <- kwb.utils::hsRenameColumns(data, renames)
588+
data <- renameColumns(data, renames)
588589

589-
kwb.utils::selectColumns(data, columns, drop = FALSE)
590+
selectColumns(data, columns, drop = FALSE)
590591
}
591592

592593
# renameColumns ----------------------------------------------------------------

R/csv.R

+5-5
Original file line numberDiff line numberDiff line change
@@ -99,16 +99,16 @@ convertCsvFile <- function(
9999
args <- c(args_read, arguments[argnames])
100100

101101
# Read data from file_in
102-
kwb.utils::catIf(dbg, sprintf("Reading from '%s' ... ", file_in))
102+
catIf(dbg, sprintf("Reading from '%s' ... ", file_in))
103103

104104
x <- do.call(utils::read.table, args)
105105

106-
kwb.utils::catIf(dbg, "ok.\n")
106+
catIf(dbg, "ok.\n")
107107

108108
# If no target file name is given, create one
109109
if (is.null(file_out)) {
110110

111-
extension <- kwb.utils::fileExtension(file_in)
111+
extension <- fileExtension(file_in)
112112

113113
pattern <- paste0("\\.", extension, "$")
114114

@@ -133,11 +133,11 @@ convertCsvFile <- function(
133133
args <- c(args_write, arguments[argnames])
134134

135135
# Write data to file_out
136-
kwb.utils::catIf(dbg, sprintf("Writing to '%s' ... ", file_out))
136+
catIf(dbg, sprintf("Writing to '%s' ... ", file_out))
137137

138138
do.call(utils::write.table, args)
139139

140-
kwb.utils::catIf(dbg, "ok.\n")
140+
catIf(dbg, "ok.\n")
141141

142142
file_out
143143
}

R/dataFrame.R

+9-7
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,8 @@ compareDataFrames <- function(
139139

140140
# Are the data frames identical after removing all attributes?
141141
result$identicalExceptAttributes <- identical(
142-
kwb.utils::removeAttributes(x),
143-
kwb.utils::removeAttributes(y)
142+
removeAttributes(x),
143+
removeAttributes(y)
144144
)
145145

146146
# Do the data frames have the same number of rows?
@@ -170,8 +170,8 @@ compareDataFrames <- function(
170170
c(
171171
identical = identical(x[[column]], y[[column]]),
172172
identicalExceptAttributes = identical(
173-
kwb.utils::removeAttributes(x[[column]]),
174-
kwb.utils::removeAttributes(y[[column]])
173+
removeAttributes(x[[column]]),
174+
removeAttributes(y[[column]])
175175
),
176176
equalValues = all(x[[column]] == y[[column]])
177177
)
@@ -606,10 +606,12 @@ safeRowBindOfListElements <- function(x, elementName)
606606

607607
# splitIntoFixSizedBlocks ------------------------------------------------------
608608

609-
#' Split into blocks of same size
609+
#' Split into Blocks of Same Size
610610
#'
611-
#' Split a data frame or matrix into blocks of the same size (= data frames of
612-
#' matrices with the same number of rows)
611+
#' Split a data frame or a matrix into blocks of the same size, i.e. data frames
612+
#' or matrices with the same number of rows (except the last one that is shorter
613+
#' unless the total number of rows is a multiple of the number of rows per
614+
#' block).
613615
#'
614616
#' @param data data frame or matrix
615617
#' @param blocksize number of rows in each block into which \code{data} is split

R/dictionary.R

+3-3
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ writeDictionary <- function(dictionary, file)
2525
header_lines <- c(
2626
header_lines,
2727
"This file has been generated using kwb.utils::writeDictionary()",
28-
sprintf("on %s by user %s", Sys.Date(), kwb.utils::user())
28+
sprintf("on %s by user %s", Sys.Date(), user())
2929
)
3030

3131
header_lines <- paste("#", header_lines)
@@ -55,9 +55,9 @@ readDictionaries <- function(folder, pattern = "^dictionary_(.*)[.]txt$")
5555
{
5656
files <- dir(folder, pattern, full.names = TRUE)
5757

58-
dictionaries <- lapply(files, kwb.utils::readDictionary, sorted = FALSE)
58+
dictionaries <- lapply(files, readDictionary, sorted = FALSE)
5959

60-
config_names <- kwb.utils::subExpressionMatches(pattern, basename(files))
60+
config_names <- subExpressionMatches(pattern, basename(files))
6161

6262
structure(dictionaries, names = sapply(config_names, "[[", 1))
6363
}

R/encode_decode.R

+3-3
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ encode <- function(x, level = 1, chars = printable_chars(level))
2222
{
2323
x <- as.factor(x)
2424

25-
m <- kwb.utils::intToNumeralSystem(seq_along(levels(x)), base = length(chars))
25+
m <- intToNumeralSystem(seq_along(levels(x)), base = length(chars))
2626

2727
result <- matrix(
2828
chars[m + 1],
@@ -31,7 +31,7 @@ encode <- function(x, level = 1, chars = printable_chars(level))
3131
dimnames = dimnames(m)
3232
)
3333

34-
result <- do.call(paste0, kwb.utils::asColumnList(result))
34+
result <- do.call(paste0, asColumnList(result))
3535

3636
encoded_indices <- gsub(pattern = "^0+", replacement = "", result)
3737

@@ -97,5 +97,5 @@ printable_chars <- function(level = 1)
9797
#'
9898
decode <- function(x)
9999
{
100-
unname(kwb.utils::getAttribute(x, "codes")[x])
100+
unname(getAttribute(x, "codes")[x])
101101
}

R/io.R

+1-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ catLines <- function(x)
8686
#'
8787
catNewLineIf <- function(condition)
8888
{
89-
kwb.utils::catIf(condition, "\n")
89+
catIf(condition, "\n")
9090

9191
invisible(condition)
9292
}

R/lookup.R

+3-3
Original file line numberDiff line numberDiff line change
@@ -39,19 +39,19 @@ toLookupClass <- function(
3939
keys, values, class = c("data.frame.1", "data.frame.2", "list", "vector")[1]
4040
)
4141
{
42-
classes <- kwb.utils::toNamedList(
42+
classes <- toNamedList(
4343
c("data.frame.1", "data.frame.2", "list", "vector")
4444
)
4545

4646
if (class %in% c(classes$data.frame.1, classes$data.frame.2)) {
4747

48-
kwb.utils::toLookupTable(
48+
toLookupTable(
4949
keys, values, as.twoColumnTable = (class == classes$data.frame.2)
5050
)
5151

5252
} else if (class == classes$list) {
5353

54-
kwb.utils::toLookupList(keys, values)
54+
toLookupList(keys, values)
5555

5656
} else if (class == classes$vector) {
5757

0 commit comments

Comments
 (0)