Home > Back-end >  Create a nested list with map and list.dirs
Create a nested list with map and list.dirs

Time:01-23

First let's set up the folder structure we need for this question.

dir.create("A")
dir.create("B")

setwd("A")
dir.create("C")
dir.create("D")

setwd("..")

setwd("B")
dir.create("E")
dir.create("F")

setwd("..")

Now let's run this code:

list.dirs(recursive = F) %>% 
  map(~list.dirs(path = ., recursive = F))

I am getting the following structure:

[[1]]
[1] "./A/C" "./A/D"

[[2]]
[1] "./B/E" "./B/F"

However, what I want is this structure:

[[1]]
[1] "./A/C" 
[2] "./A/D"

[[2]]
[1] "./B/E" 
[2] "./B/F"

How can I achieve that?

By the way, the above code worked on my old computer without a problem, but on the new one I am getting the currently described issue. Was there some sort of an update that now requires different handling?

CodePudding user response:

It seems like you want to have lists rather than vectors in your main list ?

(start <- 
list(
  c("a","b"),
  c("c","d")
))
str(start)
(goal <- 
    list(
      list("a","b"),
      list("c","d")
    ))

str(goal)

# map the lists contents to lists and achieve the goal
identical(goal,
          map(start,as.list))

 #doesnt error : 
map_depth(goal,2,.f = identity)
  • Related