【问题标题】:Extract a nested data frame from a data.table从 data.table 中提取嵌套数据框
【发布时间】:2021-06-17 08:55:08
【问题描述】:

我在 data.table 中包含以下三个 data.frame:

name <- data.frame(c("Bob","Mary","Jane","Kim"))
weight <- data.frame(c(60,65,45,55))
height <- data.frame(c(170,165,140,135))
dft <- data.table( x = list(name,weight,height) )

我想知道如何从dft 中提取一个data.frame?比如name,我可以用

dft[[1, "x"]]

但它不是很有效。有没有更有效的方法来做到这一点?

【问题讨论】:

    标签: r dataframe data.table


    【解决方案1】:

    要从x 中提取一个数据帧,您可以通过索引引用它们。

    dft$x[[1]]
    
    #  name
    #1  Bob
    #2 Mary
    #3 Jane
    #4  Kim
    

    把它们全部提取出来

    dft$x
    
    # [[1]]
    #  name
    #1  Bob
    #2 Mary
    #3 Jane
    #4  Kim
    
    #[[2]]
    #  weight
    #1     60
    #2     65
    #3     45
    #4     55
    
    #[[3]]
    #  height
    #1    170
    #2    165
    #3    140
    #4    135
    

    将它们合二为一:

    do.call(cbind, dft$x)
    
    #  name weight height
    #1  Bob     60    170
    #2 Mary     65    165
    #3 Jane     45    140
    #4  Kim     55    135
    

    数据

    library(data.table)
    
    name <- data.frame(name = c("Bob","Mary","Jane","Kim"))
    weight <- data.frame(weight = c(60,65,45,55))
    height <- data.frame(height = c(170,165,140,135))
    dft <- data.table( x = list(name,weight,height))
    

    【讨论】:

      【解决方案2】:

      dplyr 解决方案可以通过将每一行拆分为单独的数据帧然后取消嵌套来提取所有数据帧。

      library(dplyr)
      dft %>% 
        as_tibble() %>% 
        group_split(x) %>% 
        lapply(., function(z) unnest(z, x))
      

      另外,我建议您谨慎使用嵌套数据框中的未命名列名。

      【讨论】:

        猜你喜欢
        • 2020-07-30
        • 1970-01-01
        • 1970-01-01
        • 2020-07-14
        • 2020-05-23
        • 2019-10-06
        • 1970-01-01
        • 2016-05-08
        • 1970-01-01
        相关资源
        最近更新 更多