将原始字节作为R中的原始字节导入 [英] Import raw bytes as raw bytes in R

查看:104
本文介绍了将原始字节作为R中的原始字节导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已从数据库将字符串导入R。 db列类型为 BYTEA (Postgres)。为了使我能够按预期使用它,它应该是 raw 类型。相反,它的类型为 character 。我想按以下方式将其转换为raw:

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:

字符串表示形式为

\x1f8b080000000000

如果我使用 charToRaw ,它将转换为数组

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

我如何做到这一点。

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


推荐答案

这可以将您描述的类型的单个字符串转换为原始向量。

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

这篇关于将原始字节作为R中的原始字节导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆