R解码用base64编码的列

R decode a column encoded with base64

在 R 中,我有一个数据框,其列 "content" 用 base64 编码。我可以解码第 355 行中的 "content" 的单个条目,如下所示;

library(base64enc)
rawToChar(base64decode(df[355,"content"]))

当我尝试使用

解码时
rawToChar(base64decode(df$content))

我收到错误 "embedded nul in string"。我怎样才能解码整列?

编辑:我使用了一个循环,它看起来不错,但我认为这不是一个优雅的解决方案。

comments.decoded <- data.frame(comments=character(),
                               stringsAsFactors=FALSE)

for(i in 1:nrow(df))
{
    clean.row <- iconv(rawToChar(base64decode(df[i,"content"])), "latin1", "UTF-8")
    clean.row <- data.frame(trimws(clean.row), stringsAsFactors=FALSE)
    comments.decoded <- rbind(comments.decoded, clean.row)
}

comments.decoded

quote R 基金会的一位主席:

R hasn't supported embedded nulls in strings for quite a long time [...] If you want bytes that contain nulls, don't store them in character variables, store them in raw vectors

你可以试试

sapply(df$content, function(x) { 
  res <- try(rawToChar(base64decode(x) )) 
  if (!inherits(res, "try-error")) res else NA  
})

对于包含 nul 的字符串,这会产生 NA