Question

compress files in R without structure of directories

I want to compress some files in R using tar(). My code is quite simple:

f <- "C:/TEMP/tarfile.tar.gz"
files_to_compress <- dir(path=tempdir(), full.names = TRUE)
tar(tarfile = f, files = files_to_compress, compression = "gzip")

The compression works, I get the file tarfile.tar.gz but in the compressed file I get the structure of tempdir(), too.

The file tarfile.tar.gz contains for instance (-> indicating a new folder layer):

C: -> Users -> MyUserName -> AppData -> Local -> Temp -> RTmpM5Dxmp -> files_to_compress

How can I compress files_to_compress without archiving the structure of the directories, too?

 3  53  3
1 Jan 1970

Solution

 3

Change directory to tempdir() first, then use full.names=FALSE, recursive = TRUE in dir(), then change back. For example:

f <- "C:/TEMP/tarfile.tar.gz"
savedir <- setwd(tempdir())
files_to_compress <- dir(full.names = FALSE, recursive = TRUE)
tar(tarfile = f, files = files_to_compress, compression = "gzip")
setwd(savedir)

If this was in a function, you could use on.exit() to make sure the final setwd() happens.

2024-07-22
user2554330

Solution

 2

setwd to tempdir() to have this as a starting point for folders.
A solution without changing the working directory is possible by using archive::archive_write_dir (what has the lines old <- setwd(dir) and on.exit(setwd(old))).

f <- "C:/TEMP/tarfile.tar.gz"
td <- tempdir()              # Create a tempdir
. <- setwd(td)               # Save current working directory

cat("x", file="x.txt")       # Create there a file
dir.create("sub")            # Create a subfolder in tempdir
cat("y", file="./sub/y.txt") #  and create there a file

tar(tarfile = f, compression = "gzip")  # default is to archive all files under the current directory

## Alternatives to the line above:
#files_to_compress <- dir(recursive = TRUE)  # Either this where full.names=TRUE would just add ./ what is the curent folder
#files_to_compress <- dir(path=getwd(), full.names = FALSE, recursive = TRUE) # or that with a given path
#
#tar(tarfile = f, files = files_to_compress, compression = "gzip")  # and create tar

setwd(.)  # Change back to original path


archive::archive_write_dir(f, td)  # Create tar using package archive
2024-07-22
GKi