2

次の形式の R データフレームがあります。

Country Region  Year    V1  V2
AAAA    XXXX    2001    12  13
BBBB    YYYY    2001    14  15
AAAA    XXXX    2002    36  56
AAAA    XXXX    1999    45  67

そして、次のフォームに相当する JSON を生成したいと考えています。

[
  {"Country": "AAAA",
   "Region":"XXXX",
    "V1": [ [1999,45], [2001,12] , [2002,36] ],
    "V2":[ [1999,67], [2001,13] , [2002,56] ]
  },
  {"Country": "BBBB",
   "Region":"YYYY",
   "V1":[ [2001,14] ],
   "V2":[ [2001,15] ]
  }
]

私はこれが必要だと想像しています:

  1. 国と地域によるグループ化
  2. グループ内の年によるソート
  3. V1、V2 の残りの列 Vx (任意の名前を持つ可能性のある任意の数の列) のそれぞれについて、リスト要素 [Year, Vx] を含むリストを生成します。

しかし、それを行う方法を見つけるのに苦労していますか?

4

2 に答える 2

3

これを行う別の方法を次に示します。

dat <- read.table(textConnection("Country Region  Year    V1  V2
AAAA    XXXX    2001    12  13
BBBB    YYYY    2001    14  15
AAAA    XXXX    2002    36  56
AAAA    XXXX    1999    45  67"), header = TRUE)

ベクトルをまとめて圧縮する 2 つのヘルパー関数と、指定された位置の要素でリストを並べ替えるカスタム並べ替え関数を追加します。

#' Pluck element
pluck_ = function (element){
  function(x) x[[element]]
}

#' Zip two vectors
zip_ <- function(..., names = F){
  x = list(...)
  y = lapply(seq_along(x[[1]]), function(i) lapply(x, pluck_(i)))
  if (names) names(y) = seq_along(y)
  return(y)
}

#' Sort a vector based on elements at a given position
sort_ <- function(v, i = 1){
  v[sort(sapply(v, '[[', i), index.return = T)$ix]
}

物事をまとめ、split-apply-combine魔法を使って求めるアウトプットを得る時が来ました。

library(plyr)
dat2 <- dlply(dat, .(Country, Region), function(d){
  list(
    Country = d$Country[1],
    Region = d$Region[1],
    V1 = sort_(zip_(d$Year, d$V1)),
    V2 = sort_(zip_(d$Year, d$V2))
  )
})
cat(rjson::toJSON(setNames(dat2, NULL)))

これにより、出力が得られます

[
  {"Country":"AAAA",
   "Region":"XXXX",
   "V1":[[1999,45],[2001,12],[2002,36]],
   "V2":[[1999,67],[2001,13],[2002,56]]
  },
  {"Country":"BBBB",
   "Region":"YYYY",
   "V1":[[2001,14]],
   "V2":[[2001,15]]
  }
]
于 2013-11-01T14:53:40.850 に答える
0

これを行うための厄介な関数を次に示します (V1 および V2 配列の年による並べ替えを簡単に追加できます)。

dat <- read.table(textConnection(
'Country Region  Year    V1  V2
AAAA    XXXX    2001    12  13
BBBB    YYYY    2001    14  15
AAAA    XXXX    2002    36  56
AAAA    XXXX    1999    45  67'
), header=TRUE, stringsAsFactors=FALSE)

library(plyr); library(RJSONIO)
myfunc <- function(nn)
{
  tt <- split(nn, nn$Country)
  bar <- function(w){
    foo <- function(x, y, z) paste(x[y], x[z], sep=",")
    V1 <- as.character(apply(w, 1, foo, y="Year", z="V1"))
    V2 <- as.character(apply(w, 1, foo, y="Year", z="V2"))
    datlist <- list(Country = unique(w$Country), 
                    Region = unique(w$Region), 
                    V1 = V1, V2=V2)
  }
  datlist <- lapply(tt, bar)
  names(datlist) <- NULL
  RJSONIO::toJSON(datlist)
}

cat(myfunc(dat))

[
 {
   "Country": "AAAA",
   "Region": "XXXX",
   "V1": [ "2001,12", "2002,36", "1999,45" ],
   "V2": [ "2001,13", "2002,56", "1999,67" ] 
 },
 {
   "Country": "BBBB",
   "Region": "YYYY",
   "V1": "2001,14",
   "V2": "2001,15" 
  } 
]
于 2013-11-01T14:34:06.820 に答える