Writing Files in R Programming Language
Here’s the translation of the Go code to R, formatted in Markdown suitable for Hugo:
Writing files in R follows similar patterns to the ones we saw earlier for reading.
# To start, here's how to dump a string (or just bytes) into a file.
d1 <- "hello\nR\n"
writeLines(d1, "/tmp/dat1")
# For more granular writes, open a file for writing.
f <- file("/tmp/dat2", "w")
# It's good practice to close the file connection when we're done
on.exit(close(f))
# You can write strings as you'd expect.
d2 <- "some\n"
writeLines(d2, f)
cat("wrote", nchar(d2), "bytes\n")
# A writeLines is also available for writing multiple lines at once.
n3 <- writeLines("writes\n", f)
cat("wrote", nchar("writes\n"), "bytes\n")
# flush writes to ensure they're written to the file
flush(f)
# R doesn't have a direct equivalent to bufio, but we can use
# connection objects for buffered writing
w <- file("/tmp/dat2", "a") # Open in append mode
on.exit(close(w), add = TRUE)
n4 <- writeLines("buffered\n", w)
cat("wrote", nchar("buffered\n"), "bytes\n")
# Use flush to ensure all buffered operations have been applied
flush(w)
Try running the file-writing code.
$ Rscript writing-files.R
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes
Then check the contents of the written files.
$ cat /tmp/dat1
hello
R
$ cat /tmp/dat2
some
writes
buffered
Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin
and stdout
streams.
Note: In R, error handling is typically done using tryCatch()
instead of a separate error checking function. Also, R doesn’t have a direct equivalent to os.WriteFile()
or os.Create()
, so we use writeLines()
and file()
functions instead. The bufio
concept is approximated using R’s connection objects, which provide buffered I/O by default.