gpt4 book ai didi

json - 如何将数据框转换为嵌套列表?

转载 作者:行者123 更新时间:2023-12-02 17:21:01 24 4
gpt4 key购买 nike

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

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"
}
]
}
]
}
]

有更好的方法吗?

最佳答案

使用 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")

这是输出:

nestedList
# $A
# $A$a
# $A$a$tenant
# [1] "Smith"
#
# $A$a$income
# [1] "100"
#
#
# $A$b
# $A$b$tenant
# [1] "Jones"
#
# $A$b$income
# [1] "200"
#
#
#
# $B
# $B$a
# $B$a$tenant
# [1] "Smith"
#
# $B$a$income
# [1] "300"
#
#
# $B$b
# $B$b$tenant
# [1] "Jones"
#
# $B$b$income
# [1] "400"

结构:

> 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"

该结构与您正在寻找的内容并不完全匹配,但这可能有助于您开始使用替代方法。

关于json - 如何将数据框转换为嵌套列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15206576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com