2015-03-24 12 views
10

Załóżmy Mam następującą listę, która reprezentuje strukturę katalogów:Tworzenie listy rekurencyjną z listy wektorów

> pages <- list("about.Rmd", "index.Rmd", c("stats", "index.Rmd"), c("stats", "substats", "index.Rmd")) 
> pages 
[[1]] 
[1] "about.Rmd" 

[[2]] 
[1] "index.Rmd" 

[[3]] 
[1] "stats"  "index.Rmd" 

[[4]] 
[1] "stats"  "substats" "index.Rmd" 

chciałbym stworzyć rekurencyjną wersję tej liście, coś, co wyglądać tak:

> rpages <- list("about.Rmd", "index.Rmd", stats=list("index.Rmd", substats=list("index.Rmd"))) 
> rpages 
[[1]] 
[1] "about.Rmd" 

[[2]] 
[1] "index.Rmd" 

$stats 
$stats[[1]] 
[1] "index.Rmd" 

$stats$substats 
$stats$substats[[1]] 
[1] "index.Rmd" 

próbowałem różnych sposobów, aby to zrobić, ale boję się, że jestem teraz stracił w morzu lapply i sapply.

Z góry dziękuję za wszelkie wskazówki.

Odpowiedz

8

myślę, że to prawda:

build_list = function(item, res) { 
    if (length(item) > 1) { 
    res[[item[1]]] = build_list(tail(item, -1), res[[item[1]]]) 
    } else { 
    res = c(res, list(item)) 
    } 
    res 
} 

res = list() 
for (i in seq_along(pages)) res = build_list(pages[[i]], res) 

res 
#[[1]] 
#[1] "about.Rmd" 
# 
#[[2]] 
#[1] "index.Rmd" 
# 
#$stats 
#$stats[[1]] 
#[1] "index.Rmd" 
# 
#$stats$substats 
#$stats$substats[[1]] 
#[1] "index.Rmd" 
+1

znacznie prostsze niż myślałem; dzięki za wskazanie mojego błędu wcześniej (dałoby ci rep z mojego A, jeśli mógłbym) – BrodieG

+0

Świetnie! Wielkie dzięki. – juba