Base64 Encoding in R Programming Language

R provides support for base64 encoding/decoding through the base64enc package.

# Install and load the base64enc package
install.packages("base64enc")
library(base64enc)

# Here's the string we'll encode/decode
data <- "abc123!?$*&()'-=@~"

# Encoding using standard base64
sEnc <- base64encode(charToRaw(data))
cat("Standard encoded:", sEnc, "\n")

# Decoding
sDec <- rawToChar(base64decode(sEnc))
cat("Decoded:", sDec, "\n\n")

# Encoding using URL-safe base64
uEnc <- base64encode(charToRaw(data), urlsafe = TRUE)
cat("URL-safe encoded:", uEnc, "\n")

# Decoding URL-safe
uDec <- rawToChar(base64decode(uEnc))
cat("Decoded:", uDec, "\n")

In this R script:

  1. We first install and load the base64enc package, which provides base64 encoding and decoding functions.

  2. We define our input string data.

  3. For standard base64 encoding:

    • We use base64encode() function to encode the string.
    • We first convert the string to raw bytes using charToRaw().
    • To decode, we use base64decode() and then convert the raw bytes back to a character string with rawToChar().
  4. For URL-safe base64 encoding:

    • We use the same base64encode() function, but with the urlsafe = TRUE parameter.
    • Decoding is done in the same way as for standard encoding.

When you run this script, you should see output similar to this:

Standard encoded: YWJjMTIzIT8kKiYoKSctPUB+ 
Decoded: abc123!?$*&()'-=@~

URL-safe encoded: YWJjMTIzIT8kKiYoKSctPUB-
Decoded: abc123!?$*&()'-=@~

Note that in R, the URL-safe encoding replaces + with - and / with _, which is why you see a - at the end of the URL-safe encoded string instead of a +.

R’s base64 functions handle the conversion between different data types (character strings and raw bytes) automatically, making the process straightforward.