Directories in R Programming Language

Here’s the translation of the Go code to R, with explanations in Markdown format suitable for Hugo:

R has several useful functions for working with directories in the file system.

# Import required libraries
library(fs)

# Helper function to check for errors
check <- function(result) {
  if (inherits(result, "error")) {
    stop(result)
  }
}

# Create a new sub-directory in the current working directory
dir_create("subdir")

# When creating temporary directories, it's good practice to ensure their removal
# We'll use on.exit() for cleanup, which is similar to defer in other languages
on.exit(dir_delete("subdir"))

# Helper function to create a new empty file
createEmptyFile <- function(name) {
  file_create(name)
}

createEmptyFile("subdir/file1")

# We can create a hierarchy of directories, including parents
dir_create("subdir/parent/child")

createEmptyFile("subdir/parent/file2")
createEmptyFile("subdir/parent/file3")
createEmptyFile("subdir/parent/child/file4")

# dir_ls lists directory contents
contents <- dir_ls("subdir/parent")

cat("Listing subdir/parent\n")
for (entry in contents) {
  cat(" ", basename(entry), is_dir(entry), "\n")
}

# setwd lets us change the current working directory, similarly to cd
setwd("subdir/parent/child")

# Now we'll see the contents of subdir/parent/child when listing the current directory
contents <- dir_ls(".")

cat("Listing subdir/parent/child\n")
for (entry in contents) {
  cat(" ", basename(entry), is_dir(entry), "\n")
}

# Change back to where we started
setwd("../../..")

# We can also visit a directory recursively, including all its sub-directories
# dir_walk accepts a callback function to handle every file or directory visited
cat("Visiting subdir\n")
dir_walk("subdir", function(path) {
  cat(" ", path, is_dir(path), "\n")
})

In this R script:

  • We use the fs package, which provides a more consistent and cross-platform set of file system operations.
  • dir_create() is used to create directories, similar to os.Mkdir() and os.MkdirAll() in Go.
  • on.exit() is used for cleanup, which is similar to defer in Go.
  • dir_ls() is used to list directory contents, similar to os.ReadDir() in Go.
  • setwd() is used to change the current working directory, similar to os.Chdir() in Go.
  • dir_walk() is used for recursive directory traversal, similar to filepath.WalkDir() in Go.

To run the script, save it as directories.R and use:

$ Rscript directories.R

The output will be similar to the Go version, listing the contents of the directories and showing the recursive visit of the subdir directory.

R’s file system operations are different from Go’s, but they provide similar functionality. The fs package in R aims to provide a more consistent interface across different operating systems, similar to how Go’s standard library does.