R中的嵌套分层数据帧

Mic*_*ner 2 json r hierarchical hierarchical-data dataframe

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

我的data.frame sample.data包含"普通"属性(例如author)另一个嵌套的data.frame(files)列表,其中包含例如属性extension.

如何筛选已创建具有特定扩展名的文件的作者?有没有一种R-ic方式呢?也许在这个方向:

t <- subset(data, data$files[['extension']] > '.R')
Run Code Online (Sandbox Code Playgroud)

其实我想避免循环.

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

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)))
Run Code Online (Sandbox Code Playgroud)

sample.data来自的JSON看起来像

[
    {
        "author": "author_1",
        "files": [
            {
                "extension": ".py",
                "path": "/a/path/somewhere/"
            },
            {
                "extension": ".c++",
                "path": "/a/path/somewhere/else/"
            }, ...
        ]
    }, ...
]
Run Code Online (Sandbox Code Playgroud)

Mik*_*ise 6

至少有十几种方法可以做到这一点,但是如果你想学习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
Run Code Online (Sandbox Code Playgroud)

产量:

[[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/
Run Code Online (Sandbox Code Playgroud)

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

   mdf <- do.call("rbind", listdf)
   mdf[ mdf$ext==".py", ]
Run Code Online (Sandbox Code Playgroud)

收益:

    author ext               path
1 author_1 .py /a/path/somewhere/
3 author_2 .py /b/path/somewhere/
Run Code Online (Sandbox Code Playgroud)