[英]as_tibble control level of flattening
In the example below I have a list where one element is a list with a sublist. 在下面的示例中,我有一个列表,其中一个元素是带有子列表的列表。 It appears that as_tibble()
is flattening down until the 3rd level of list before stopping. 似乎在停止之前, as_tibble()
平直到列表的第3级。 It would be nice to be able to control the flattening so I could preserve the entire list with sublist in element "c"
of the example. 能够控制展平会很好,因此我可以在示例的元素"c"
中保留带有子列表的整个列表。 I suspect some combination of map()
, flatten()
, etc. is needed, but cannot figure it out. 我怀疑需要map()
, flatten()
等的某种组合,但无法弄清楚。
as_tibble()
returns 2 rows, but I really only want 1 row with a column corresponding to each list element ("a", "b", "c"). as_tibble()
返回2行,但实际上我只希望1行具有与每个列表元素(“ a”,“ b”,“ c”)相对应的列。
library(dplyr)
x <- list(a = 1,
b = 2,
c = list(x=list(y=3,
z=4),
xx=NULL))
parsed <- as_tibble(x)
parsed
#> # A tibble: 2 x 3
#> a b c
#> <dbl> <dbl> <list>
#> 1 1. 2. <list [2]>
#> 2 1. 2. <NULL>
parsed[1,]$c
#> $x
#> $x$y
#> [1] 3
#> $x$z
#> [1] 4
parsed[2,]$c
#> $xx
#> NULL
parsed <- as_tibble(x)
parsed
#> # A tibble: 1 x 3
#> a b c
#> <dbl> <dbl> <list>
#> 1 1. 2. <list [2]>
parsed[1,]$c
#> $x
#> $x$y
#> [1] 3
#> $x$z
#> [1] 4
#> $xx
#> NULL
This is not elegant but here is one way to do it. 这不是很优雅,但这是实现它的一种方法。
library(purrr)
x <- list(a = 1,
b = 2,
c = list(x=list(y=3,
z=4),
xx=NULL))
# define a function to preserve the list
unnest_one_level <- function(x){
if(is.list(x)) list(x) else x
}
res <- x %>% map_dfr(unnest_one_level)
res
#> # A tibble: 1 x 3
#> a b c
#> <dbl> <dbl> <list>
#> 1 1. 2. <list [2]>
res$c
#> [[1]]
#> [[1]]$x
#> [[1]]$x$y
#> [1] 3
#>
#> [[1]]$x$z
#> [1] 4
#>
#> [[1]]$xx
#> NULL
as.tibble will repeat each column recycle each column value till they all have a shared number of elements. as.tibble将重复每一列,回收每个列的值,直到它们都具有共享数量的元素。 Here you are a
and b
have length 1, but c
has length 2. So it seems you really want to treat it as a length one list, you just need to nest it in a list. 在这里, a
和b
长度为1,而c
长度为2。因此,您似乎真的想将其视为一个列表的长度,只需要将其嵌套在列表中即可。 I think this will do what you want in this case at least. 我认为这至少可以满足您的需求。
parsed <- as_tibble(modify_if(x, ~length(.x)>1, list))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.