【问题标题】:R: JSON Package - importing data & missing values / nullR:JSON 包 - 导入数据和缺失值 / null
【发布时间】:2013-12-13 07:07:52
【问题描述】:

我正在使用 JSON 包读取数据。

数据基本上有以下格式:

{"a":1,"b":2,"c":3}
{"a": null,"b":2,"c":3}

我在R中存储数据如下:

DAT<-data.table(read.csv("D:/file.csv"))
i<-1
#create unified variable names
while (i<=nrow(DAT)) {
OUT[[i]]<-fromJSON(as.character(DAT[i]$results))
vnames<-c(vnames,names(OUT[[i]]))
i<-i+1
}
#create the corresponding content 
content <- NULL
Applicant <- NULL
  i<-1
  while (i<=nrow(DAT)) {
    temp<-fromJSON(as.character(DAT[i]$results))
    laenge <- length(fromJSON(as.character(DAT[i]$results)))
    for(j in 1:laenge)
    {
      content_new <- as.character(temp[[j]])
      content <- c(content, content_new)
    }
    i <- i+1
  }

然后我想通过以下方式加入列表(为了获得典型格式的数据):

assets_mren = data.frame(asset_class=vnames, value=content)

但我收到一条错误消息,指出 vnamescontent不同的行数。我认为问题在于要读入的数据中的“null”。您知道如何在上面的“null”中读取或如何更好地读取数据?

【问题讨论】:

    标签: arrays json r import null


    【解决方案1】:

    是的,问题是空的。每行都有不同的结构。

    ll <- '{"a":1,"b":2,"c":3}
           {"a": null,"b":2,"c":3}'
    res <- lapply(ll,function(x)str(fromJSON(x)))
     Named num [1:3] 1 2 3                       ## named vector for the first line
     - attr(*, "names")= chr [1:3] "a" "b" "c"
    List of 3
     $ a: NULL                                   ## list for the second line
     $ b: num 2
     $ c: num 3
    

    所以你必须均匀化每一行的输出。这里有 2 个选项:

    1- 将 null 替换为虚拟值(0 或 -1),例如:

    ll <- readLines(textConnection(gsub("null",-1,ll)))
    do.call(rbind,lapply(ll,function(x)
        fromJSON(x)))
         a b c
    [1,]  1 2 3
    [2,] -1 2 3    ## res[res==-1] <- NA to replace dummy value
    

    2- 保留 null 但您应该使用 rbind.fill 来获取数据帧:

    ll <- readLines(textConnection(gsub("null",-1,ll)))
    do.call(rbind,lapply(ll,function(x)
      fromJSON(x)))
    ll <- '{"a":1,"b":2,"c":3}
    {"a": null,"b":2,"c":3}'
    ll <- readLines(textConnection(ll))
    res <- lapply(ll,function(x)
        as.data.frame(t(as.matrix(unlist(fromJSON(x))))))
    library(plyr)
    rbind.fill(res)
    
       a b c
    1  1 2 3
    2 NA 2 3
    

    【讨论】:

    • 嘿。非常感谢您的回答。你的例子工作正常。然而,当我阅读“我的数据”时,我收到以下错误消息:来自 JSON(x) 的错误:意外字符 'c'
    • @user3021506 很难在没有数据的情况下帮助您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2011-04-15
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 2014-04-17
    相关资源
    最近更新 更多