Json 如何将数据帧转换为嵌套列表?

Json 如何将数据帧转换为嵌套列表?,json,r,list,dataframe,Json,R,List,Dataframe,我有一个数据框,我想将其转换为具有自定义嵌套级别的嵌套列表。我就是这样做的,但我相信有更好的方法: data <- data.frame(city=c("A", "A", "B", "B"), street=c("a", "b", "a", "b"), tenant=c("Smith","Jones","Smith","Jones"), income=c(100,200,300,400)) nested_data <- lapply(levels(data$city), funct

我有一个数据框,我想将其转换为具有自定义嵌套级别的嵌套列表。我就是这样做的,但我相信有更好的方法:

data <- data.frame(city=c("A", "A", "B", "B"), street=c("a", "b", "a", "b"), tenant=c("Smith","Jones","Smith","Jones"), income=c(100,200,300,400))

nested_data <- lapply(levels(data$city), function(city){
    data_city <- subset(data[data$city == city, ], select=-city)
    list(city = city, street_values=lapply(levels(data_city$street), function(street){
        data_city_street <- subset(data_city[data_city$street == street, ], select=-street)
        tenant_values <- apply(data_city_street, 1, function(income_tenant){
            income_tenant <- as.list(income_tenant)
            list(tenant=income_tenant$tenant, income=income_tenant$income)
        })
        names(tenant_values) <- NULL
        list(street=street, tenant_values=tenant_values)
    }))
})

有更好的方法吗?

使用
split
可以让您获得最大的收益,最后一步是
rapply

nestedList <- rapply(lapply(split(data[-1], data[1]), 
                            function(x) split(x[-1], x[1])), 
                     f = function(x) as.character(unlist(x)), 
                     how = "replace")
结构:

> str(nestedList)
List of 2
 $ A:List of 2
  ..$ a:List of 2
  .. ..$ tenant: chr "Smith"
  .. ..$ income: chr "100"
  ..$ b:List of 2
  .. ..$ tenant: chr "Jones"
  .. ..$ income: chr "200"
 $ B:List of 2
  ..$ a:List of 2
  .. ..$ tenant: chr "Smith"
  .. ..$ income: chr "300"
  ..$ b:List of 2
  .. ..$ tenant: chr "Jones"
  .. ..$ income: chr "400"

结构与您要查找的不完全匹配,但这可能有助于您开始使用另一种方法。

我通过将函数更改为:

nestedList <- rapply(lapply(split(df[-1], df[1]),
                          function(x) split(x[-1], x[1])),
                   f = function(x) as.data.frame(as.list(split(x,x))),  how = "replace")

nestedList那么,你是在问一个关于R的
JSON
输出的问题,还是如何创建一个
R
对象,它是R的定义中的“嵌套列表”,例如
fooI刚才显示了
JSON
输出,因为它比R list格式更容易理解,但我想从R数据帧转到R list
> str(nestedList)
List of 2
 $ A:List of 2
  ..$ a:List of 2
  .. ..$ tenant: chr "Smith"
  .. ..$ income: chr "100"
  ..$ b:List of 2
  .. ..$ tenant: chr "Jones"
  .. ..$ income: chr "200"
 $ B:List of 2
  ..$ a:List of 2
  .. ..$ tenant: chr "Smith"
  .. ..$ income: chr "300"
  ..$ b:List of 2
  .. ..$ tenant: chr "Jones"
  .. ..$ income: chr "400"
nestedList <- rapply(lapply(split(df[-1], df[1]),
                          function(x) split(x[-1], x[1])),
                   f = function(x) as.data.frame(as.list(split(x,x))),  how = "replace")