【问题标题】:Preserve original type `tibble` in nested columns在嵌套列中保留原始类型“tibble”
【发布时间】:2020-02-18 16:21:16
【问题描述】:

我真的很喜欢 v1.0.0 附带的新 tidyr 界面。

但是,由于 tidyverse 或多或少以 tibble 为中心,我有点困惑,嵌套列似乎是 data.frames 的列表 - 即使原始数据是 tibble 开始with(在这种情况下,我希望我最终在嵌套列中得到一个 tibbles 列表):

library(magrittr)

df <- tibble::tribble(
  ~id, ~x, ~y,
  1, 10, 20,
  1, 100, 200,
  2, 1, 2
)
df
#> # A tibble: 3 x 3
#>      id     x     y
#>   <dbl> <dbl> <dbl>
#> 1     1    10    20
#> 2     1   100   200
#> 3     2     1     2

df %>% tidyr::nest_legacy(-id)
#> # A tibble: 2 x 2
#>      id data            
#>   <dbl> <list>          
#> 1     1 <tibble [2 x 2]>
#> 2     2 <tibble [1 x 2]>

df %>% tidyr::nest(data = -id)
#> # A tibble: 2 x 2
#>      id           data
#>   <dbl> <list<df[,2]>>
#> 1     1        [2 x 2]
#> 2     2        [1 x 2]

有什么方法可以得到tidyr::nest_legacy() 给/给我的完全相同的结果?

【问题讨论】:

  • 我认为df %&gt;% group_nest(id) 给了你想要的结果。
  • @tmfmnk 感谢您的指点。不过,仍然感觉有点混乱/不一致,因为group_nest() 住在dplyr 而不是tidyr,还有df %&gt;% dplyr::group_by(id) %&gt;% tidyr::nest() 再次给了我data.frames 的列表:-/
  • 这可能会得到相同的结果:df %&gt;% nest(data = -id) %&gt;% mutate_at(vars(data), ~as.list(.))

标签: r nested tidyr tibble


【解决方案1】:

似乎区别在于使用 nestnest_legacy 时数据列的类。

library(tidyr)
library(dplyr)

df <- tibble::tribble(
   ~id, ~x, ~y,
   1, 10, 20,
   1, 100, 200,
   2, 1, 2
 )
 df
# A tibble: 3 x 3
#     id     x     y
#  <dbl> <dbl> <dbl>
#1     1    10    20
#2     1   100   200
#3     2     1     2

使用这两种方法并检查它们是否为tibbles

 test1 <- df %>% nest(data = -id)
 test2 <- df %>% nest_legacy(-id)

 test1 %>% '[['(2) %>% '[['(1) %>% is_tibble()
[1] TRUE

 test1
# A tibble: 2 x 2
#     id           data
#  <dbl> <list<df[,2]>>
#1     1        [2 x 2]
#2     2        [1 x 2]

 test2 %>% '[['(2) %>% '[['(1) %>% is_tibble()
[1] TRUE

 test2
# A tibble: 2 x 2
#     id data            
#  <dbl> <list>          
#1     1 <tibble [2 x 2]>
#2     2 <tibble [1 x 2]>

检查数据列的类

 class(test1[[2]])
[1] "vctrs_list_of" "vctrs_vctr"   
 class(test2[[2]])
[1] "list"

在您的数据列上使用as.list 将产生与nest_legacy 相同的结果

 test3 <- df %>% nest(data = -id) %>% mutate_at(vars(data), ~as.list(.))
 test3

# A tibble: 2 x 2
#     id data            
#  <dbl> <list>          
#1     1 <tibble [2 x 2]>
#2     2 <tibble [1 x 2]>


 identical(test2, test3)
[1] TRUE

【讨论】:

  • 太好了,谢谢!但我真的不明白它为什么会起作用,as.list() 是如何突然将data.frame 变成tibble 的?
  • @Rappster 我认为他们已经是tibbles,就像我的回答一样,如果您查看df %&gt;% nest(-id) %&gt;% '[['(2) %&gt;% '[['(1) %&gt;% is_tibble(),它将返回TRUEas.list 只是更改 data 列的类以匹配 nest_legacy 所做的事情。
  • 嗯,好的,知道了。似乎tidyr 更多地使用了vctrs。也是vctrs 的粉丝,但我仍然觉得现在看到&lt;list&lt;df[,2]&gt;&gt; 并且没有关于tibble 的信息感到困惑
猜你喜欢
  • 2019-11-03
  • 1970-01-01
  • 2019-12-14
  • 1970-01-01
  • 2020-06-25
  • 2021-03-11
  • 1970-01-01
  • 2022-07-07
  • 2018-05-18
相关资源
最近更新 更多