在嵌套列中保留原始类型的"tibble" [英] Preserve original type `tibble` in nested columns
问题描述
我真的很喜欢v1.0.0
随附的新tidyr
界面.
I really like the new tidyr
interface that came with v1.0.0
.
但是,由于tidyverse或多或少地以tibble
为中心,我有点困惑,嵌套列似乎是data.frame
的列表,即使原始数据是要开始的tibble
与(在这种情况下,我期望在嵌套列中以tibble
的列表结尾):
However, with the tidyverse more or less being centered around tibble
, I was a bit puzzled that the nested column seems to be a list of data.frame
s - even when the original data was a tibble
to begin with (in which case I would have expected that I end up with a list of tibble
s in the nested column):
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()
给/给我的结果完全相同的结果吗?
Is there any way the get to exact same result that tidyr::nest_legacy()
gave/gives me?
推荐答案
使用nest
与nest_legacy
似乎是数据列的类.
It seems like the difference is the class of the data column when using nest
versus nest_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
同时使用两种方法并检查它们是否为tibble
Using both methods and checking if they are tibble
s
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
Using as.list
on your data column will produce the same results as 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
这篇关于在嵌套列中保留原始类型的"tibble"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!