问题
I really like the new tidyr
interface that came with v1.0.0
.
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]
Is there any way the get to exact same result that tidyr::nest_legacy()
gave/gives me?
回答1:
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
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]>
Checking the class of the data column
class(test1[[2]])
[1] "vctrs_list_of" "vctrs_vctr"
class(test2[[2]])
[1] "list"
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
来源:https://stackoverflow.com/questions/58505582/preserve-original-type-tibble-in-nested-columns