我已将数据库中的字符串导入到 R 中。数据库列类型是BYTEA
(Postgres)。为了让我按预期使用它,它应该是类型raw
。相反,它是类型character
。我想在以下意义上将其转换为原始数据:
字符串表示形式是
\x1f8b080000000000
如果我使用charToRaw
,它被转换为数组
5c 78 31 66 38 62 30 38
相反,我需要它是数组
1f 8b 08 00 00 00 00 00
我该如何实现这一目标。
Edit #1回复克里斯
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
这适用于将您描述的类型的单个字符串转换为原始向量。
## 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)