Jan Kislinger Jan Kislinger - 1 month ago 27
R Question

R mongolite: Arrays are loaded from mongo as columns with elements as data.frame

I've been using

jsonlite
and I used to argument
simplifyDataFrame
in
fromJSON()
function. Is there something similar to this in
mongolite
package? For example using
handler
argument? I haven't find enough documentation for this method.

I have records similar to

json <- '{"list": [{"x": 1, "y": "a"},{"x": 2, "y": "b"}],"numeric": 1.2}'


When I load the records using
find()
function it creates data frame with two columns. The first column contains whole data frames as elements.

df <- m$find()
df$list[[1]]
# x y
# 1 1 a
# 2 2 b


What I want is something like

json %>% fromJSON(simplifyDataFrame = F) %>% as.data.frame.list
# list.x list.y list.x.1 list.y.1 numeric
# 1 1 a 1 a 1.2


Is there a solution for that?




Edit:

I know that I can do it in a loop to convert the data frame into a list. Or convert the data into JSON format and then use the
fromJSON(simplifyDataFrame = F)
. Both methods are too slow for the size of data I use. See my previous question.

Answer

Try using m$iterate()$batch() instead of m$find(). It gives the output you expect.

json <- '{"list": [{"x": 1, "y": "a"},{"x": 2, "y": "b"}],"numeric": 1.2}'
json %>% fromJSON(simplifyDataFrame = F) %>% as.data.frame.list
  list.x list.y list.x.1 list.y.1 numeric
1      1      a        2        b     1.2
catch <- m$insert(json)
m$iterate()$batch() %>% as.data.frame.list
  list.x list.y list.x.1 list.y.1 numeric
1      1      a        2        b     1.2