Skip to contents

Compress or decompress using gzip, bzip2, or xz compression.

Usage

compress(
  file,
  ext = c("gz", "bz2", "xz", "zip"),
  remove = FALSE,
  overwrite = FALSE
)

decompress(file, remove = FALSE, overwrite = FALSE)

Arguments

file

character(1). File path.

ext

character(1). Compression file format extension. Uses match.arg() internally and defaults to the first argument in the character vector.

Supported formats:

  • gz: gzip compression; calls gzfile() internally.

  • bz: bzip2 (lzma) compression; calls bzfile() internally.

  • xz: xz compression; calls xzfile() internally.

  • zip: zip compression; calls zip() or unzip() internally.

remove

logical(1). Remove the input file once the output file is fully created and the connection is closed.

overwrite

logical(1). Overwrite existing file on disk.

Value

Invisible character(1). File path.

Details

For ZIP files, refer to zip and unzip in the utils package.

Note

Updated 2023-09-21.

Examples

## Create an example text file.
text <- c("hello", "world")
file <- "test.txt"
writeLines(text = text, con = file)
readLines(con = file)
#> [1] "hello" "world"

## Apply gzip compression.
gzfile <- compress(
    file = file,
    ext = "gz",
    remove = TRUE,
    overwrite = TRUE
)
print(gzfile)
#> [1] "/Users/mike/git/monorepo/r-packages/AcidBase/docs/reference/test.txt.gz"
#> attr(,"bytes")
#> [1] 12
readLines(con = gzfile)
#> [1] "hello" "world"
## When `remove = TRUE`, the original input file will be removed.
file.exists(file)
#> [1] FALSE

## Decompress the gzipped file.
file <- decompress(
    file = gzfile,
    remove = TRUE,
    overwrite = TRUE
)
print(file)
#> [1] "/Users/mike/git/monorepo/r-packages/AcidBase/docs/reference/test.txt"
#> attr(,"bytes")
#> [1] 12

## Clean up.
unlink2(file)