통계 분석 및 보고서 작성을위한 워크 플로우
사용자 정의 보고서 작성과 관련된 데이터 분석을위한 워크 플로우에 대한 지식이 있습니까? 유스 케이스는 기본적으로 다음과 같습니다.
고객은 데이터 분석을 사용하는 보고서, 예를 들어 수자원 지구에 대한 인구 추정 및 관련 맵을 의뢰합니다.
분석가는 일부 데이터를 다운로드하고 데이터를 병합하며 결과를 저장합니다 (예 : 단위당 인구에 대한 열 추가 또는 지구 경계에 따라 데이터 하위 설정).
분석가는 (2)에서 생성 된 데이터를 분석하고 목표에 가까워 지지만 더 많은 데이터가 필요하므로 (1)로 돌아갑니다.
테이블과 그래픽이 QA / QC를 충족하고 클라이언트를 만족시킬 때까지 헹굽니다.
테이블과 그래픽을 통합 한 보고서를 작성하십시오.
내년에 행복한 고객이 돌아와서 업데이트를 원합니다. 사양을 변경하지 않는 한 새 다운로드로 업스트림 데이터를 업데이트하고 (예 : 작년에 건물 허가를받는 등) "RECALCULATE"버튼을 누르는 것만 큼 간단합니다.
지금은 디렉토리를 시작하고 최선을 다해 임시로 만듭니다. 좀 더 체계적인 접근 방식을 원하므로 누군가가 이것을 이해하기를 바라고 있습니다. 나는 스프레드 시트, SQL, ARCGIS, R 및 Unix 도구를 혼합하여 사용합니다.
감사!
추신:
다음은 다양한 중간 데이터 세트 ( .RData
접미사 포함) 및 스크립트 ( .R
접미사) 에 대한 종속성을 확인하는 기본 Makefile입니다 . Make는 타임 스탬프를 사용하여 종속성을 확인하므로이 touch ss07por.csv
파일이 종속 된 모든 파일 / 대상보다이 파일이 최신 파일인지 확인하고 지정된 스크립트를 실행하여 그에 따라 업데이트합니다. 이 작업은 여전히 SQL 데이터베이스에 들어가기위한 단계 및 스 웨브와 같은 템플릿 언어를위한 단계를 포함하여 진행중인 작업입니다. Make는 구문에 따라 탭을 사용하므로 잘라서 붙여 넣기 전에 설명서를 읽으십시오. 즐기고 의견을 보내십시오!
http://www.gnu.org/software/make/manual/html_node/index.html#Top
R = / home / wsprague / R-2.9.2 / bin / R persondata.RData : ImportData.R ../../DATA/ss07por.csv Functions.R $ R --slave -f ImportData.R persondata.Munged.RData : MungeData.R persondata.RData Functions.R $ R --slave -f MungeData.R report.txt : TabulateAndGraph.R persondata.Munged.RData Functions.R $ R --slave -f TabulateAndGraph.R> report.txt
나는 일반적으로 프로젝트를 4 개 조각으로 나눕니다.
- 로드
- 깨끗합니다 .R
- func.R
- 할 .R
R : 필요한 모든 데이터를로드합니다. 일반적으로 이것은 파일, URL 및 / 또는 ODBC에서 데이터를 읽는 짧은 파일입니다. 이 시점의 프로젝트에 따라 save()
다음 단계를 사용하여 작업 공간을 작성 하거나 메모리에 보관합니다.
clean.R : 결 측값을 처리하고, 데이터 프레임을 병합하고, 이상 값을 처리하는 모든 추악한 것들이있는 곳입니다.
func.R : 실제 분석을 수행하는 데 필요한 모든 기능이 포함되어 있습니다. source()
이 파일은 함수 정의를로드하는 것 외에 부작용이 없어야합니다. 즉, 큰 데이터 세트에 대해 실행하는 데 시간이 오래 걸릴 수있는 1 단계와 2 단계를 반복하지 않고도이 파일을 수정하고 다시로드 할 수 있습니다.
do.R : func.R에 정의 된 함수를 호출하여 분석을 수행하고 차트와 테이블을 생성합니다.
이 설정의 주요 동기는 후속 단계를 변경할 때마다 데이터를 다시로드 할 필요가없는 대용량 데이터를 다루는 것입니다. 또한 코드를 이와 같이 구획화하면 오랫동안 잊혀진 프로젝트로 돌아와서 빠르게로드를 읽을 수 있습니다 .R. 업데이트해야 할 데이터를 찾은 다음 수행해야 할 데이터를 조사하여 수행 된 분석을 수행합니다.
몇 가지 예를 보려면 온라인에서 사용할 수있는 소규모 (소형이 아닌) 데이터 정리 및 분석 프로젝트가 있습니다. 대부분의 경우 데이터를 다운로드하는 스크립트, 정리하는 스크립트 및 탐색 및 분석을위한 스크립트를 찾을 수 있습니다.
최근에 스크립트 번호를 매기기 시작 했으므로 어떤 순서로 스크립트를 실행해야하는지 분명합니다. (정말 기분이 좋으면 탐색 스크립트가 청소 스크립트를 호출하고 다운로드 스크립트를 호출하여 필요한 최소 작업을 수행합니다. 일반적으로 출력 파일의 존재 여부를 확인하여 확인합니다 file.exists
. 그러나 대부분의 경우 이것은 과도한 것으로 보입니다.
모든 프로젝트 (소스 코드 관리 시스템)에 git을 사용하므로 다른 사람들과 공동 작업하기 쉽고 변경 사항을 확인하고 이전 버전으로 쉽게 롤백 할 수 있습니다.
공식 보고서를 작성하는 경우 일반적으로 R과 라텍스를 별도로 유지하지만 항상 source
R 코드를 사용하여 보고서에 필요한 모든 코드와 출력을 생성 할 수 있는지 확인합니다 . 내가하는 여러 종류의 보고서에 대해서는 라텍스를 사용하는 것보다 더 쉽고 깔끔하다는 것을 알았습니다.
다른 응답자에 동의합니다. Sweave는 R로 보고서를 작성하는 데 탁월합니다. 업데이트 된 결과로 보고서를 다시 작성하는 것은 Sweave 기능을 다시 호출하는 것만 큼 간단합니다. 모든 분석, 데이터 등을 포함하여 완전히 독립적이며 전체 파일을 버전 제어 할 수 있습니다.
보고서 개발을 위해 Eclipse 용 StatET 플러그인을 사용하고 Sweave가 통합되었습니다 (Eclipse는 라텍스 형식 지정 등을 인식 함). Windows에서는 MikTEX를 사용하기 쉽습니다 .
또한 Beamer로 멋진 보고서를 만들 수 있다고 덧붙였습니다 . 일반 보고서 작성은 간단합니다. Yahoo!에서 데이터를 가져 오는 예제가 아래에 포함되어 있습니다. quantmod를 사용하여 차트와 테이블을 만듭니다. 다음과 같이이 보고서를 작성할 수 있습니다.
Sweave(file = "test.Rnw")
비머 문서 자체는 다음과 같습니다.
%
\documentclass[compress]{beamer}
\usepackage{Sweave}
\usetheme{PaloAlto}
\begin{document}
\title{test report}
\author{john doe}
\date{September 3, 2009}
\maketitle
\begin{frame}[fragile]\frametitle{Page 1: chart}
<<echo=FALSE,fig=TRUE,height=4, width=7>>=
library(quantmod)
getSymbols("PFE", from="2009-06-01")
chartSeries(PFE)
@
\end{frame}
\begin{frame}[fragile]\frametitle{Page 2: table}
<<echo=FALSE,results=tex>>=
library(xtable)
xtable(PFE[1:10,1:4], caption = "PFE")
@
\end{frame}
\end{document}
누군가가 그것을 놓친 경우를 대비 하여 Jeffrey Horner의 brew 패키지를 사용 하여 반복적 인 보고서 를 만드는 것에 대해 학습자 블로그에 훌륭한 게시물 이 있음 을 추가하고 싶었습니다 . 매트와 케빈은 모두 위에서 양조를 언급했습니다. 나는 실제로 그것을 많이 사용하지 않았습니다.
항목은 훌륭한 워크 플로를 따르므로 읽을 가치가 있습니다.
- 데이터를 준비하십시오.
- 보고서 템플릿을 준비하십시오.
- 보고서를 작성하십시오.
처음 두 단계가 완료되면 실제로 보고서를 작성하는 것은 매우 간단합니다.
library(tools)
library(brew)
brew("population.brew", "population.tex")
texi2dvi("population.tex", pdf = TRUE)
For creating custom reports, I've found it useful to incorporate many of the existing tips suggested here.
Generating reports: A good strategy for generating reports involves the combination of Sweave, make, and R.
Editor: Good editors for preparing Sweave documents include:
- StatET and Eclipse
- Emacs and ESS
- Vim and Vim-R
- R Studio
Code organisation: In terms of code organisation, I find two strategies useful:
- Read up about analysis workflow (e.g., ProjectTemplate, Josh Reich's ideas, my own presentation on R workflow Slides and Video )
- Study example reports and discern the workflow
I use Sweave for the report-producing side of this, but I've also been hearing about the brew package - though I haven't yet looked into it.
Essentially, I have a number of surveys for which I produce summary statistics. Same surveys, same reports every time. I built a Sweave template for the reports (which takes a bit of work). But once the work is done, I have a separate R script that lets me point out the new data. I press "Go", Sweave dumps out a few score .tex files, and I run a little Python script to pdflatex them all. My predecessor spent ~6 weeks each year on these reports; I spend about 3 days (mostly on cleaning data; escape characters are hazardous).
It's very possible that there are better approaches now, but if you do decide to go this route, let me know - I've been meaning to put up some of my Sweave hacks, and that would be a good kick in the pants to do so.
I'm going to suggest something in a different sort of direction from the other submitters, based on the fact that you asked specifically about project workflow, rather than tools. Assuming you're relatively happy with your document-production model, it sounds like your challenges really may be centered more around issues of version tracking, asset management, and review/publishing process.
If that sounds correct, I would suggest looking into an integrated ticketing/source management/documentation tool like Redmine. Keeping related project artifacts such as pending tasks, discussion threads, and versioned data/code files together can be a great help even for projects well outside the traditional "programming" bailiwick.
Agreed that Sweave is the way to go, with xtable for generating LaTeX tables. Although I haven't spent too much time working with them, the recently released tikzDevice package looks really promising, particularly when coupled with pgfSweave (which, as far as I know is only available on rforge.net at this time -- there is a link to r-forge from there, but it's not responding for me at the moment).
Between the two, you'll get consistent formatting between text and figures (fonts, etc.). With brew, these might constitute the holy grail of report generation.
At a more "meta" level, you might be interested in the CRISP-DM process model.
"make" is great because (1) you can use it for all your work in any language (unlike, say, Sweave and Brew), (2) it is very powerful (enough to build all the software on your machine), and (3) it avoids repeating work. This last point is important to me because a lot of the work is slow; when I latex a file, I like to see the result in a few seconds, not the hour it would take to recreate the figures.
For writing a quick preliminary report or email to a colleague, I find that it can be very efficient to copy-and-paste plots into MS Word or an email or wiki page -- often best is a bitmapped screenshot (e.g. on mac, Apple-Shift-(Ctrl)-4). I think this is an underrated technique.
For a more final report, writing R functions to easily regenerate all the plots (as files) is very important. It does take more time to code this up.
On the larger workflow issues, I like Hadley's answer on enumerating the code/data files for the cleaning and analysis flow. All of my data analysis projects have a similar structure.
I'll add my voice to sweave. For complicated, multi-step analysis you can use a makefile to specify the different parts. Can prevent having to repeat the whole analysis if just one part has changed.
I use project templates along with R studio, currently mine contains the following folders:
info
: pdfs, powerpoints, docs... which won't be used by any scriptdata input
: data that will be used by my scripts but not generated by themdata output
: data generated by my scripts for further use but not as a proper report.reports
: Only files that will actually be shown to someone elseR
: All R scriptsSAS
: Because I sometimes have to :'(
I wrote custom functions so I can call smart_save(x,y)
or smart_load(x)
to save or load RDS files
to and from the data output
folder (files named with variable names) so I'm not bothered by paths
during my analysis.
A custom function new_project
creates a numbered project folder, copies all the files from the template, renames the RProj
file and edits the setwd
calls, and set working directory to new project.
All R
scripts are in the R
folder, structured as follow :
00_main.R
setwd
- calls scripts 1 to 5
00_functions.R
- All functions and only functions go there, if there's too many I'll separate it into several, all named like
00_functions_something.R
, in particular if I plan to make a package out of some of them I'll put them apart
00_explore.R
- a bunch of script chunks where i'm testing things or exploring my data
- It's the only file where i'm allowed to be messy.
01_initialize.R
- Prefilled with a call to a more general
initialize_general.R
script from my template folder which loads the packages and data I always use and don't mind having in my workspace - loads
00_functions.R
(prefilled) - loads additional libraries
- set global variables
02_load data.R
- loads
csv/txt
xlsx
RDS
, there's a prefilled commented line for every type of file - displays which files hava been created in the workspace
03_pull data from DB.R
- Uses
dbplyr
to fetch filtered and grouped tables from the DB - some prefilled commented lines to set up connections and fetch.
- Keep client side operations to bare minimum
- No server side operations outside of this script
- Displays which files have been created in the workspace
- Saves these variables so they can be reloaded faster
Once it's been done once I switch off a query_db
boolean and the data will reloaded from RDS
next time.
It can happen that I have to refeed data to DBs, If so I'll create additional steps.
04_Build.R
- Data wrangling, all the fun
dplyr
/tidyr
stuff goes there - displays which files have been created in the workspace
- save these variables
Once it's been done once I switch off a build
boolean and the data will reloaded from RDS
next time.
05_Analyse.R
- Summarize, model...
- report
excel
andcsv
files
95_build ppt.R
- template for powerpoint report using
officer
96_prepare markdown.R
setwd
- load data
- set markdown parameters if needed
render
97_prepare shiny.R
setwd
- load data
- set shiny parameters if needed
runApp
98_Markdown report.Rmd
- A report template
99_Shiny report.Rmd
- An app template
I also do what Josh Reich does, only I do that creating my personal R-packages, as it helps me structure my code and data, and it is also quite easy to share those with others.
- create my package
- load
- clean
- functions
- do
creating my package: devtools::create('package_name')
load and clean: I create scripts in the data-raw/ subfolder of my package for loading, cleaning, and storing the resulting data objects in the package using devtools::use_data(object_name). Then I compile the package. From now on, calling library(package_name) makes these data available (and they are not loaded until necessary).
functions: I put the functions for my analyses into the R/ subfolder of my package, and export only those that need to be called from outside (and not the helper functions, which can remain invisible).
do: I create a script that uses the data and functions stored in my package. (If the analyses only need to be done once, I can put this script as well into the data-raw/ subfolder, run it, and store the results in the package to make it easily accessible.)
참고URL : https://stackoverflow.com/questions/1429907/workflow-for-statistical-analysis-and-report-writing
'Programming' 카테고리의 다른 글
WebView로 HTML 파일로드 (0) | 2020.05.19 |
---|---|
AppCompat-v7이 포함 된 도구 모음 및 상황 별 작업 모음 (0) | 2020.05.19 |
항목이 배열 / 목록에 있는지 확인 (0) | 2020.05.19 |
C #에서 프리미티브의 ==와 Equals ()의 차이점은 무엇입니까? (0) | 2020.05.19 |
/ proc / self / exe없이 현재 실행 파일 경로 찾기 (0) | 2020.05.19 |