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

编程入门 行业动态 更新时间:2024-10-25 19:23:59
本文介绍了将原始字节作为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中的原始字节导入

本文发布于:2023-11-12 07:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580859.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字节   原始

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!