【问题标题】:How to nest a dataframe in R based on columns?如何根据列在 R 中嵌套数据框?
【发布时间】:2020-07-03 09:50:16
【问题描述】:

我正在尝试嵌套数据框(例如 iris),以便 columnamesclass(例如数字、因子等)位于单独的列和行中,并且数据 在嵌套列表中。需要与 dplyr 一起使用。

结果应该是这样的:

非常感谢您的帮助和

最好的问候 亚历克斯

【问题讨论】:

    标签: r dplyr nested


    【解决方案1】:

    你可以使用:

    out <- data.frame(class = sapply(iris, class), 
                      column_name = names(iris), row.names = NULL)
    out$nested <- as.list(iris)
    View(out)
    

    【讨论】:

      【解决方案2】:

      你可以直接在一行中写:

      tibble(class = sapply(iris, class), column = names(iris), nested = as.list(iris))
      #> # A tibble: 5 x 3
      #>   class   column       nested      
      #>   <chr>   <chr>        <named list>
      #> 1 numeric Sepal.Length <dbl [150]> 
      #> 2 numeric Sepal.Width  <dbl [150]> 
      #> 3 numeric Petal.Length <dbl [150]> 
      #> 4 numeric Petal.Width  <dbl [150]> 
      #> 5 factor  Species      <fct [150]> 
      

      【讨论】:

        【解决方案3】:

        我们可以使用I 调用data.frame 创建一个列表

        data.frame(class = sapply(iris, class), 
                column_name = names(iris), nested = I(as.list(iris)))
        

        【讨论】:

          猜你喜欢
          • 2021-05-24
          • 2022-07-04
          • 2023-03-20
          • 1970-01-01
          • 2019-05-20
          • 2023-03-21
          • 2013-08-01
          • 2021-09-06
          • 1970-01-01
          相关资源
          最近更新 更多