问题描述
我有一个小标题和一个列表,我想将其写入json文件.
I have a tibble and a list which I would like to write to a json file.
# 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 would like to replace the 'x' column with a list.
当我尝试通过'i'列与列表的元素合并时,很多数据被重复...:/
When I try to merge by the 'i' column with the element of the list, a lot of data is duplicated... :/
样本列表:
$NYC
d p
1: LON 271
2: BOS 201
$LON
d p
1: NYC 270
我想得到的最终结果是这样的:
I would like to end up with something that looks like this:
[
{
"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文件而不合并列表和小标题,或者也许有一种方法可以将它们合并到?
I'm thinking there should be a way to write the json file without merging the list and the tibble, or maybe there is a way to merge them in a ragged way ?
啊.我只是有另一个主意.也许我可以将数据框转换为列表,然后使用Reduce组合列表...
ah. I just had another idea. maybe I can convert my dataframe to a list then use Reduce to combine the lists...
http://www.sharecsv.com/s/2e1dc764430c6fe746d2299f71879c2e/routes-before-split.csv
http://www.sharecsv.com/s/b114e2cc6236bd22b23298035fb7e042/tibble.csv
推荐答案
我们可以执行以下操作:
We may do the following:
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等效项的简化版本:
The latter two lines are a shortened version of this base R equivalent:
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
列中的偶数元素.
We go over the x
column, split its elements by ;
and ,
whenever possible, and then use the fact that the resulting odd elements will correspond do the d
column in the desired outcome, and the even elements to the p
column.
输出:
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
}
]
}
]
这篇关于在R中使用多个输入编写JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!