1

我有一个小标题和一个列表,我想写入一个 json 文件。

# A tibble: 2 x 12
  i     n             c                  x      
  <chr> <chr>         <chr>              <chr>  
1 NYC   New York City United States      LON,271;BOS,201
2 LON   London        United Kingdom     NYC,270

我想用列表替换“x”列。

当我尝试将“i”列与列表元素合并时,很多数据被重复...:/

样品清单:

$NYC
     d   p
1: LON 271
2: BOS 201

$LON
     d   p
1: NYC 270

我想最终得到如下所示的东西:

[
  {
    "i": "NYC",
    "n": "New York City",
    "c": "United States",
    "C": "US",
    "r": "Northern America",
    "F": 66.256,
    "L": -166.063,
    "b": 94.42,
    "s": 0.752,
    "q": 4417,
    "t": "0,0,0,0,0",
    "x": [{
              "d": "LON",
              "p": 271
          },
          {
              "d": "BOS",
              "p": 201
          }]
}
  ...
]

我在想应该有一种方法可以在不合并列表和小标题的情况下编写 json 文件,或者也许有一种方法可以以不规则的方式合并它们?

啊。我只是有了另一个想法。也许我可以将我的数据框转换为列表,然后使用 Reduce 来组合列表...

http://www.sharecsv.com/s/2e1dc764430c6fe746d2299f71879c2e/routes-before-split.csv

http://www.sharecsv.com/s/b114e2cc6236bd22b23298035fb7e042/tibble.csv


4

1 回答 1

1

我们可以做以下事情:

tbl
# A tibble: 1 x 13
#       X i     n      c             C     r                 F      L     b     s     q t        x               
#   <int> <fct> <fct>  <fct>         <fct> <fct>         <dbl>  <dbl> <dbl> <dbl> <int> <fct>    <fct>           
# 1     1 LON   London United Kingd… GB    Northern Eur…  51.5 -0.127  55.4  1.25  2088 0,0,1,3… AAL,15;AAR,15;A…

require(tidyverse)
tbl$x <- map(tbl$x, ~ strsplit(., ";|,")[[1]] %>%
             {data.frame(d = .[c(T, F)], p = as.numeric(.[c(F, T)]))})

后两行是此基本 R 等效项的缩短版本:

tbl$x <- lapply(tbl$x, function(r) {
  tmp <- strsplit(r, ";|,")[[1]]
  data.frame(d = tmp[seq(1, length(tmp), 2)],
             p = as.numeric(tmp[seq(2, length(tmp), 2)]))
})

我们遍历该x列,尽可能将其元素拆分;,然后使用结果奇数元素将对应d于所需结果的列,以及偶数元素对应于该列的事实p

输出:

toJSON(tbl, pretty = TRUE)
[
  {
    "X": 1,
    "i": "LON",
    "n": "London",
    "c": "United Kingdom",
    "C": "GB",
    "r": "Northern Europe",
    "F": 51.508,
    "L": -0.127,
    "b": 55.43,
    "s": 1.25,
    "q": 2088,
    "t": "0,0,1,3,1",
    "x": [
      {
        "d": "AAL",
        "p": 15
      },
      {
        "d": "AAR",
        "p": 15
      },
      {
        "d": "ABZ",
        "p": 48
      }
    ]
  }
] 
于 2018-12-04T11:08:19.960 回答