2017-03-20 4 views
0

ggplots 및 데이터 프레임이 각각 포함 된 'list_plots'및 'list_tables'라는 두 개의 하위 목록이있는 'list_export'목록이 있습니다.목록 구조를 폴더 구조로 내보내기

list_plots <- list(plot1, plot2, plot3) 
list_tables <- list(table1, table2, table3) 
list_export <- list(list_plots, list_tables) 
내가 같은 올바른 데이터 유형과 폴더 구조로 목록의 트리 구조를 수출하고자하는

:

list_export/list_plots/plots[1-3].png 
list_export/list_tables/tables[1-3].csv 

직접 목록의 구조를 내보낼 수있는 방법이 있나요 폴더로? 2 차원이 아닌 n 레벨에 솔루션을 적용하고 싶습니다.

답변

1

이와 비슷한 작업은 없습니다. 도움이 될 수있는 함수를 만들 수 있습니다. 어쩌면이

savers <- list(
    "ggplot" = function(pp, base) ggsave(filename=paste0(base,".png"), plot=pp), 
    "data.frame" = function(dd, base) write.table(dd, file=paste0(base,".txt")) 
) 

save_list <- function(x, prefix=deparse(substitute(x)), savers=savers) { 
    ids = as.character(if(!is.null(names(x))) {names(x)} else {seq_along(x)}) 
    ids[nchar(ids)<1] <- as.character(seq_along(x)[nchar(ids)<1]) 
    ret <- Map(function(x, id) { 
    found <- FALSE 
    for(type in names(savers)) { 
     if(inherits(x, type)) { 
      found <- TRUE 
      ret <- savers[[type]](x, file.path(prefix, id)) 
      return(ret) 
     } 
    } 
    if (!found) { 
     if (class(x)=="list") { 
      save_list(x, file.path(prefix, id), savers=savers) 
     } else { 
      stop(paste("unable to save object of type:", class(x))) 
     } 
    } 
    }, x, ids) 
    invisible(ret) 
} 

같은 여기에 나는 다른 개체 유형을보고 디스크로 쓰는 savers의 목록을 만들 수 있습니다. 그런 다음 샘플 목록

plot_list <- Map(function(x) ggplot(mtcars) + geom_point(aes(cyl, disp)) + ggtitle(x), paste("plot", 1:3)) 
data_list <- replicate(4, data.frame(x=runif(10), y=rnorm(10)), simplify=FALSE) 
x <- list(plot_list=plot_list, data_list=data_list) 

으로 난 당신이 정말 그 이후의 파일 이름을 결정하기 위해 명명 된 목록이 필요

save_list(x) 

참고로를 작성할 수 있습니다. 여기에 x의 요소를 명시 적으로 지정하지만 표시되지 않으면 간단한 색인이 사용됩니다. 또한 화면에 값을 인쇄하여 저장 기능을 바꿀 수 있습니다.

noop <- list(
    "ggplot" = function(pp, fn) print(paste(paste0(fn,".png"),"(plot)")), 
    "data.frame" = function(dd, fn) print(paste(paste0(fn,".txt"), "(df)")) 
) 
save_list(x, savers=noop) 
# [1] "x/plot_list/plot 1.png (plot)" 
# [1] "x/plot_list/plot 2.png (plot)" 
# [1] "x/plot_list/plot 3.png (plot)" 
# [1] "x/data_list/1.txt (df)" 
# [1] "x/data_list/2.txt (df)" 
# [1] "x/data_list/3.txt (df)" 
# [1] "x/data_list/4.txt (df)" 

이는 디렉토리가 이미 있다고 가정합니다. 먼저 확인해야 할 경우 가능한 해결책은 this question을 참조하십시오.

+0

감사합니다. MrFlick! –