I have imported a string into R from a database. The db column type is BYTEA
(Postgres). In order for me to use it as intended, it should be of type raw
. Instead, it is of type character
. I want to convert it to raw in the following sense:
The string representation is
\x1f8b080000000000
If I use charToRaw
, it is converted to the array
5c 78 31 66 38 62 30 38
Instead I need it to be the array
1f 8b 08 00 00 00 00 00
How do I acheive this.
Edit #1 Reply to Chris
library(RPostgreSQL)
conn <- dbConnect(dbDriver("PostgreSQL"), dbname = "somename",
host = "1.2.3.4", port = 5432,
user = "someuser", password = pw)
some_value <- dbGetQuery(conn, "select value from schema.key_value where key like '%somekey%' limit 1")
some_value$value
# [1] "\\x1f8b080000000000000
This works for converting a single character string of the type you've described to a vector of raws.
## The string I think you're talking about
dat <- "\\x1f8b080000000000"
cat(dat, "\n")
## \x1f8b080000000000
## A function to convert one string to an array of raw
f <- function(x) {
## Break into two-character segments
x <- strsplit(x, "(?<=.{2})", perl=TRUE)[[1]]
## Remove the first element, "\\x"
x <- x[-1]
## Complete the conversion
as.raw(as.hexmode(x))
}
## Check that it works
f(dat)
## [1] 1f 8b 08 00 00 00 00 00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With