【问题标题】:converting nested list into dataframe/datatable将嵌套列表转换为数据框/数据表
【发布时间】:2018-09-03 19:40:54
【问题描述】:

我遇到了一个非常特殊的问题。我有一个带有 JSON 字段的数据库:

# A tibble: 1 x 3
   field1 field2        JSONfield
    <int> <chr>         <chr>                                                      
1      43 stringgg      "{\"typ\": \"Liste mit Punkten\", \"min~

现在,如果我应用以下模式:

dbGetQuery(pool, mydatabase) %>% 
  mutate(json = map(JSONfield, ~ fromJSON(.) %>% 
                      as.data.frame(stringsAsFactors = FALSE))) %>% 
  unnest(json)

我会收到:

# A tibble: 2 x 10
   field1 field2     JSONfield                typ   min   max   items.1 items.2  items.3
    <int> <chr>       <chr>                   <chr> <int> <int> <fct>   <fct>    <fct>  
1     43  stringgg    "{\"typ\": \"Liste mit~ List~ 0     1      first  second   third   
2     43  stringgg    "{\"typ\": \"Liste mit~ List~ 0     1      3       0        7   

虽然我想要的输出是:

# A tibble: 2 x 10
   field1 field2     JSONfield                typ   min   max   items
    <int> <chr>       <chr>                   <chr> <int> <int> <list>  
1     43  stringgg    "{\"typ\": \"Liste mit~ List~ 0     1      <data.frame~ 

JSON 对象如下所示:

{"typ": "Liste mit Punkten",  
   "min": 0, 
   "max": 1, 
   "items": [["first", "second", "third"], 
             [3, 0, 7]]}

此外,我必须处理的 JSON 对象具有最多 7 个名称/值对的子集,这些名称/值对可能会或可能不会出现在对象中,因此我正在寻找一个相当不具体的解决方案。

非常感谢在此问题上提供任何帮助。

【问题讨论】:

  • data.framedata.table 在 R 中不能接受另一个 data.frame, data.table 作为列。要么将其保存为嵌套列表,要么将项目连接到一个字符串列中。

标签: r json dataframe datatable dplyr


【解决方案1】:

试试

library(dplyr)
library(purrr)
library(tidyr)
library(jsonlite)

text <- '{"typ": "Liste mit Punkten",  
   "min": 0, 
   "max": 1, 
   "items": [["first", "second", "third"], 
             [3, 0, 7]]}'

dd <- data_frame(field1 = 43, field2 = "stringgg", JSONfield = text)

dd %>% 
  mutate(json = map(JSONfield, ~ fromJSON(.) %>%
      map_if(is.matrix, ~list(as.data.frame(.))) %>% as_tibble
  )) %>%
  unnest() %>%
  select(-JSONfield)
# # A tibble: 1 x 6
#   field1 field2   typ                 min   max items               
#    <dbl> <chr>    <chr>             <int> <int> <list>              
# 1     43 stringgg Liste mit Punkten     0     1 <data.frame [2 × 3]>

要查看发生了什么,我们可以检查fromJSON(text)

# $typ
# [1] "Liste mit Punkten"

# $min
# [1] 0

# $max
# [1] 1

# $items
#      [,1]    [,2]     [,3]   
# [1,] "first" "second" "third"
# [2,] "3"     "0"      "7"    

我们将items 元素(一个矩阵)转换为数据框,然后将其放入列表中。最后,我们将整个列表(包含 typminmaxitems)转换为 tibble。

【讨论】:

    猜你喜欢
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多