2

Is it possible run lapply such that the X list argument is used as the second argument to FUN and the first argument to FUN is skipped?

One example is rjson::fromJSON(json_str, file, [other arguments]). I have a list containing several file paths of json files and would like to read each of them, collapsing the results into a list.

Normally, lapply would be ideal for this. However, in order to read from a file, the json_str argument cannot be given, even a null value. This is because fromJSON uses missing to check whether arguments are given. If both file and json_str are given, an error is thrown.

That means that lapply(files, fromJSON, json_str = NULL) will not work. I'm aware that I could work around this by manually making my own function as follows.

result <- lapply(files, function(file) {
  fromJSON(file = file)
})

However, this seems cumbersome and unnecessary. Is there some cleaner way of doing this?

Jon Claus
  • 2,862
  • 4
  • 22
  • 33
  • Unless you can set it separately with `lapply`'s `...` argument, there's really no way around it, especially if you want to indicate an argument much later in the list, like `read.table(text = ...)`. – alistaire Mar 24 '16 at 19:54
  • 1
    Yeah, I don't know of a cleaner way either. Depending on your view of "cleaner" though, you might give the anonymous function a name, say `fromJSONfile`, so it would just be `lapply(files, fromJSONfile)`. – Aaron left Stack Overflow Mar 24 '16 at 20:08
  • You could use `fromJSON` from the package `jsonlite` instead. It have `txt` as first argument which could be a JSON string, URL or file – cderv Mar 24 '16 at 22:57

0 Answers0