gpt4 book ai didi

json - R 中的嵌套分层数据框

转载 作者:行者123 更新时间:2023-12-05 00:36:42 27 4
gpt4 key购买 nike

我是 R 的新手,我不想从一开始就误解语言及其数据结构。 :)

我的 data.frame sample.data 除了“正常”属性(例如 author)之外还包含另一个嵌套的 data.frame 列表(files), 例如属性 extension.

如何筛选创建了具有特定扩展名的文件的作者?有 R-ic 的方法吗?也许在这个方向:

t <- subset(data, data$files[['extension']] > '.R')

其实我想避免 for 循环。

在这里您可以找到一些示例数据:

d1 <- data.frame(extension=c('.py', '.py', '.c++')) # and some other attributes
d2 <- data.frame(extension=c('.R', '.py')) # and some other attributes

sample.data <- data.frame(author=c('author_1', 'author_2'), files=I(list(d1, d2)))

sample.data 来自的 JSON 看起来像

[
{
"author": "author_1",
"files": [
{
"extension": ".py",
"path": "/a/path/somewhere/"
},
{
"extension": ".c++",
"path": "/a/path/somewhere/else/"
}, ...
]
}, ...
]

最佳答案

至少有十几种方法可以做到这一点,但如果你想正确地学习 R,你应该学习子集数据结构的标准方法,尤其是原子向量、列表和数据框。这在本书的第二章中有所介绍:

http://adv-r.had.co.nz/

还有其他好书,但这是一本好书,而且是在线免费的。

更新:好的,这会将您的 json 转换为数据框列表。

library("rjson")
s <- paste(c(
'[{' ,
' "author": "author_1",',
' "files": [',
' {',
' "extension": ".py",',
' "path": "/a/path/somewhere/"',
' },',
' {',
' "extension": ".c++",',
' "path": "/a/path/somewhere/else/"',
' }]',
'},',
'{',
'"author": "author_2",',
'"files": [',
' {',
' "extension": ".py",',
' "path": "/b/path/somewhere/"',
' },',
' {',
' "extension": ".c++",',
' "path": "/b/path/somewhere/else/"',
' }]',
'}]'),collapse="")

j <- fromJSON(s)

todf <- function (x) {
nrow <- length(x$files)
vext <- sapply(x$files,function (y) y[[1]])
vpath <- sapply(x$files,function (y) y[[2]])
df <- data.frame(author=rep(x$author,nrow),ext=vext,path=vpath)
}
listdf <- lapply(j,todf)
listdf

产生:

[[1]]
author ext path
1 author_1 .py /a/path/somewhere/
2 author_1 .c++ /a/path/somewhere/else/

[[2]]
author ext path
1 author_2 .py /b/path/somewhere/
2 author_2 .c++ /b/path/somewhere/else/

并完成任务、合并和子集:

   mdf <- do.call("rbind", listdf)
mdf[ mdf$ext==".py", ]

产量:

    author ext               path
1 author_1 .py /a/path/somewhere/
3 author_2 .py /b/path/somewhere/

关于json - R 中的嵌套分层数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31401430/

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