How to use context
usage.Rmd
library(context)
#>
#> Attaching package: 'context'
#> The following objects are masked from 'package:base':
#>
#> open, with
Basic usage
Usage will be familiar to anyone that used Pythons
with-as
context manager. For example, to iterate file line
by line, run a function on a line, then do something with the
result:
# Add numbers 1, 2, 3, 4, 5 to a file
set.seed(42)
temp_file <- tempfile()
writeLines(as.character(1:5), temp_file)
numbers <- c()
with(open(temp_file) %as% f, {
while (read_line(f) %as% line) {
numbers <- c(numbers, as.integer(line))
}
})
cat("Sum of the numbers is: ", sum(numbers), "\n")
#> Sum of the numbers is: 15
file.remove(temp_file) |> invisible()
In addition to the with
context creation,
%as%
can be used to store the value of the expression on
its left side to the variable name on its right side. When used in this
manner, this type of assignment returns FALSE
only when the
end of the is reached, that is when the length of the return value is
zero. This is useful when iterating through files in chunks; for example
line by line or block-by-block as is the case for example with
ShortRead::FastqStreamer()
.