3

我正在用 jsonlite 加载这个 JSON 数据

<snip>  
"rawData": {
    "fortune": {}, 
    "plaintext": {}, 
    "db": {}, 
    "update": {
      "duda": [
        {
          "latencyAvg": "201.40us", 
          "latencyMax": "727.00us", 
          "latencyStdev": "54.85us", 
          "totalRequests": 561810, 
          "startTime": 1413890149, 
          "endTime": 1413890164
        }
      ]
      }, 
    "json": {
      "duda": [
        {
          "latencyAvg": "201.40us", 
          "latencyMax": "727.00us", 
          "latencyStdev": "54.85us", 
          "totalRequests": 561810, 
          "startTime": 1413890149, 
          "endTime": 1413890164
        }
      ]
    }, 
    "query": {}
  }

这导致具有嵌套数据框的结构

data <- structure(list(fortune = structure(list(), .Names = character(0)), 
    plaintext = structure(list(), .Names = character(0)), db = structure(list(), .Names = character(0)), 
    update = structure(list(duda = structure(list(latencyAvg = "201.40us", 
        latencyMax = "727.00us", latencyStdev = "54.85us", totalRequests = 561810L, 
        startTime = 1413890149L, endTime = 1413890164L), .Names = c("latencyAvg", 
    "latencyMax", "latencyStdev", "totalRequests", "startTime", 
    "endTime"), class = "data.frame", row.names = 1L)), .Names = "duda"), 
    json = structure(list(duda = structure(list(latencyAvg = "201.40us", 
        latencyMax = "727.00us", latencyStdev = "54.85us", totalRequests = 561810L, 
        startTime = 1413890149L, endTime = 1413890164L), .Names = c("latencyAvg", 
    "latencyMax", "latencyStdev", "totalRequests", "startTime", 
    "endTime"), class = "data.frame", row.names = 1L)), .Names = "duda"), 
    query = structure(list(), .Names = character(0))), .Names = c("fortune", 
"plaintext", "db", "update", "json", "query"))

我想创建一个如下所示的单个 data.frame:

Type   | Name | latencyAvg | latencyMax | latencyStdev | totalRequests | startTime | endTime
json   | duda | 201.40us   | <etc..>
update | duda | 201.40us   | <etc..>

通过展平嵌套的数据框。我正在弄清楚如何通过删除我想要的项目并使用 rbind/cbind 将它们移动到新的数据框来手动执行此操作,但是有没有一种简单的方法来执行这种类型的递归展平?

4

3 回答 3

2

假设该对象被命名为“数据”的不幸名称:

newdat <- rbind.data.frame( Type= c(rep("json",   nrow(data$json$duda)), 
                                    rep("update", nrow(data$update$duda)) ), 
                            rbind( data$json$duda, data$update$duda) )
于 2014-10-21T23:55:55.147 回答
2

使用flatten功能。它获取一个数据框并返回一个平面数据框。如果您需要从源数据框中排除某些列,请使用df[[-i]]排除列i

于 2018-06-05T19:41:29.237 回答
1

另一个单线

do.call(rbind, lapply(data[c('json', 'update')], '[[', 'duda'))
于 2014-10-22T15:41:04.283 回答