R数据帧为嵌套列表形式或json形式

时间:2017-12-14 12:46:43

标签: json r list dataframe

我在数据帧格式方面遇到了一些麻烦。我的数据是这样的3级嵌套数据

df = data.frame(index1=c("a","a","b","b","b","c","d","d","d"),index2=c(0,1,0,0,0,0,0,0,1),index3=c(0,0,0,1,2,0,0,1,0),
            value1=c(99,99,88,88,88,77,55,55,55),value2=c(50,50,40,40,40,30,17,17,15),value3=c(55,55,4,4,4,3,1,1,7),
            value4=c(10,15,9,9,9,5,4,4,2),value5=c(10,15,10,10,7,5,2,3,5))

我想将其转换为此格式

{
index1:"a",
value1:99,
index2:[
  {
   value2:50,
   value3:55,
   index3:
   [
     {
     value4:10,
     value5:10
     }
   ]},
  {
   value2:50,
   value3:55,
   index3:
   [
     {
     value4:15,
     value5:15
     }
   ]}

},
{
index1:"b",
value1:88,
index2:[
  {
   value2:40,
   value3:4,
   index3:
   [
     {
     value4:9,
     value5:10
     },
     {
     value4:9,
     value5:10
     },
     {
     value4:9,
     value5:7
     }
   ]}

},
{
index1:"c",
value1:77,
index2:[
  {
   value2:30,
   value3:3,
   index3:
   [
     {
     value4:5,
     value5:5
     }
   ]}

},
{
index1:"d",
value1:55,
index2:[
  {
    value2:17,
    value3:1,
    index3:[
       {
        value4:4,
        value5:2
       },
       {
        value4:4,
        value5:3
       }
     ],
    value2:15,
    value3:7,
    index3:[
      {
       value4:2,
       value5:5
      }
    ]
  }]
}

我该怎么办?我能怎么做??我可以使用功能拆分和lapply吗?但我不知道如何使用.......................................... .................................................. .................................................. .................

0 个答案:

没有答案