3

我试图从数据框中获取 JSON 数组对象,其中每个 JSON 对象都是数据框的子集

> x <- 1:5  
> y <-c('a','b','c','d','e')  
> z <-c(1,1,1,2,2)  
> df <-data.frame(x,y,z)  
> df  
    x y z  
  1 1 a 1  
  2 2 b 1  
  3 3 c 1  
  4 4 d 2  
  5 5 e 2  
> rjson::toJSON(df)  
[1] "{\"x\":[1,2,3,4,5],\"y\":[\"a\",\"b\",\"c\",\"d\",\"e\"],\"z\":[1,1,1,2,2]}"  
> df1 = toJSONArray2(na.omit(df), json = F, names = F)  
> rjson::toJSON(df1)  
[1] "[[1,\"a\",1],[2,\"b\",1],[3,\"c\",1],[4,\"d\",2],[5,\"e\",2]]"  

我需要的输出是

[ [ [1,a],[2,b],[3,c] ],[ [4,d],[5,e] ] ]

下面的方法我能够按预期获得数据帧列表,但无法获得所需的 json 输出。

> x <- foreach(i=1:2) %do% { subset(df,df$z==i)[c(1,2)]}  
> x  
 [[1]]   
   x y  
 1 1 a  
 2 2 b  
 3 3 c  

 [[2]]
   x y
 4 4 d
 5 5 e

找到了解决方案。

> x <- foreach(i=1:2) %do% {
   tmp <-subset(df,df$z==i)[c(1,2)]  
   toJSONArray2(na.omit(tmp), json = F, names = F)  
   }
> rjson::toJSON(x) 

我需要一个没有 toJSONArray2 的实现,这很慢

4

2 回答 2

5

中的toJSONArray2功能rCharts很慢,主要是由于使用RJSONIO. 我正在使用rjson. 这是我到目前为止所拥有的。我orientpandas.

to_json = function(df, orient = "columns", json = T){
  dl = as.list(df)
  dl = switch(orient, 
    columns = dl,
    records = do.call('zip_vectors_', dl),
    values = do.call('zip_vectors_', setNames(dl, NULL))
  )
  if (json){
    dl = rjson::toJSON(dl)
  }
  return(dl)
}

zip_vectors_ = function(..., names = F){
  x = list(...)
  y = lapply(seq_along(x[[1]]), function(i) lapply(x, pluck_(i)))
  if (names) names(y) = seq_along(y)
  return(y)
}

pluck_ = function (element){
  function(x) x[[element]]
}

下面的示例将向您展示to_json20 倍于toJSONArray2,其中大部分是由于使用rjson而不是RJSONIO.

N = 10^3

df <- data.frame(
  x = rpois(N, 10),
  y = sample(LETTERS, N, replace = T),
  z = rpois(N, 5)
)

library(microbenchmark)
autoplot(microbenchmark(
  to_json(df, orient = "values", json = T),
  toJSONArray2(df, names = F),
  times = 5
))

在此处输入图像描述

更新:在仔细阅读您的问题后,我意识到我们可以通过使用dplyrto_json

library(dplyr)

dfl = df %.%
  group_by(z) %.%
  do(function(x){
    to_json(x[-3], orient = 'values', json = F)  
  })
于 2014-03-21T15:49:48.070 回答
2

对于其他试图回答的人,toJSONArray[2]功能在rCharts包中。sapply您的解决方案非常紧凑,但可以使用and进行解环和收紧split

library(rjson)
library(rCharts)

x <- 1:5  
y <- c('a', 'b' ,'c' ,'d' ,'e')  
z <- c(1, 1, 1, 2, 2)  

df <- data.frame(x, y, z) 

toJSON(df)

out <- toJSONArray(sapply(split(df[,1:2], df$z), function(x) {
  toJSONArray2(x, names=FALSE, json = FALSE)
}))

# doing gsub only for SO example output
cat(gsub("\\n", "", out))

## [ [ [ 1,"a" ],[ 2,"b" ],[ 3,"c" ] ],[ [ 4,"d" ],[ 5,"e" ] ] ]

每个请求者,让我们看一下toJSONArray[2]()函数实现rCharts

toJSONArray <- function(obj, json = TRUE, nonames = TRUE){
  list2keyval <- function(l){
    keys = names(l)
    lapply(keys, function(key){
      list(key = key, values = l[[key]])
    })
  }
  obj2list <- function(df){
    l = plyr::alply(df, 1, as.list)
    if(nonames){ names(l) = NULL }
    return(l)
  }
  if (json){
    toJSON(obj2list(obj))
  } else {
    obj2list(obj)
  }
}

toJSONArray2 <- function(obj, json = TRUE, names = TRUE, ...){
  value = lapply(1:nrow(obj), function(i) {
    res <- as.list(obj[i, ])
    if (!names) names(res) <- NULL  # remove names (e.g. {x = 1, y = 2} => {1, 2})
    return(res)
  })
  if (json){
    return(toJSON(value, .withNames = F, ...))
  } else {
    names(value) <- NULL;
    return(value)
  }
}

这些函数已经非常优化,但toJSONArray2基本上是使用其中一个apply函数作为for循环,所以让我们看看 JSON 的自编码是否能更好地满足您的需求。以下内容对您来说可能更快,但您可能需要为您的生产代码进行更多调整(如果您需要取消引用整数):

out <- sapply(split(df[,1:2], df$z), function(x) {
  out.2 <- apply(x, 1, function(y) {
    return(paste0(toJSON(unlist(as.list(y)), .withNames = FALSE), sep=",", collapse=""))
  })
  out.2 <- paste(out.2, sep=", ", collapse=" ")
  out.2 <- gsub(",$", "", out.2)
  return(sprintf("[ %s ], ", out.2))
})

cat(sprintf("[ %s ]", gsub(", $", "", paste(unlist(out), collapse=""))))
## [ [ [ "1", "a" ], [ "2", "b" ], [ "3", "c" ] ], [ [ "4", "d" ], [ "5", "e" ] ] ]

它与实现共享一些相似的模式,rCharts但完全专注于将因子拆分数据帧的行拍成您需要的格式。

于 2014-03-20T10:51:20.793 回答