2

階層情報を含む data.frame を JSON (またはネストされたリスト) に適切に変換するにはどうすればよいですか?

次の data.frame があるとします。

df <- data.frame(
  id = c('1', '1.1', '1.1.1', '1.2'), 
  value = c(10, 5, 5, 5)) 

#  id   value
#     1    10
#   1.1     5
# 1.1.1     5
#   1.2     5

次に、次の JSON で終了したいと思います。

{
 "id": "1",
 "value": 10,
 "children": [
  {
   "id": "1.1",
   "value": 5,
   "children": [
    {
     "id": "1.1.1", 
     "value": 5 
    }
   ]
  },
  {
   "id": "1.2",
   "value": 5
  }
 ]
}

whereidは階層構造を定義.する区切り文字です。

私の意図は、データを R から階層的な D3 ビジュアライゼーション(たとえば、パーティション レイアウトまたはズーム可能なツリーマップ) に簡単に変換できるようにすることです。さらに「値」列を追加できるとよいでしょう。例: 、、など。valuesizeweight

ありがとうございました!

編集:元の質問に戻したので、すべての回答を簡単に確認できます (すべての編集で申し訳ありません)。

4

2 に答える 2

3

RJSONIO私はこれを行うインストールする傾向があります:

R> df <- data.frame(id = c('1', '1.1', '1.1.1', '1.2'), value = c(10, 5, 5, 5)) 
R> RJSONIO::toJSON(df)
[1] "{\n \"id\": [ \"1\", \"1.1\", \"1.1.1\", \"1.2\" ],\n\"value\": [     10,      5,      5,      5 ] \n}"
R> cat(RJSONIO::toJSON(df), "\n")
{
 "id": [ "1", "1.1", "1.1.1", "1.2" ],
"value": [     10,      5,      5,      5 ] 
} 
R> 

これは目的の出力ではありませんが、目的のネスト/階層がdata.frame に存在しませんでした。リスト内にdata.frameをネストすると、そこに到達すると思います。

編集:あなたの改訂された質問について、ここにあなたがスペックしたJSONを読み込んだR出力があります:

R> RJSONIO::fromJSON("/tmp/foo.json")
$id
[1] "1"

$value
[1] 10

$children
$children[[1]]
$children[[1]]$id
[1] "1.1"

$children[[1]]$value
[1] 5

$children[[1]]$children
$children[[1]]$children[[1]]
$children[[1]]$children[[1]]$id
[1] "1.1.1"

$children[[1]]$children[[1]]$value
[1] 5




$children[[2]]
$children[[2]]$id
[1] "1.2"

$children[[2]]$value
[1] 5



R> 
于 2013-01-25T20:13:12.590 に答える
1

可能な解決策。

まず、次の関数を定義します。

# Function to get the number hierarchical dimensions (occurences of "." + 1)
ch_dim <- function(x, delimiter = ".") {
    x <- as.character(x)
    chr.count <- function(x) length(which(unlist(strsplit(x, NULL)) == delimiter))
    if (length(x) > 1) {
        sapply(x, chr.count) + 1
    } else {
        chr.count(x) + 1
    }
}

# Function to convert a hierarchical data.frame to a nested list
lst_fun <- function(ch, id_col = "id", num = min(d), stp = max(d)) {

    # Convert data.frame to character
    ch <- data.frame(lapply(ch, as.character), stringsAsFactors=FALSE)

    # Get number of hierarchical dimensions
    d <- ch_dim(ch[[id_col]])

    # Convert to list
    lapply(ch[d == num,][[id_col]], function(x) {
        tt <- ch[grepl(sprintf("^%s.", x), ch[[id_col]]),]
        current <- ch[ch[[id_col]] == x,]
        if (stp != num && nrow(tt) > 0) { 
            c(current, list(children = lst_fun(tt, id_col, num + 1, stp)))
        } else { current }
    })
}

次に、data.frame をリストに変換します。

lst <- lst_fun(df, "id")

最後に、JSON:

s <- RJSONIO::toJSON(lst)
于 2013-01-29T07:39:18.727 に答える