嵌套命名列表列时保留名称

时间:2019-06-20 22:09:47

标签: r dplyr tidyverse purrr

这是我的代表:

make_named_list <- function(x) {
  list(apple = 1, banana = 2, carrot = 3)
}

tibble(x = 1:3, y = 2:4) %>% 
  mutate(z = map(x, make_named_list)) %>% 
  unnest() %>% 
  pull(z)

输出是一个没有任何名称的列表,但是我想输出一个命名列表。我看了一个相关的问题here,但不确定该解决方案是否适用于我的(简单?)方案。

要清楚,所需的输出是:

list(apple = 1, banana = 2, carrot = 3, 
     apple = 1, carrot = 2, banana = 3, 
     apple = 1, banana = 2, carrot = 3)

3 个答案:

答案 0 :(得分:1)

根据您的输出要求,可以尝试以下操作之一

library(tidyverse)

tibble(x = 1:3, y = 2:4) %>% 
  mutate(z = map(x, make_named_list)) %>%
  pull(z) 

#[[1]]
#[[1]]$apple
#[1] 1

#[[1]]$banana
#[1] 2

#[[1]]$carrot
#[1] 3


#[[2]]
#[[2]]$apple
#[1] 1
#.....

tibble(x = 1:3, y = 2:4) %>% 
   mutate(z = map(x, make_named_list)) %>%
   pull(z) %>% unlist() 

# apple banana carrot  apple banana carrot  apple banana carrot 
#     1      2      3      1      2      3      1      2      3 

tibble(x = 1:3, y = 2:4) %>% 
   mutate(z = map(x, make_named_list)) %>%
   pull(z) %>% unlist() %>% as.list()

#$apple
#[1] 1

#$banana
#[1] 2

#$carrot
#[1] 3

#$apple
#[1] 1
#... 

答案 1 :(得分:1)

好像我们只需要rep

rep(make_named_list(3), 3)
#$apple
#[1] 1

#$banana
#[1] 2

#$carrot
#[1] 3

#$apple
#[1] 1

#$banana
#[1] 2

#$carrot
#[1] 3

#$apple
#[1] 1

#$banana
#[1] 2

#$carrot
#[1] 3

或者如果我们使用tidyverse,则使用flatten

tibble(x = 1:3, y = 2:4) %>% 
    transmute(z = map(x, make_named_list)) %>% 
    pull(z) %>% 
    flatten
#$apple
#[1] 1

#$banana
#[1] 2

#$carrot
#[1] 3

#$apple
#[1] 1

#$banana
#[1] 2

#$carrot
#[1] 3

#$apple
#[1] 1

#$banana
#[1] 2

#$carrot
#[1] 3

答案 2 :(得分:0)

names_repair = tidyr_legacy中设置unnest()

library(tidyverse)
make_named_list <- function(x) {
  list(apple = 1, banana = 2, carrot = 3)
}

tibble(x = 1:3, y = 2:4) %>% 
  mutate(z = map(x, make_named_list)) %>% 
  unnest(cols = c(z), names_repair = tidyr_legacy) %>% 
  pull(z)