在R中写出大数据帧作为json的最快方法是什么?

Joe*_*ano 6 json r

我需要在R中将大数据帧写为JSON.我正在使用rjson包.下面的方法很慢......

for (i in 1:nrow(df)) {
      write.table(toJSON(df[i,]),"[FILENAME]",
      row.names=FALSE,col.names=FALSE,quote=FALSE,append=TRUE)
    }
Run Code Online (Sandbox Code Playgroud)

所以我尝试了这个:

write.table(toJSON(df),"FILENAME]",
            row.names=FALSE,col.names=FALSE,quote=FALSE,append=TRUE)
Run Code Online (Sandbox Code Playgroud)

由于toJSON()无法处理长度非常长的字符串,因此会出现问题.所以我想一次写出我的数据表块.推荐的方法是什么?如果它涉及split()你可以提供一些伪代码吗?

Mar*_*gan 8

这是一个很大的数据集

big = iris[rep(seq_len(nrow(iris)), 1000),]
Run Code Online (Sandbox Code Playgroud)

for循环toJSON(df[i,])创建一个表示每行的键值对的平面文件,同时toJSON(df)生成列向量; 这些是非常不同的.我们的目标是相当于toJSON(df[i,]),但格式化为单个JSON字符串.

首先biglol每个内部元素命名为列表列表(将因子设置为一个字符,以免将json进一步混淆),所以lol看起来像list(big[1,], big[2,], ...)每个元素上都有名称.

big1 <- Map(function(x, nm) setNames(x, rep(nm, length(x))), big, names(big))
big1$Species <- as.character(big1$Species)
lol <- unname(do.call(Map, c(list, big1)))
Run Code Online (Sandbox Code Playgroud)

然后我们把它变成一个json的向量,使用rjson库splitIndices并由并行库提供(可能是生成拆分的其他方法)

chunks <- 10
json <- sapply(splitIndices(length(lol), chunks), function(idx) toJSON(lol[idx]))
Run Code Online (Sandbox Code Playgroud)

我们几乎可以将json块写入文件,但它们并不完全合法 - 除了最后一个字符串应该以","结尾,但以"]"结尾,除了第一个之外的所有字符串都应该从零开始,但是而是以"["开头.

substring(json[-length(json)], nchar(json)[-length(json)]) = ","
substring(json[-1], 1, 1) = ""
Run Code Online (Sandbox Code Playgroud)

然后准备将这些文件写入文件

fl <- tempfile()
writeLines(json, fl)
Run Code Online (Sandbox Code Playgroud)

结合,当然很多特殊情况下的柱式强制都是未处理的,

library(parallel)  ## just for splitIndices; no parallel processing here...
library(json)
fastJson <- function(df, fl, chunks=10) {
    df1 = Map(function(x, nm) setNames(x, rep(nm, length(x))), df, names(df))
    df1 <- lapply(df1, function(x) {
        if (is(x, "factor")) as.character(x) else x
    })
    lol = unname(do.call(Map, c(list, df1)))

    idx <- splitIndices(length(lol), chunks)
    json <- sapply(idx, function(i) toJSON(lol[i]))
    substring(json[-length(json)], nchar(json)[-length(json)]) <- ","
    substring(json[-1], 1, 1) <- ""
    writeLines(json, fl)
}
Run Code Online (Sandbox Code Playgroud)

> fastJson(big, tempfile())
> system.time(fastJson(big, fl <- tempfile()))
   user  system elapsed 
  2.340   0.008   2.352 
 > system(sprintf("wc %s", fl))
     10      10 14458011 /tmp/RtmpjLEh5h/file3fa75d00a57c
Run Code Online (Sandbox Code Playgroud)

相比之下,只需将子设置为大(无需解析为JSON或写入文件)需要很长时间:

> system.time(for (i in seq_len(nrow(big))) big[i,])
   user  system elapsed 
 57.632   0.088  57.835 
Run Code Online (Sandbox Code Playgroud)

打开此文件以追加,每行一次,与子设置相比不会花费太多时间

> system.time(for (i in seq_len(nrow(big))) { con <- file(fl, "a"); close(con) })
   user  system elapsed 
  2.320   0.580   2.919 
Run Code Online (Sandbox Code Playgroud)