r - 将原始字节作为 R 中的原始字节导入

标签 r postgresql encoding

我已经从数据库中将一个字符串导入到 R 中。数据库列类型是 BYTEA (Postgres)。为了让我按预期使用它,它应该是 raw 类型。相反,它是 character 类型。我想在以下意义上将其转换为原始数据:

字符串表示为

\x1f8b080000000000

如果我使用charToRaw,它会被转换成数组

5c 78 31 66 38 62 30 38 

相反,我需要它是数组

1f 8b 08 00 00 00 00 00

我如何实现这一目标。

编辑 #1 回复 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

最佳答案

这适用于将您所描述类型的单个字符串转换为原始向量。

## 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

关于r - 将原始字节作为 R 中的原始字节导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36343513/

相关文章:

sql - 每月累计总计和 Postgresql

java - 纯 HTTP GET 和 POST 通信的安全数据序列化

haskell - Hasql:编码和类型

php - 字符编码 : Changing file from MacRoman to UTF-8 breaks string

r - 将分组数据框导出到 excel 并为每个组创建一个单独的选项卡(R,dplyr)

注册 R6 类的 S4 等效项,同时保留继承

r - geom_boxplot,如何根据组专门为异常值着色并保持黑色?

r - 如何将 Theil-Sen 方法与 geom_smooth 一起使用

postgresql - 用户和角色有什么区别?

python - Docker 中 python :2. 7-alpine 的 psycopg2 安装