我有一个数据框,想要将其转化为具有自定义嵌套级别的嵌套列表。以下是我的做法,但我相信有更好的方法:
JSON 的输出看起来像这样:
有没有更好的方法来做这件事?
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)
}))
})
JSON 的输出看起来像这样:
library(rjson)
write(toJSON(nested_data), "")
[{"city":"A","street_values":[{"street":"a","tenant_values":[{"tenant":"Smith","income":"100"}]},{"street":"b","tenant_values":[{"tenant":"Jones","income":"200"}]}]},{"city":"B","street_values":[{"street":"a","tenant_values":[{"tenant":"Smith","income":"300"}]},{"street":"b","tenant_values":[{"tenant":"Jones","income":"400"}]}]}]
# or prettified:
[
{
"city": "A",
"street_values": [
{
"street": "a",
"tenant_values": [
{
"tenant": "Smith",
"income": "100"
}
]
},
{
"street": "b",
"tenant_values": [
{
"tenant": "Jones",
"income": "200"
}
]
}
]
},
{
"city": "B",
"street_values": [
{
"street": "a",
"tenant_values": [
{
"tenant": "Smith",
"income": "300"
}
]
},
{
"street": "b",
"tenant_values": [
{
"tenant": "Jones",
"income": "400"
}
]
}
]
}
]
有没有更好的方法来做这件事?
JSON
的问题,还是如何创建一个符合R定义的“嵌套列表”的R
对象,例如foo<-list(bar=NA,snafu="hello, Dave"); foo[[bar]] <- list(a=1,b=2)
? - Carl WitthoftJSON
输出,因为它比R列表格式更容易理解,但我想从R数据框转换为R列表。 - nachocab