knitr和matchit的神秘缓存bug(包MatchIt)

时间:2014-06-06 19:53:33

标签: r caching simulation knitr

我有一个问题,knitr缓存一个包含对MatchIt包中matchit()函数的调用的R块,使用匹配和rgenoud包中实现的“遗传”算法:这个块在执行每个编译。这是双重痛苦:

  • 遗传算法使用模拟==>结果略有不同(我的学生会对p.value的第三个“重要”小数的变化概念感到茫然......)
  • 非常耗时(倾向得分匹配比你想象的要困难,特别是在小样本上)。

我已经设法将其减少到“最小可重复的示例”,这不是 最小Rnw-wise(大约5 Kb .Rnw文件,包括严重的前同步码),并且需要非常小的数据(80 Kb .csv数据)和一个小的.bib文件。无论如何,似乎没有办法将文件附加到stackoverflow问题......

我试图通过使用cache.extra选项添加对MD5总和的显式依赖来减少数据文件的依赖性。没有成功

我还使用dependspon()指定了显式依赖项。没有运气。

我也问过这个问题(带有示例数据)给谢一晖(没有答案,但毕竟......这个人可能有一个博士来保卫......)。

现在,我解决了穷人缓存的困难(测试是否存在objevt并且只在没有的情况下执行代码),但当然我失去了一致性,这是使用knitr的重点!

如果某个善良的灵魂对我的问题感兴趣,我可以通过这个例子向他发送一个tarball。

任何提示?

编辑:根据原始需求,这里是最小.Rnw的当前状态(我没有触及长前导码,以防它相关......):


\documentclass[a4paper,twoside,12pt]{article}
\synctex=1
\pdfcompresslevel=0
\pdfobjcompresslevel=0
<<include=FALSE>>=
## opts_chunk$set(concordance=TRUE, self.contained=TRUE)
opts_knit$set(concordance=TRUE, self.contained=TRUE)
@ 
%% \SweaveOpts{concordance=TRUE}
\usepackage[utf8]{inputenc}
\usepackage[english,francais]{babel} %% Français dominant
\usepackage[T1]{fontenc} % Utilité ??
\usepackage{lmodern} %% Polices pour les guillemets ? Oui ! Et
             %% meilleur...
\DeclareMathAlphabet{\mathpzc}{OT1}{pzc}{m}{it} %% Cursives math (distris)
\usepackage{cite} %% Biblios !
\usepackage[a4paper]{geometry}
\geometry{verbose,tmargin=2cm,bmargin=2cm,lmargin=2cm,rmargin=2cm}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{rotating} %% Pour \sidewaysxxx. et rotations dans les tables.
\usepackage{float} %% pour utiliser la position "H" des tables
\usepackage{subfig} %% Pour les légendes des sous-figures
%% \usepackage{subcaption} %% Mieux ?
\usepackage{hyperref} %% Signets dans le PDF. Doit venir en dernier,
\usepackage{sagetex} %% sauf si on veut l'interfaçage avec Sage,
%                      %% qui doit être *APRÈS*!!!
% \usepackage{emaxima} %% Si l'on veut utiliser maxima...

\title{Minimal reproductible example exhibiting a caching problem with \textsl{knitr} caching}
\author{Emmanuel Charpentier}
\date{June 4, 2014}

\begin{document}
\selectlanguage{english}
\maketitle
\begin{abstract}
  \emph{}
\end{abstract}

\tableofcontents
\listoffigures
\listoftables
\clearpage

%% My usual setup, adapted to each main (noweb) file name via emacs.

<<KnitrSetup, eval=TRUE, echo=FALSE>>=
render_sweave()
library(Cairo)
##
opts_chunk$set(eval=TRUE, echo=FALSE, dev=c('cairo_pdf', 'cairo_ps'),
               fig.ext=c('pdf', 'eps'), fig.path="figureTmp/",
               cache=TRUE, cache.path="cacheTmp/",
               fig.width=5, fig.height=4, ## Pouces (obligatoire)
               out.width="5in", ## 1/1 scale, just in case...
               autodep=TRUE, cache.lazy=FALSE)
@ 

<<LibsSetup, echo=FALSE, results="hide">>=
## libaries used in the rest of the text.
require(xtable)
require(MatchIt)
@ 

Start compilation with a citation\cite{rosenbaum_central_1983} to appease \textsl{knit2pdf}\dots

<<Lecture1, echo=FALSE, results="hide", cache.extra=file.info("Pts.csv")$mtime>>=
## Read data
## On lit à partir du jeu que j'ai mis au propre
Pts<-within(read.csv("Pts.csv", sep=";", dec=","),
            PtId<-factor(as.character(PtId),levels=PtId))
@ 

<<Lecture2, echo=FALSE, results="hide", cache.extra=file.info("Data.csv")$mtime>>=
## Read data (bis)
Data.long<-within(read.csv("Data.csv", dec=",", sep=";"),
                  PtId<-factor(as.character(PtId),levels=levels(Pts$PtId)))
@ 

<<Variations, echo=FALSE, results="hide">>=
Variations<-within(reshape(Data.long, idvar=c("PtId", "Var"),
                           timevar="T", direction="wide"),
                   Variation<-Val.Ap-Val.Av)
Vars<-merge(Pts,Variations)
@ 


<<Appariement1, echo=FALSE, results="hide", message=FALSE, warning=FALSE>>=
## Create the (wide) pre-treatment dataset
PreTtt<-local({
    foo<-merge(Pts[,c("PtId","Groupe","Sexe","Age.T0","Durée")],
               within(reshape(Variations[,c("PtId", "Var", "Val.Av")],
                              idvar="PtId",
                              timevar="Var",
                              direction="wide"), {
                                  PtId<-factor(as.character(PtId),
                                               levels=levels(Pts$PtId))
                              }))
    foo<-within(foo, {
        Ttt<-(Groupe=="Ttt")
        SexeF<-(Sexe=="F")
    })
    foo<-foo[!is.na(foo$Age.T0),
             setdiff(names(foo),
                     c("Groupe","Sexe"))]
    names(foo)<-gsub("Val\\.Av\\.","",names(foo))
    row.names(foo)<-foo$PtId
    foo
})
@ 

This is the problematic chunk. It re-runs in every compilation.

<<Appariement2, echo=FALSE, results="hide", message=FALSE, warning=FALSE>>=
## Do pairing on pre-treatment variables
## NB : matchit is noisy...
## Poor man's attempt at caching (commented out)
## if (!("Pairing" %in% ls())) {
Pairing<-local({
    foo<-matchit(Ttt~Apx.Sup.x+Sn.x+BL.Sup.x+L.Sup.y+Prn.y+Age.T0+ANB+
                 BL.Sup.y+L.Inf.y+SexeF+Apx.Sup.x+Sn.x+Durée+Apx.Inf.x+
                 Pog.Os.x+Pog.Cut.x+SLM.x+Sn.x+L.Sup.y+SNA+BL.Inf.y+SLM.y,
                 data=PreTtt[!is.na(PreTtt$Age.T0),],
                 method="genetic", pop.size=500,
                 estimand="ATE",
                 discard="both")
    foo
})
## } ## end of caching
@ 

Pairing done.

%% Still untested : pairing summary :

%% <<Appariement3, echo=FALSE, results="hide", message=FALSE, warning=FALSE>>=
%% ## Balance de l'appariement
%% PairingSum<-summary(Pairing,
%%         addlvariables=PreTtt[!is.na(PreTtt$Age.T0),
%%             setdiff(names(PreTtt),
%%                     c("PtId","Ttt",
%%                       do.call(c,
%%                               lapply(as.character(Pairing$formula[[3]]),
%%                                      function(x) {
%%                                          strsplit(x,
%%                                                   " + ",
%%                                                   fixed=TRUE)[[1]]}))[-1]))],
%%              standardize=TRUE)
%% @ 


\clearpage


\bibliographystyle{vancouver}
\bibliography{Tmp}

\end{document}

%%% Local Variables:
%%% TeX-master: "Tmp"
%%% End:

感觉更好? ; - )

0 个答案:

没有答案
相关问题