import ndjson into R skip first n lines

217 views Asked by At

How to read a big ndjson (20GB) file by chunk into R?

I have a big data file that I want to read 1M rows at a time.

currently, I'm using below code to load data into R.

jsonlite::stream_in(
  file(fileName)
)

But I don't need to load all data together. how can I split this file to chunk to load faster?

1

There are 1 answers

2
hrbrmstr On BEST ANSWER

If you don't want to level-up and use Drill, this will work on any system zcat (or gzcat) and sed live:

stream_in_range <- function(infile, start, stop, cat_kind = c("gzcat", "zcat")) {

  infile <- path.expand(infile)
  stopifnot(file.exists(infile))

  gzip <- (tools::file_ext(infile) == "gz")
  if (gzip) cat_kind <- match.arg(cat_kind, c("gzcat", "zcat"))

  start <- as.numeric(start[1])
  stop <- as.numeric(stop[1])

  sed_arg <- sprintf("%s,%sp;", start, stop, (stop+1))

  sed_command <- sprintf("sed -n '%s'", sed_arg)

  if (gzip) {
    command <- sprintf("%s %s | %s ", cat_kind, infile, sed_command)
  } else {
    command <- sprintf("%s %s", sed_command, infile)
  }

  ndjson::flatten(system(command, intern=TRUE), "tbl")

}

stream_in_range("a-big-compressed-ndjson-file.json.gz", 100, 200)

stream_in_range("a-big-uncompressed-nsjdon-file.json", 1, 10)

Choose and/or add a different cat_kind for whatever works for you.