微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

字符串表示是

\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

解决方法

这适用于将您描述的类型的单个字符串转换为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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐