3
votes

I am trying to create a named nested list, something like:

list(
  list(id = 1, name = "Abbie"), 
  list(id = 2, name = "Benjamin")
  # ... more list statements here
)

I have created the nested list structure using purrr::map2:

c("Abbie", "Benjamin") %>% 
  map2(seq(.), ., list) 

However, how do I then name the list with purrr?

Note: From this question I experimented with the following, which does not do what I'm looking for:

c("Abbie", "Benjamin") %>% 
  map2(seq(.), ., list) %>% 
  set_names(paste0("ID", seq(.)))
3
You don't need map c("Abbie", "Benjamin") %>% set_names(., seq_along(.)) %>% as.list - akrun

3 Answers

3
votes

Here is another way to create the nested list

library(purrr)
c("Abbie", "Benjamin") %>% 
     list(id = seq_along(.), name =.) %>% 
     transpose
#[[1]]
#[[1]]$id
#[1] 1

#[[1]]$name
#[1] "Abbie"


#[[2]]
#[[2]]$id
#[1] 2

#[[2]]$name
#[1] "Benjamin"
2
votes

Use one more map() because the names you want to set are the inner lists. If not, set_names() will set the names of outer lists.

c("Abbie", "Benjamin") %>% 
  map2(seq(.), ., list) %>%
  map(~ set_names(., c("ID", "Name")))

[[1]]
[[1]]$ID
[1] 1

[[1]]$Name
[1] "Abbie"


[[2]]
[[2]]$ID
[1] 2

[[2]]$Name
[1] "Benjamin"
0
votes

I would do it this way using purr::imap :

library(purr)
c("Abbie", "Benjamin") %>% imap(~list(id=.y,name=.x))
# [[1]]
# [[1]]$id
# [1] 1
# 
# [[1]]$name
# [1] "Abbie"
# 
# 
# [[2]]
# [[2]]$id
# [1] 2
# 
# [[2]]$name
# [1] "Benjamin"