【问题标题】:R Read Json into a data.frameR将Json读入data.frame
【发布时间】:2018-01-11 03:52:04
【问题描述】:

我正在尝试将json 文件加载到R 中的data.frame。但是我的数据中有一些 list() 为空。

这是我的json 数据:

json_file1 <- jsonlite::fromJSON('{"txtId":"20180101","data":{"user":[{"id":"123","phone":"00001","realName":"Eric","addr":{},"source":{},"registerDate":{},"type":0,"remain":{}}],"score":[]}}')
json_file2 <- jsonlite::fromJSON('{"txtId":"20180102","data":{"user":[{"id":"456","phone":"00002","realName":"Amy","addr":{},"source":{},"registerDate":{},"type":0,"remain":100}],"score":[]}}')
json_file = list(json_file1, json_file2)
zt.detail = lapply(json_file, function(y){
  if(!is.null(y$data$user)) data.frame(y$data$user, stringsAsFactors = F)
  })

当我rbind zt.detail 时,我收到错误:

# > dat_callrecord = data.table::rbindlist(zt.detail, fill = T)
# Error in data.table::rbindlist(zt.detail, fill = T) : 
#   Column 4 of item 1 is length 0, inconsistent with first column of that item which is length 1. rbind/rbindlist doesn't recycle as it already expects each item to be a uniform list, data.frame or data.table
# > str(zt.detail[[1]])
# 'data.frame': 1 obs. of  9 variables:
#   $ id          : chr "123"
# $ phone       : chr "00001"
# $ realName    : chr "Eric"
# $ addr        :'data.frame':  1 obs. of  0 variables
# $ source      :'data.frame':  1 obs. of  0 variables
# $ registerDate:'data.frame':  1 obs. of  0 variables
# $ type        : int 0
# $ remain      :'data.frame':  1 obs. of  0 variables

错误是因为我的数据结构包含 data.frame 的 1 个观察值但 0 个变量。所以我想将那些list() 转移到NA 之前并得到以下结果:

> dat_callrecord
id phone realName type remain addr source registerDate
123 00001  Eric    0    NA     NA     NA    NA      
456 00002  Amy     0    100    NA     NA    NA

【问题讨论】:

    标签: json r dataframe rbind


    【解决方案1】:

    我们可以循环遍历list,如果有data.frame,将其替换为NA,然后执行rbindlist

    data.table::rbindlist(lapply(zt.detail, function(x) {
           x[] <- lapply(x, function(y) if(is.data.frame(y)) NA else y)
          x}))
    #    id phone realName addr source registerDate type remain
    #1: 123 00001     Eric   NA     NA           NA    0     NA
    #2: 456 00002      Amy   NA     NA           NA    0    100
    

    【讨论】:

      猜你喜欢
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多