Home Comments Thread

[knitr] Elegant, flexible and fast dynamic report generation with R | /knitr/

yihui yihui 3y ago

knitr: Elegant, flexible and fast dynamic report generation with R

https://yihui.org/knitr/

👍👍❤️👍❤️

88 Replies

giscus-bot giscus-bot 3y ago
Guest *Kihoro* @ 2012-03-02 08:38:03 originally posted:

Thanks for your good work. We are following and using the tools innovatively. Here at  JKUAT (KENYA) .  We are now able to dynamically generate exams in LYX.  

yihui yihui 3y ago

 That sounds super cool! Do you have any examples that I can see online? If not, I'm wondering the brief idea behind these dynamic exams. Thanks!

Originally posted on 2012-03-02 20:28:48

giscus-bot giscus-bot 3y ago
Guest *Kihoro* @ 2012-03-22 18:47:32 originally posted:

System not yet hosted but the concept is simple.

Write all questions (with their answers/solutions) as child documents and have the main file to input them only if knitr code allows (random or systematic) selection. Knitting allows not manages the file/question selection but also sweaves the child files before a  standard exam draft with appended marking scheme thanks to answers.sty package.

Two questions

  1. With the appended exams it would be nenessary to access the lyx/latex file containing the solutions. Is this possible. In other words, how can one access lyx temporary files immediately after compilation.

  2. With Knitr, character zero (0) is displayed in scientific notation. How can I alter this?

yihui yihui 3y ago

2 is a bug and has been fixed in the latest version on CRAN; for 1, take a look at the object .cmdargs when you compile the lyx document -- it contains information about the temp directory (e.g. dirname(.cmdargs[1]) might be what you want).

Originally posted on 2012-03-22 20:01:12

giscus-bot giscus-bot 3y ago
Guest *astaines* @ 2012-03-31 20:20:16 originally posted:

Very impressive, thank you very much!
Anthony Staines

giscus-bot giscus-bot 3y ago
Guest *idrisr* @ 2012-04-09 03:52:44 originally posted:

I'm about to dig in to knitr, thanks in advance for your effrots.

giscus-bot giscus-bot 3y ago
Guest *Timm Danker* @ 2012-04-10 10:16:25 originally posted:

Thank you so musch for this excellent work!

giscus-bot giscus-bot 3y ago
Guest *MartinInFfm* @ 2012-04-11 02:14:48 originally posted:

I use the lyx/knitr  for dataset validation reporting in population pharmacokinetic modeling and simulation.
The new code externalization is superb.
What could improved is that

  • framed chunks (you use them in your demos) appear to work differently than unframed chunks.
    The frame of a chunk is a pain because on the screen you do not see whether the surrounding format is "standard" as you most certainly want it or "chunk". Framed chunks embedded in a chunk environment are not executed without warning.
    The benefit of the frame around a chunk is still unclear to me as it has no properties menu.
    One feature that would come in handy would be collapsability of the frame at a mouse click.
    Another would be mobility so that the chunk label needs no update if I cut and paste it somewhere else.
  • The cache function could be simplified. At the moment I create a new filename everytime I want to preview. Cache=FALSE does not help somehow. There appear pdf in the same folder where the lyx file is kept.
    Is there a global option to switch off all caching?
yihui yihui 3y ago
  1. I guess you mean the TeX ERT (Ctrl+L)  is the framed chunk, and the Chunk ERT is the unframed chunk ( https://github.com/downloads/yihui/lyx/sweave.pdf ). The former is more stable because it is a whole unit and the Chunk ERT is not, e.g. you cannot easily paste code into a Chunk ERT, and when you copy and paste a Chunk ERT, you can lose the indentation information. It is strongly recommended to use the TeX ERT only. You can collapse it by right click and "Close Inset".

  2. I do not understand your situation, but you can turn off cache by SweaveOpts{cache=FALSE} which is the default of the cache option, so you do not really need to do it.

Originally posted on 2012-04-11 04:00:10

giscus-bot giscus-bot 3y ago
Guest *MartinInChemnitz* @ 2012-04-23 04:13:07 originally posted:

Thank you for the helpful clarification Yihui.

  1. I did have ERT-frames in chunk formatted paragraphs that did not evaluate. Now I know what caused the problem.

  2. The caching and the overwriting of figures by reused chunks are still my biggest stumbling blocks:
    a) If I make a little change to a chunk in a lyx file that I have compiled, like inserting a line with a "1" at the   end, I need to save the file under a different name or the output of the chunk will remain unchanged in the necxt compilation - in spite of an ERT-box at the very top with the command "SweaveOpts{cache=FALSE}" that you recommended above.  One filename one compilation is my work around routine fight against caching.
    b) I reuse a chunk that displays descriptive statistics for various columns in a data frame.
    like (ERT boxes not shown)
    SweaveOpts{cache=FALSE}
    <>=
    require(ggplot2)
    a<- data.frame(X=c(1,2,3),Y=c(4,5,6),Z=c(7,8,9))
    VarName<- 'Y'
    (at)
    <<displayvar,cache=f,results='asis',echo=f,fig.width=4,fig.height=3>>=
    d <- a[,c('X',VarName)]
    names(d)<-c('x','y')
    ggplot()+geom_point(data=d,mapping=aes(x=x,y=y))
    (at)
    <<2>>=
    VarName<- 'Z'
    (at)
    <<displayvar,cache=f,results='asis',echo=f,fig.width=4,fig.height=3>>=
    (at)

And the second call of the chunk overwrites the figure produced by the first call so that I get twice the same figure.
No idea why I cannot remove the following from this comment:

yihui yihui 3y ago

You need to convert < to < when writing comments; I'm using Disqus and this annoys me a lot (they should be able to automatically encode HTML entities).

For caching, you are recommended to use the ref.label option: http://yihui.name/knitr/demo/reference/

It will not work if you use the same label for two chunks which generate cache and figure files, because these filenames are from the chunk label. The latter will certain overwrite the former if they have the same name.

Originally posted on 2012-04-23 04:30:52

giscus-bot giscus-bot 3y ago
Guest *Klebyn* @ 2012-04-29 20:30:14 originally posted:

knitr+Lyx don't compile if I set my language for 'Portuguese (Brazil)'. Someone have a tip? thanks.

yihui yihui 3y ago

I recommend you to use the UTF-8 encoding for your LyX document; before trying knitr, you need to make sure this LyX document compiles successfully without R code. Besides, Windows is difficult to work with non-ASCII documents.

Originally posted on 2012-04-29 21:29:29

giscus-bot giscus-bot 3y ago
Guest *Klebyn* @ 2012-04-29 22:30:57 originally posted:

Every examples (in ... Rlibraryknitrexamples) compile very fine, no errors! :-). But when I put characters with accents, like áéíóú in normal text, not in R chunk, I get the error message:

File ended while scanning use of Hy@scantitle.  
<*> knitr-listings.tex  
                       
*** (job aborted, no legal end found)  

neither convert to plain latex, works.
In Lyx, I set to utf8, but don't work anyway... Thanks for your attention.

Cleber Borges

yihui yihui 3y ago

As I said, you need to create a lyx document with Portuguese which compiles correctly, then add the knitr module. I mean you have to make it clear if it is a LaTeX problem or a knitr problem.

Originally posted on 2012-04-30 00:19:12

giscus-bot giscus-bot 3y ago
Guest *Klebyn* @ 2012-04-30 00:31:44 originally posted:

The problem occur just when I load the module knitr... Portuguese compile very fine without module knitr. I make several tests. Thanks again.

yihui yihui 3y ago

I just tested under Ubuntu (Linux), and UTF8-encoded Portuguese worked fine. Windows is often hopeless in terms of encodings. Which version of knitr are you using? If the latest version on Github does not work for you ( https://github.com/yihui/knitr ), I probably will not have a good solution in the very near future.

BTW, does knitr-minimal.Rhtml work for you? http://yihui.name/knitr/demo/minimal/

Originally posted on 2012-04-30 00:42:44

giscus-bot giscus-bot 3y ago
Guest *Klebyn* @ 2012-04-30 01:16:38 originally posted:

 library(knitr)
knit('knitr-minimal.Rnw')it create tex file and compile without errors. My version is knitr_0.4. I make changes: add áéí innormal text and in the title with usepackage[utf8]{inputenc}. Compile without errors again.The problem ought be the processing in LyX. (version 2.0.3-2).Is there any schedule for to create knitr_0.5.zip package and to migrate for the CRAN???

yihui yihui 3y ago

knitr 0.5 has been submitted to CRAN this morning, and if it passes R CMD check, it will be on CRAN in two days.

Originally posted on 2012-04-30 01:25:31

giscus-bot giscus-bot 3y ago
Guest *Klebyn* @ 2012-04-30 01:42:22 originally posted:

 I used the suggestion:library(devtools); install_github('knitr', 'yihui')and I get the version 0.5. I get the same behaviour :-( .

yihui yihui 3y ago

Then it is real hacking time for you -- the R script used to call knitr is lyxknitr.R under the "scripts" directory of your library directory (see Help -- About). Open that script and tweak it to see if you can make it. I guess it may have something to do with options(encoding = ...).

Originally posted on 2012-04-30 01:51:26

giscus-bot giscus-bot 3y ago
Guest *Klebyn* @ 2012-04-30 02:44:25 originally posted:

 o/o/o/

Now it works!!! :-)

I just comment the line (in lyxknitr.R)
####options(encoding = .cmdargs[3])

I don't understand why, but works!

Thanks for your attention and patience

yihui yihui 3y ago

Good to know. I will update the web page accordingly. Thanks!

Originally posted on 2012-04-30 03:01:45

giscus-bot giscus-bot 3y ago
Guest *Bastien Ferland-Raymond* @ 2012-05-01 12:34:59 originally posted:

If I can allow myself a simple comment and suggestion, I would love to have a 'silent=T' option with the knit function.  Seeing the code compile is nice at the beginning, but when it's working fine, I found it neater without.  Anyway, it's not a big deal, just my 2 cents.

Thanks.

yihui yihui 3y ago

Thanks. That makes sense, and you can set opts_knit$set(progress = FALSE) before you knit() to suppress the progress bar. See http://yihui.name/knitr/options

Originally posted on 2012-05-01 15:09:58

giscus-bot giscus-bot 3y ago
Guest *Bastien Ferland-Raymond* @ 2012-05-01 18:37:24 originally posted:

 Thanks, it works great.  Sorry I didn't notice the option, I still new in sweave/knitr and I not there yet in my self teaching schedule...
Keep up the good work, your package is amazing.

yihui yihui 3y ago

No problem. I know there are too many options :)

Originally posted on 2012-05-01 18:43:39

giscus-bot giscus-bot 3y ago
Guest *Shmil T* @ 2012-05-20 17:33:53 originally posted:

OK, no worries.

I think that what can actually solve the problem is to hook a TeX command which forces LTR in the beginning of the R code, and cancel it (meaning to return to the previous writing direction) in the end of the code. 

As you can see, the whole document is right aligned (which happens only when I use knitr)
I tried to write Pi several times.
Attached is the output of this syntax:

% Preview source code

%% LyX 2.0.3 created this file. For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
documentclass[english,hebrew]{article}
usepackage[T1]{fontenc}
usepackage[latin9,cp1255]{inputenc}
usepackage{fixltx2e}

makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.
usepackage{theorem}
theorembodyfont{upshape}
newtheorem{theorem}{R{משפט}}[section]
AtBeginDocument{make@lrthetheorem}

makeatother

usepackage{babel}
begin{document}
שלום, רציתי לומר מהו הערך של המספר האהוב עליי, פי: Sexpr{pi} . ואני
שואל אתכם, האין זה מספר יפה?

<<>>=
pi
@

inputencoding{latin9}Now, lets take a look of an english expression
such as Sexpr{pi}. Ain't it beautiful? %

end{document}

giscus-bot giscus-bot 3y ago
Guest *Shmil T* @ 2012-05-20 03:36:30 originally posted:

Hi, Thanks for the wonderful work. Knitr is a very powerful tool.
I have a problem working with knitr through Lyx in Hebrew -  when I activate the module it crashes.
I tweaked it as You said, and I got it to work together with the FixLatex package.
But now, I can't see graphs and the alignment is LTR! 
Which means that all is in the opposite direction.

I'd be happy to know if there's a solution for this situation.

Thanks in advance!

yihui yihui 3y ago

I'm afraid it is difficult for me to help in this case, because I know nothing about Hebrew. Can you provide an example to me? What is your OS and what is the version of your LyX as well as its LaTeX backend?

Originally posted on 2012-05-20 15:55:48

giscus-bot giscus-bot 3y ago
Guest *Shmil T* @ 2012-05-20 16:23:52 originally posted:

Hi, and thanks for the reply!
Using windows 7, Lyx 2.0.3, MikTeX 2.9.Using also the TEWAKED version of knitr (solution taken from other post in this site), as it is the only way to get it working.The attached code gave me 2 words in hebrew and a reversed R output (RTL).FYI, I don't get it to draw plots either.Thanks again!Shmulik% Preview source code

%% LyX 2.0.3 created this file. For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
documentclass[english,hebrew]{article}
usepackage[T1]{fontenc}
usepackage[latin9,cp1255]{inputenc}
usepackage{fixltx2e}

makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.
usepackage{theorem}
theorembodyfont{upshape}
newtheorem{theorem}{R{משפט}}[section]
AtBeginDocument{make@lrthetheorem}

makeatother

usepackage{babel}
begin{document}
שלום

<<>>=
1+1
@

%
תודה!
end{document}

yihui yihui 3y ago

I do not even know how to compile a normal Hebrew document with LaTeX; at least pdflatex fails under my Ubuntu system...

Originally posted on 2012-05-20 17:19:38

giscus-bot giscus-bot 3y ago
Guest *Shmil T* @ 2012-05-21 13:33:41 originally posted:

Sorry, I replied to the next thread by mistake :

giscus-bot giscus-bot 3y ago
Guest *zhangym* @ 2012-05-25 02:28:44 originally posted:

How to use knitr in the file with ctex?

yihui yihui 3y ago

An Rnw document is basically a LaTeX document, so just write whatever you write with ctex, and make sure the R code is marked up appropriately. If you are not familiar with Sweave, see this example: https://github.com/yihui/knitr/blob/master/inst/examples/knitr-minimal.Rnw

Originally posted on 2012-05-25 02:40:54

giscus-bot giscus-bot 3y ago
Guest *Aloy* @ 2012-05-31 18:30:46 originally posted:

I am trying to make a beamer presentation with knitr in Rstudio and am running into some problems when I use cite(...) for references. Commenting out the cite(...) commands avoids errors when knitting, and I can open the .tex file and bibtex and latex the file twice to produce the citations. Is there a way to do all of this within Rstudio?

yihui yihui 3y ago

Sounds like a pure RStudio problem (so better report to them: http://support.rstudio.org/help/ ). What is your RStudio version? I thought RStudio should be intelligent enough to solve the bib problem; if you could provide a reproducible example, they should be glad to help you.

Originally posted on 2012-06-01 20:40:12

giscus-bot giscus-bot 3y ago
Guest *Kevin Goulding* @ 2012-05-31 21:16:22 originally posted:

Hi Yihui -- I'm considering learning either "Rapport" or "Knitr".  Could you give a rundown on how knitr is different (...better!) than rapport, or why someone might gravitate to one versus the other?  Many thanks!

yihui yihui 3y ago

rapport is based on templates, and knitr is based on literate programming; programming allows you to do anything, including using templates. There are just too many features to describe, but I do not know your background, so it is hard to list the points that may interest you most. Anyway, one thing that I can sell to you is that you can easily get started with this R Markdown example in RStudio: https://raw.github.com/yihui/knitr/master/inst/examples/knitr-minimal.Rmd

Originally posted on 2012-06-01 20:36:57

giscus-bot giscus-bot 3y ago
Guest *JMol* @ 2012-06-03 10:32:50 originally posted:

Hello Yihui;
First thank you very much, you have done a great job.
How can I decrease the distance between the knitrout environment and the normal text?

yihui yihui 3y ago

This is a LaTeX question; you can redefine the knitrout environment, and here is an example: https://gist.github.com/2760395#file_knitrout_vspace.rnw

Originally posted on 2012-06-03 13:41:50

giscus-bot giscus-bot 3y ago
Guest *JMol* @ 2012-06-04 18:24:54 originally posted:

Thank you very much. Originally in what file is defined for first time the knitrout environment?. I have been looking for in knitr.sty and other files with out luck.

yihui yihui 3y ago

It was defined as an empty environment which allows you to redefine later: https://github.com/yihui/knitr/blob/master/inst/misc/knitr.sty

Originally posted on 2012-06-04 18:47:37

giscus-bot giscus-bot 3y ago
Guest *JMol* @ 2012-06-04 18:54:54 originally posted:

Thank you again for your great job.

giscus-bot giscus-bot 3y ago
Guest *Chris* @ 2012-06-04 21:33:47 originally posted:

Hi Yihui,

Thank you very much for knitr, it has together with RStudio become a very important component of my R-work.

One question: I use LaTex because of its powerful layout capabilities, especially for creating advanced slides (beamer) with graphs, maps and text layouted together, that can be recreated many times with different indata. I see a lot of focus on Markdown, both here and with RStudio. It is good for fast and simple production, but for me it is too limited. Have I misunderstood Markdown? Can I continue using LaTex with knitr for my more advanced layout-needs?

Again, thanks a lot for knitr and all the supporting documentation and examples.

/Chris

yihui yihui 3y ago

Hi,

This is pretty simple to decide: the two formats have different goals. Markdown aims to be simple, so it has to be very limited; LaTeX is a comprehensive typesetting toolset, which allows you to do anything but requires more efforts too. If you need advanced layouts, you definitely should go with LaTeX.

Originally posted on 2012-06-04 23:29:38

giscus-bot giscus-bot 3y ago
Guest *Chris* @ 2012-06-05 08:01:02 originally posted:

Ok, good. I hope knitr will continue to support LaTex. Thanks again for it.

yihui yihui 3y ago

Absolutely! I worked much harder on LaTeX than Markdown. You can compare the amount of code on them respectively: https://github.com/yihui/knitr/blob/master/R/hooks-md.R and https://github.com/yihui/knitr/blob/master/R/hooks-latex.R There is not much to do with markdown now, and there may still be issues to fix/improve with LaTeX.

Originally posted on 2012-06-05 15:10:40

giscus-bot giscus-bot 3y ago
Guest *JMol* @ 2012-06-05 17:48:53 originally posted:

Hello again, Yihui;

There is a problem with the R output, it produces a overfull hbox warning.
Example:
<<codigo1, size="small">>=
str(Orange)
@

yihui yihui 3y ago

That is because the output is too wide; you should either make the page margin smaller, or cut the output width somehow (may not be possible with str()).

BTW, you should use size='small' instead of size=small; see http://yihui.name/knitr/options

Originally posted on 2012-06-05 17:55:26

giscus-bot giscus-bot 3y ago
Guest *JMol* @ 2012-06-05 18:33:01 originally posted:

I am a newbie both in R and LaTeX, so, please, excuse my insolence, but is it not possible to find a solution. For example, redefining knitrout environment

ifdefinedknitrout
  renewenvironment{knitrout}{
    parnoindentbegin{minipage}{textwidth}
  }{
    end{minipage}
  }
else
fi

Generating new problems, it resolves partially the overfull problem.

Nevertheless, I can break the line manually.

giscus-bot giscus-bot 3y ago
Guest *HLM* @ 2012-06-14 22:32:26 originally posted:

Hi Yihui,

First of all, great work on the knitr package. Some truly impressive work there, thank you for developing the package.

I was wondering if there is a way in which its possible to integrate the 'manipulate' package or 'gWidgetsManipulate' package so that their outputs can be viewable/manipulable in the html/markdown output file, as I think that this would be extremely useful when developing reproducible  interactive research reports.I know that googleVis has some functionality that allows it to be integrated with knitr so that the outputs go into the html file by using options like results='asis' but googleVis is currently quite restrictive in its capabilities when using sliders for example.

If the package outputs of manipulate or gWidgetsManipulate hasn't quite been integrated yet, would it be possible to suggest a workaround for the time being that will allow it to be viewed?

Thanks

HLM

yihui yihui 3y ago

duplicate with http://stackoverflow.com/q/11042681/559676

Originally posted on 2012-06-15 22:17:29

giscus-bot giscus-bot 3y ago
Guest *JMol* @ 2012-06-15 11:45:23 originally posted:

Hello Yihiu again;
I am having a problem with Knitr, it breaks the code lines in the code output.

Minimal example:
<>=
vol_fvs_ni_bdft <- function(spp, dbh_in, ht_ft) {
bf_params <- data.frame(species = c("WP", "WL", "DF", "GF", "WH", "WC", "LP", "ES", "SF", "PP", "HW"))
}

... the code continue in the function

@

The code output is similar to:
vol_fvs_ni_bdft <- function(spp, dbh_in, ht_ft) {
bf_params <- data.frame(species = c("WP", "WL", "DF", "GF", "WH",
"WC",
"LP", "ES", "SF", "PP", "HW"))
}

Nevertheless, if I use render_listings() this problem doesn't occur.

yihui yihui 3y ago

The line is wrapped because it is too wide. You probably need a smaller width, e.g. options(width=40)

Originally posted on 2012-06-15 21:47:46

giscus-bot giscus-bot 3y ago
Guest *JMol* @ 2012-06-16 09:28:23 originally posted:

Thank you Yihui. Please forgive my stupidity, but I am not able to find the width option both in the package and chunk options.

yihui yihui 3y ago

I said options(width=40), so you should go to the documentation ?options instead of looking for that option in this package; options() is a function in base R.

Originally posted on 2012-06-17 17:37:59

giscus-bot giscus-bot 3y ago
访客 *Kelin Lu* @ 2012-06-21 08:28:08 写道:

你好,我下载knitr_0.6.tgz至Users/Me/Downloads/knitr_0.6.tgz ,接着在Terminal中输入install.packages('knitr', dependencies = TRUE),总是报这样的错:syntax error near unexpected token `"knitr",',请问这是为什么?

yihui yihui 3y ago

How about install.packages('knitr', dependencies = TRUE, repos = 'http://rforge.net')?

Originally posted on 2012-06-21 13:44:05

giscus-bot giscus-bot 3y ago
Guest *Dihua* @ 2012-06-21 19:01:36 originally posted:

Hi Yihui,

Congratulations on your new package. It is awesome. A qick question. I saw your acknowledgement included Andrew, is he the one who wrote Npp2R? I am a huge fan of that tool. Do you know by any chance he will write a similar package to link Knitr and notepad++? Thanks.

yihui yihui 3y ago

see, e.g. http://superuser.com/questions/404060/configuring-notepad-to-run-knitr2pdf

You can write to Andrew directly about this (yes, he is the author of NppToR). Or you can try RStudio, which is well integrated with knitr.

Originally posted on 2012-06-22 04:56:54

giscus-bot giscus-bot 3y ago
Guest *Jacob Wegelin* @ 2012-06-22 18:04:52 originally posted:

Dear Yihui,
I enjoyed your recent talk at the R Users' Conference in Nashville.
Where can one find an introduction to knitr, which explains the basics in a fairly systematic way?
It appears that one runs knitr by
(1) writing a text file, say "stuff.Rnw", that has the structure of a LaTeX *.tex file, complete with the LaTeX headers and the begin and end document commands,
(2) sourcing this file in a special way by typing knit("stuff.Rnw") at the R command line
(3) LaTeXing the resulting *.tex file which knitr creates.
But I do not understand the knitr code. What is the "<>=" type code? Does this define a label or a variable, analogous to "label{something1334211}" in LaTeX? Is it merely a comment? What is the "@" doing in your code?
Also, if I keep my *.Rnw files in some other directory, not the root directory where I am running R, can I get knitr to put the figures under the same directory? For instance, the following code
knit("Snapshots_Backup/toknit1.Rnw", output='Snapshots_Backup/toknit1.tex')does not work as I had hoped. The figure does not get put under the same directory and consequently LaTeX does not know where to find the figure.
Thanks

Jake

yihui yihui 3y ago

Please see if http://yihui.name/knitr/demo/minimal/ answers your questions. Basically you have to let R know where is the computer code and where is the text for human.

For the last question, I recommend you to work under the directory of Rnw files, and do not set the 'output' argument unless you really have to and you understand the consequences well; setting it to a file under another directory will not work since figure files are written to the current working directory.

Originally posted on 2012-06-22 20:39:45

giscus-bot giscus-bot 3y ago
Guest *Jacob Wegelin* @ 2012-07-11 15:47:27 originally posted:

Thanks for your reply.

In the past I have developed R code for a given project within a single function, which I keep editing and enlarging. I place readline() and/or error() calls inside this function, so that the execution will pause or stop before certain not-well-developed (draft) code below it is executed. Is there a way to do something like this in knitr? 

Below a toy example of the kind of function I mean. 

Below that is example.Rnw, which shows that neither readline() nor error() will pause or stop execution. Thus, suppose I made a mistake which generated huge, nonsense output (such as an infinite or huge loop with a cat() command inside it). This would just keep running and pouring text into in a huge example.tex file. Is there a way to pause or stop execution in knitr?    myreadline <-function (mytext = "enter to continue:")
   {
       cat(mytext)
       readline()
   }

fnJunk <-function(){

 First some stuff I want to run

   x<-rnorm(5)
   print(x)

 Now some stuff I don't want to run yet 

   myreadline("Are you ready to do a big simulation?")
   stop("Hey! No you aren't! This is enough!")
   for(thisdog in 1:1e5) {
   #  Some time-consuming calculation ...
      cat(thisdog, "n")
   }
}

%% LyX 2.0.3 created this file.  For more info, see http://www.lyx.org/.%% Do not edit unless you really know what you are doing.documentclass{article}usepackage[sc]{mathpazo}usepackage[T1]{fontenc}usepackage{geometry}geometry{verbose,tmargin=2.5cm,bmargin=2.5cm,lmargin=2.5cm,rmargin=2.5cm}setcounter{secnumdepth}{2}setcounter{tocdepth}{2}usepackage{url}usepackage[unicode=true,pdfusetitle, bookmarks=true,bookmarksnumbered=true,bookmarksopen=true,bookmarksopenlevel=2, breaklinks=false,pdfborder={0 0 1},backref=false,colorlinks=false] {hyperref}hypersetup{ pdfstartview={XYZ null null 1}}usepackage{breakurl}setlength{parindent}{0.0in}setlength{parskip}{0.1in}newcommand{superscript}[1]{ensuremath{^{textrm{#1}}}}newcommand{subscript}[1]{ensuremath{_{textrm{#1}}}}begin{document}<<setup, include="FALSE," cache="FALSE">>=# this is equivalent to SweaveOpts{...}opts_chunk$set(fig.path='figure/minimal-', fig.align='center', fig.show='hold')options(replace.assign=TRUE,width=90)@<<loaddata, echo="TRUE">>=x<-rnorm(5)print(x)myreadline <-function (mytext = "enter to continue:") {    cat(mytext)    readline()}myreadline("Do you really want to continue?")stop("Nooo! This is the start of a long simulation!")#Suppose this was long, not just 1 to 5.for( dog in 1:5 ){cat(dog, "n")}@EnD{document}

giscus-bot giscus-bot 3y ago
访客 *张无忌* @ 2012-07-02 10:14:53 写道:

您好!我用RStudio,如果选择sweave选项中的LaTeX editing and compilation选项下的多个选项就会出现Error running C:/CTEX/MiKTeX/miktex/bin/pdflatex.exe (exit code 1)错误。如果只选择第一项Clean auxiliary output after compile就没有问题。请问这是肿么回事呢?谢谢!

yihui yihui 3y ago

见统计之都上的回答。

——原帖发布于 2012-07-03 03:43:02

giscus-bot giscus-bot 3y ago
Guest *Ross Gayler* @ 2012-07-05 15:20:19 originally posted:

Hi Yihui. I have started to use knitr since it was incorporated in Rstudio, and I think it's great. I now do all my work as markdown documents.

Is it possible to tell knitr/tidy.source to respect line breaks in
R comments in a code chunk?  In my R code I have comments that specify the arguments to a function and I want each of the argument comments to start on a separate line. Elsewhere in the R code I have really long comments which need to be line-wrapped in the rendering to html.  I am using the Rstudio syntax-sensitive editor to enter and edit this R code. It preserves line breaks in R comments so I just manually insert line breaks to get the argument comments on separate lines. The editor also automatically wraps long comments - so the code looks the way I want it.When I render the markdown document with knitr, the argument comments that were on separate lines get run together.  Alternatively, if I set the tidy=FALSE chunk option, the argument comments get left on their separate lines but the long comments are not wrapped.Would it be possible to have a chunk option to respect line breaks in code comments? As an example, I have code like:

fun <- function(k, d){
  # Really, really long line that needs to be wrapped in final rendering and is displayed as wrapped in the Rstudio editor even though it is really one line 

  # Args:
  # k: (integer) Number of atomic items to generate
  # d: (integer) Dimensionality of VSA representations to generate
  #  

Returns:

(real k x d matrix) k randomly generated VSA representations

}

I want it to render like that except that the really long comment line should be wrapped (which means inserting a '#' at the start of the follow on line.tidy.source() does the comment wrapping I want, but runs together the consecutive, non-blank comment lines thus:

Args: k: (integer) Number of atomic items to generate d: (integer)

Dimensionality of VSA representations to generate

and

Returns: (real k x d matrix) k randomly generated VSA representations

Ross

yihui yihui 3y ago

An awkward way is to leave a blank line after each comment of arguments. All comments are wrapped in the units of paragraphs, so if a comment forms a paragraph, it will not be wrapped with the next/previous comments.

It is possible, though, to strop wrapping on certain types of comments, e.g. #' roxygen comments. If that is a desirable solution, I can implement it in the next version of formatR.

Originally posted on 2012-07-05 18:14:51

giscus-bot giscus-bot 3y ago
Guest *Ross Gayler* @ 2012-07-09 04:04:52 originally posted:

 Thanks, Yihui.  I had tried leaving a blank line and decided I didn't really like the way it looked when rendered.  I also tried adding two spaces at the end of the line (which works in the markdown text but not the embedded R chunks).

I'm not familiar with roxygen so can't really comment on the desirability of your suggestion.  I think the arguments would go something like this: Any mechanism would either be a very specific chunk option in knitr (e.g. respect.R.comment.break=TRUE) or be some sort of markup (which would be more flexible than a chunk option). If it is markup, it would either be some sort of pre-existing markup (e.g. #' roxygen comment) or some new markup that is specific to formatR.  All other things being equal I think I would prefer co-opting some pre-existing markup scheme rather than some new, ad hoc markup. (On the other hand, it probably makes little sense to drag in an isolated fragment of some pre-existing markup scheme, so you may have to support all the roxygen markup, for example.  Then I would be worried that the learning curve has been made even steeper. (That seems like a lot of effort just to get a line break.)

yihui yihui 3y ago

 OK, I think I will just stop wrapping roxygen comments, i.e. comments that begin with #'. I will not check the type of roxygen comments; as you said, that will make things complicated. The simple rules will be: # will be wrapped, and #' will not.

Originally posted on 2012-07-09 16:59:42

giscus-bot giscus-bot 3y ago
Guest *Ross Gayler* @ 2012-07-09 20:41:40 originally posted:

Thanks Yihui.
Ross

giscus-bot giscus-bot 3y ago
Guest *Jacob Wegelin* @ 2012-07-11 15:59:50 originally posted:

Dear Yihui:

I posted this query a moment ago with code, but the code was garbled on the website. Now the code is posted at a url given below. Is there a way to pause or stop execution in knitr?In the past I have developed R code for a given project within a single function, which I keep editing and enlarging. I place readline() and/or error() calls inside this function, so that the execution will pause or stop before certain not-well-developed (draft) code below it is executed. Is there a way to do something like this in knitr? At http://jacobwegelin.net/tmp/XieYihui/ you will find (1) A toy example of the kind of function I mean. (2) Example.Rnw, which shows that neither readline() nor error() will pause or stop execution. Thus, suppose I made a mistake which generated huge, nonsense output (such as an infinite or huge loop with a cat() command inside it). This would just keep running and pouring text into in a huge example.tex file. 
I would be interested in your thoughts on this. 

Thanks

Jake

giscus-bot giscus-bot 3y ago
Guest *wegelinjacob* @ 2012-07-11 18:31:07 originally posted:

One advantage to errors (calls to stop()) embedded in the code, is to build in guarantees, along the lines of 

stopifnot( is.numeric(x))

Is there a way to design a *.Rnw file so that it will  refuse to continue if the condition (such as a condition set up by stopifnot() ) is notsatisfied? 

yihui yihui 3y ago

If you have stop() in a function, knitr will not run the code after stop() in that function. You can easily verify this by, say,

f = function() {
  stop('no, stop here')
  for (i in 1:10000) cat(i, 'n')
}
f()

However, if stop() is in a separate expression, the code after it will still be executed because all the code is evaluated with try(). If you want a full stop in that chunk, see https://gist.github.com/2629886#file_knitr_error.rmd

Note there is NO option named 'error' in opts_knit; I have no idea on where you saw it. All possible package options were documented here: http://yihui.name/knitr/options#package_options

readline() is a very different problem; see a discussion here: http://stackoverflow.com/q/11248705/559676

In your case, I would suggest you use a global variable to control your code rather than readline(), e.g. run = TRUE/FALSE, which is a better programming practice, I believe; there is no guarantee for the output of readline() but global constants are easier to control and have guaranteed values.

Originally posted on 2012-07-11 20:35:08

giscus-bot giscus-bot 3y ago
Guest *wegelinjacob* @ 2012-07-11 23:06:43 originally posted:

Dear Yihui,

Thank you for your reply and the link on how to make knitr completely stop in case of an error.
But is the code on that page an example of an error that stops knitr? Is the code
x<-ff(1:10)
print(x)

supposed to return an error?

Is this the "ff" function which is in the "ff" library? I loaded that package and ran ff(1:10) and it did not return an error. What would ff(1:10) have to do with causing knitr to stop?
Thank you also for the link regarding conceptual incompatibility between readline() and knitr.
Jake

yihui yihui 3y ago

That is just a coincidence; ff was not supposed to be found because it was not defined in the document. All my examples are self-contained; if I need add-on packages, I will write library() explicitly in the source document.

Originally posted on 2012-07-12 00:56:49

giscus-bot giscus-bot 3y ago
Guest *wegelinjacob* @ 2012-07-11 19:05:02 originally posted:

Under http://yihui.name/knitr/options, we read that the following is apparently a "built-in option" for knitr. 

error: (TRUE; logical) whether to preserve errors (from stop()) (by default, the evaluation will not stop even in case of errors!!)

Does this mean that if 

opts_knit$get()$error==TRUE

then evaluation will not stop for errors?

Then the command 

opts_knit$set(error=FALSE)

will mean that in the future, evaluation will stop for an error? 

But the "example2" code posted at http://jacobwegelin.net/tmp/XieYihui/ shows that an error does not stop evaluation either way: with error set to TRUE or FALSE. 

How does one make knit() stop in case of an error?

yihui yihui 3y ago

knitr will not stop no matter if error=TRUE or FALSE; the only way to stop it is showed in this example via an output hook: https://gist.github.com/2629886#file_knitr_error.rmd

NOTE: 'error' is NOT an option in opts_knit; it is in opts_chunk. In that page, there are two objects opts_chunk and opts_knit, one controlling chunks, the other controlling package options.

Originally posted on 2012-07-11 21:28:03

giscus-bot giscus-bot 3y ago
Guest *wegelinjacob* @ 2012-07-13 16:46:43 originally posted:

Dear Yihui:

Thank you for this information.

I believe the following is common practice for programmers building code: to step through code; or, more crudely, to run code up to a certain point and have it either pause or die at that point. Then when the programmer is confident that the results are good up to that point, he/she moves the "die point" further down the code and tests it again.
I do not mean that the final code would behave like this, but that the programmer uses this technique when building it.

This is my object in asking about a way to make knitr stop or pause.

At http://jacobwegelin.net/tmp/XieYihui/ is an example, 2012-07-13Fri12h30m-a.Rnw, where I tested the

knit_hooks$set(error = function(x, options) stop(x))

approach.

This approach presents two difficulties.

(1) The resulting 2012-07-13Fri12h30m-a.tex lacks an end{document} line, so that it cannot be compiled in LaTeX without being edited first.

(2) More difficult, 2012-07-13Fri12h30m-a.tex also lacks a definition of the knitrout environment.

In fact, it lacks even more than this, as I discovered by trying the following workarounds:

(1) First I added by hand end{document} to the end of 2012-07-13Fri12h30m-a.tex.
(2) I added by hand

newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
to 2012-07-13Fri12h30m-a.Rnw.

But then I found also that definecolor was missing from 2012-07-13Fri12h30m-a.tex.
Ideally, one could place a command inside the *.Rnw so that the code below that command would not be run, but the code up to that command would run; and so that one could compile *.tex, i.e., see the results up to that point.

I use that practice continually.

I understand that in the final product, one does not want the *.Rnw to be interactive. But when building the code, I want to interact with it and, at every step, see how well I've done so far.

Do you see my point?

Maybe there is some other way to do this in the context of knitr, other than by putting an error or readline() inside the code?

Thanks again. I'd be interested in your thoughts on this.

Jake

giscus-bot giscus-bot 3y ago
Guest *wegelinjacob* @ 2012-07-13 17:47:11 originally posted:

I think the solution is to add "eval=FALSE" to the code chunks that one does not want to run yet. An example is posted under today's date at http://jacobwegelin.net/tmp/XieYihui/.
---------- Forwarded message ----------
Date: Fri, 13 Jul 2012 12:46:32

yihui yihui 3y ago

When you throw a real error during the compilation, the result tex document is not supposed to be a complete document (because the process was interrupted), and I guess it is not surprising that some stuff like end{document} or the preamble are missing.

Instead of being as "rude" as asking the program to die by knit_hooks$set(error = function(x, options) stop(x)), I'd rather suggest you ask the program to skip the evaluation of the rest of chunks by setting opts_chunk$set(eval=FALSE) in the chunk after which you want the rest of the code not to be evaluated any more. This guarantees the process finishes normally and quits gracefully after a certain chunk. Otherwise you have to wrestle with a broken output document endlessly.

If you want to interact with your code, you just need a decent editor like Emacs/ESS or RStudio, both of which recognize code chunks in an Rnw document and support running code chunks in an interactive R session. Even if you do not use these editors, there is still another approach to interact with code: http://yihui.name/knitr/demo/externalization/ You can write all your pure R code in a separate script, in which you are free to explore/diagnose your code; after you are done, just add a label to the code and reference it in your Rnw document.

Originally posted on 2012-07-13 17:50:21

yihui yihui 3y ago

See my reply below: http://yihui.name/knitr/#comment-587156836

Originally posted on 2012-07-13 17:58:15

giscus-bot giscus-bot 3y ago
Guest *wegelinjacob* @ 2012-07-13 18:23:03 originally posted:

From the new example I just placed at http://jacobwegelin.net/tmp/XieYihui/ under "2012-07-13Fri14h03m example", it appears that putting
opts_chunk$set(eval=FALSE)

anywhere inside a chunk has the following effect:

(1) if eval=TRUE is specified in the chunk header, then eval remains true in spite of the opts_chunk$set(eval=FALSE) statement.
(2) if eval is left at the default value, then

opts_chunk$set(eval=FALSE)

turns off evaluation for the entire chunk, not only the code after the opts_chunk statement.
Is this correct?

Thus, the code

opts_chunk$set(eval=FALSE)

seems no more flexible than simply putting "eval=TRUE/FALSE" into the header. Is this correct?

yihui yihui 3y ago

opts_chunk sets options globally in the whole document after that chunk, whereas options in the chunk header are local

There is no way to set an option in the middle of a chunk and let it affect the rest of the code in the chunk; all the code in a chunk is evaluated as a whole unit. If you want to change options in the middle, you have to separate the chunk into two.

Originally posted on 2012-07-13 19:25:26

giscus-bot giscus-bot 3y ago
Guest *wegelinjacob* @ 2012-07-12 15:34:25 originally posted:

When running a fairly small "try.Rnw" file, I find that knitr frequently hangs. Then R does not respond, and I have to kill the R job and restart it. Then the same file may run okay, but later knitr hangs again. Is this a known issue? It's really slowing me down to keep having to kill R and restart it. For instance, in the attached screen shot, you can see where it is hung at 92% evaluation of one of the chunks. The chunk is a call to ggplot. 

yihui yihui 3y ago

I have never seen that happens. Do you have a reproducible example? What is your sessionInfo() after library(knitr)?

Originally posted on 2012-07-12 16:38:17

giscus-bot giscus-bot 3y ago
Guest *wegelinjacob* @ 2012-07-13 19:53:14 originally posted:

Dear Yihui,

Thank you for your reply re: knitr hanging.

You suggested I send a reproducible example.

I cannot post the example publicly on the Web, because it depends on a dataset that has not been published. But if you would like to look at an example, I could show it to you individually.
The behavior is sporadic, but frequent enough to slow down my work and be a real annoyance. The same file might run on one occasion and then not run on another.
Just now, for instance, I got "try.Rnw" to run many times, and then it froze up again. Could this be caused by a memory leak? It tends to work for a while, then fail; then if I kill R and restart R, it works again.
Here is the sessionInfo() that you requested:

yihui yihui 3y ago

First I recommend you to update to the latest version of knitr (better to the development version: https://github.com/yihui/knitr#readme)

If the same thing still occurs, try to use some random data instead of the real data to make a reproducible example.

I do not know how you run knitr; ideally you should run it in a new R session each time instead of calling knit() in the same R session again and again.

Originally posted on 2012-07-13 20:22:39

giscus-bot giscus-bot 3y ago
Guest *Ikuyasu* @ 2012-07-12 21:41:25 originally posted:

Hi, Yihui. Thank you for doing all those work!

My question is on graphic images produced from Rstudio
markdown. I know that knitr produces png output for markdown graphics, but Rstudio
produces base64 image with html. This isn’t actually bad because you don’t have
to host png images to a location online like imgur, which remove another step
to publish your report. But the base64 image isn’t as nice as the anti-aliased
png image. Can you think of any way that base64 images produced by Rstudio  can appear better through knitr?

I want to be able to write markdown document on Rstudio,
knit html it, and copy the body part of produced html file and paste it on to a
blog post manually to produce my report on my blogger account.

giscus-bot giscus-bot 3y ago
Guest *Ikuyasu* @ 2012-07-12 21:53:46 originally posted:

I believe that that's the fastest way to publish online through blog system (blogger, wordpress etc) after creating a statistical report in R. If there is a way to link a post on Rpub to my blog entry, then this will be the fastest since Rstudio has a botton just to click to publish on Rpub.

yihui yihui 3y ago

To my understanding, base64 encoded images are just another type of representation of the original images, so there should not be quality loss. Do you have an example PNG that looks different when encoded?

Originally posted on 2012-07-12 23:46:40

yihui yihui 3y ago

I have seen quiet a few people trying to publish blog posts with knitr; you can search for "wordpress" or "blog" in the page http://yihui.name/knitr/demo/showcase/

For RPubs, you need to contact RStudio developers. I'm not the right person to talk to. You can, for example, suggest them make RPubs embeddable in other sites.

Originally posted on 2012-07-12 23:52:34

giscus-bot giscus-bot 3y ago
Guest *ikuyasu* @ 2012-07-13 21:14:00 originally posted:

Thank you for pointing out the direction that I can look at. I will keep you updated on what I find!

giscus-bot giscus-bot 3y ago
Guest *Loyolite270* @ 2012-07-23 05:01:54 originally posted:

Hi, Yihui
I got a problem, When i tried to run the below chunk , it throws an  error:
<<tidy=true>>=
print("Hello World")
@
Error in process_file(text, output) :
Quitting from lines 46-49: (v1.Rnw) Error in match(data$token, grammar_symbols$token) :
object 'grammar_symbols' not foundHow do i resolve it ?

giscus-bot giscus-bot 3y ago
Guest *Loyolite270* @ 2012-07-23 10:10:47 originally posted:

 The problem is resolved, i just updated the knitr package in R. Thank you very much for this wonderful package

giscus-bot giscus-bot 3y ago
Guest *Claas-Thido Pfaff* @ 2012-07-29 13:51:10 originally posted:

He Yihui. Thanks for this amazing R package. I tried it out for a while kniting my .Rnw files. I include som figures in them and also some plots through the chunks. I normally surround my included pictures with a tikz frame which is definded like:

 tikzstyle{pictureframe} = [rectangle, rounded corners, draw]

And then I do the following to surround my included figres:

begin{figure}[htbp]
   centering
      begin{tikzpicture}
         node[pictureframe]{%
            begin{minipage}{0.9textwidth}%
               begin{center}
                  includegraphics[width=.8linewidth]{figurename}
               end{center}
            end{minipage}
         }; 
      end{tikzpicture}
   captionbelow{catptiontext}
   label{fig:label}
end{figure}

So now I want to have the knitr included plots with the same look as the other included figures with the tikz frame around them.
How could I achieve this?

EDIT:

Already solved the problem.

Best Regards Claas

yihui yihui 3y ago

OK, I saw it on StackOverflow as well: http://tex.stackexchange.com/q/65497/9128

Originally posted on 2012-08-04 23:34:18

giscus-bot giscus-bot 3y ago
Guest *Maciej* @ 2012-07-30 09:43:15 originally posted:

I am wondering if problem with changing  default library is solved? I don't now how (or if) I can change it...:(

yihui yihui 3y ago

which problem are you talking about?

Originally posted on 2012-08-04 23:38:56

giscus-bot giscus-bot 3y ago
Guest *Ricardo* @ 2012-08-26 00:16:48 originally posted:

Hi Yihui!
 
    I came across an odd (at least for me!) problem. The following chunck gets evaluated just fine when I use "Run Current Chunk" in an .Rmd file:

library(rdatamarket)  

 BUT when I try KnitHTML, I get an error message saying   "## Error: there is no package called 'rdatamarket' "     (and of course the package IS installed)

I tried loading other packages like ggplot2 and tables, and both work without problems.

Is this a knitr, rdatamarket or RStudio problem??

yihui yihui 3y ago

Sounds like an RStudio problem: http://groups.google.com/group/knitr/browse_thread/thread/e1d6d71220bc5d06

Originally posted on 2012-08-26 01:17:05

giscus-bot giscus-bot 3y ago
Guest *Marcus* @ 2012-09-05 19:30:42 originally posted:

Hi Yihui,

thanks for this AWESOME piece of code! It helps my work a lot!!!

One small question regarding Python as an alternative engine: 

On my Mac I have several Python executables, a system one which I think is picked up by knitr, and versions 2.7 and 3.2 installed through homebrew into /usr/local/bin/... 

Is there a way to set the Python engine to work with some of these alternative Version?

Thanks a lot!

yihui yihui 3y ago

Great question. This part (foreign language engines) is still not mature in knitr, and I need to think about a more general design. For the time being, it is simply a system() call to python, so R picks whatever version that comes first in the PATH variable. If you want one specific version of python to be used, you can probably use Sys.setenv(PATH = "change.the.order.of.paths").

I'll consider generalizing the framework in the next version so it will be easier to configure the engines. That being said, you can always reset the default engines, e.g. knit_engines$set(python = your_own_function); see https://github.com/yihui/knitr/blob/master/R/engine.R

Originally posted on 2012-09-05 21:09:54

giscus-bot giscus-bot 3y ago
访客 *Henry Shang* @ 2012-09-11 05:47:07 写道:

谢益辉你好,
Ubuntu 12.04 64 lyx 2.0.4(ppa) texlive2012(ppa 或者 .ISO)R 2.15.1
问题:从texlive2009(ubuntu默认源)升级到texlive2012后的问题
只要添加Rnw(knitr)模块就发生编译错误:

  1. 紧急叫停

File ended while scanning use of kvsetkeys.
<*> MyFileName.tex
*** (job aborted, no legal end found)
视中文环境不同(导言区)kvsetkeys 或为其它值。

  1. 有时候,或许不同的文件,造成输出静默。即看似完成编译了,既不给出错误信息,又没有编译结果显示。去掉knitr既有输出。

不知道这三个冤家谁的问题?

yihui yihui 3y ago
  1. 能检查一下你的TeX源代码究竟有什么问题吗?
  2. 消息栏里没有任何消息?View-->View Messages

——原帖发布于 2012-09-11 21:40:35

giscus-bot giscus-bot 3y ago
访客 *Henry Shang* @ 2012-09-16 21:35:20 写道:

 我相信是LyX的问题。View-->View Messages里面仅仅提示预览pdf4时发生错误。经反复升降级Texlive,发现lyx问题越来越多了,甚至找不到xetex了。最后将~/.lyx文件夹删除即OK。显然LyX的重新配置命令存在缺陷。
最后给点鼓励的话,大家使用knitr感到很顺手,希望你继续努力!有这么給力的年轻人,不愁拿不下钓鱼岛。加油!

giscus-bot giscus-bot 3y ago
Guest *Gilbert Ritschard* @ 2012-09-12 10:11:50 originally posted:

Hi Yihui,

I have .Rnw file which starts with

  documentclass[xcolor={svgnames,table},trans]{beamer}

and when I knit it, knitr adds stuff  after the first "}" instead of after {beamer}. For example, with
option self.contained=FALSE, I get

   documentclass[xcolor={svgnames,table}usepackage{knitr},trans]{beamer}

Is there a way I can fix that?

Thanks for offering us this nice and powerful knitr tool.

Gilbert

yihui yihui 3y ago

You can probably try to move the xcolor options before documentclass, e.g.

PassOptionsToPackage{svgnames,table}{xcolor}
documentclass[trans]{beamer}

Originally posted on 2012-09-12 18:25:43

giscus-bot giscus-bot 3y ago
Guest *Marco Smolla* @ 2012-09-13 15:59:45 originally posted:

Hi Yihui!
Thanks for your work! I have some trouble with changing the code in- and output. The one thing is, that in input lines do not start with >,  the output lines however do start with an ##. Is there a way to get back to the standard that I see in the R console?
I also tried to change the font size of R code using DefineVerbatimEnvironment{Sinput}{Verbatim} ... but nothing changes in the PDF. I inserted it between the documentclass and begin{document}.
I use R 2.15.1 on a Mac 
Thanks for any suggestions.

marco

yihui yihui 3y ago

Read the manual please (Section 3.1): https://github.com/downloads/yihui/knitr/knitr-manual.pdf (also FAQ6 https://github.com/yihui/knitr/blob/master/FAQ.md)

Originally posted on 2012-09-13 16:26:29

giscus-bot giscus-bot 3y ago
Guest *Mat* @ 2012-09-21 19:41:00 originally posted:

Hi Yihui,
I'm not sure whether this query should be here or on the ggplot group or at RStudio, but I decided to start here!
I'm learning knitr and R and ggplot & RStudio all at once so this may be a simple beginner overload error and if so my apologies.

I am working through Hadley's book and am unable to get facet plots depicted in my output pdf. The facet plots work absolutely fine to RStudio 'plots' window, but do not come through into the pdf; what I get instead is a single plot like the 'no faceting' example. No error msg is provided to the pdf, nor to the RStudio 'compile PDF' window, nor is the log file form that compilation helpful.

The effect should be completely reproducible from this code from the book, using the diamonds dataset (section 2.6, page23)
   
    # no faceting
    qplot(carat, data = diamonds,
    geom = "histogram", binwidth = 0.1, xlim = c(0, 3))
   
    # faceting with original y-axis scale
    qplot(carat, data = diamonds, facets = color ~ .,
    geom = "histogram", binwidth = 0.1, xlim = c(0, 3))

    #faceting with y-axis scale replaced with density scale
    qplot(carat, ..density.., data = diamonds, facets = color ~ .,
    geom = "histogram", binwidth = 0.1, xlim = c(0, 3))

Thank you for making your knitr available; most of the time it seems some kind of miracle!
best
M
 

yihui yihui 3y ago

Sorry I cannot reproduce the problem. Attached is what I got from your code with the latest versions of all packages: http://i.imgur.com/BOPFZ.png

Originally posted on 2012-09-21 21:38:17

giscus-bot giscus-bot 3y ago
Guest *mat* @ 2012-09-24 14:16:35 originally posted:

 Yihui,
Thank you for looking at this. I loaded mgcv so our sessionInfo() call have the same output but I'm still not getting the nice output in your .png

Could the header on the .Rnw cause this effect? I'm using this one (amended from Coombes and Baggerly at MDAnderson).

% HEADER
documentclass{article}  % Use the standard article style by default
usepackage{graphicx}    %,color,fancyvrb}    % So we can include graphics easily
pagestyle{myheadings}   % put our own headings on all but the first page

% Reset the page size to use more of the paper
setlength{topmargin}{0in}
setlength{textheight}{8in}
setlength{textwidth}{6.5in}
setlength{oddsidemargin}{0in}
setlength{evensidemargin}{0in}

% meta-data
title{Learning ggplot}
markright{ggplot ch02.Rnw}   % this.Rnw NB, does not tolerate underscore use
author{mat}
date{21 sep 2012}

begin{document}
SweaveOpts{concordance=TRUE}
maketitle

<>=
opts_chunk$set(tidy = FALSE)
@f1ecdb63bdeec2a6b1134e2acf417c9b:disqus

Should I take this to stackoverflow?

giscus-bot giscus-bot 3y ago
Guest *mat* @ 2012-09-24 14:18:47 originally posted:

 I have no idea how that link icon got into the setopts chunk! (to clarify, it's not in the original .Rnw)
Thanks
Mat

yihui yihui 3y ago

Please post source code to pastebin.com or elsewhere and paste the link here. Disqus really sucks when dealing with program code. It has been driving me crazy.

Originally posted on 2012-09-24 16:45:19

giscus-bot giscus-bot 3y ago
Guest *Levi Waldron* @ 2012-09-30 22:26:49 originally posted:

Is there (or will there be?) any way to pass arguments to the R script, as with the "--args arg1 arg2" + commandArgs() method when using R CMD BATCH / R CMD Sweave, or as with the optparse R library?  This would allow the user to incorporate knitr in Make-like pipelines, where the script has dependencies and output files in addition to the report output.

yihui yihui 3y ago

You can pass arguments to R or Rscript directly as well, e.g.

R -e 'commandArgs()' --args a b c
Rscript -e 'commandArgs()' --args a b c
Rscript foobar.R --args a b c

Originally posted on 2012-10-01 00:14:39

giscus-bot giscus-bot 3y ago
Guest *Levi Waldron* @ 2012-10-01 02:51:54 originally posted:

 Thanks for your prompt reply, Yihui!  This is very convenient that the arguments passed to the knitr-invoking script are then just available to the .Rnw file.  Your suggestions do the trick, and also it is no problem to use optparse with either positional or flag arguments, for the knitr-invoking script.  Here is an example of a generic knitr-invoking script I am using, with a combination of flag arguments (for knitr input/output files) and positional arguments (passed on the the tangled R script). https://dl.dropbox.com/u/15152544/knit.R.  It is based on the script provided by http://www.tomtorsneyweir.com/research-notebook.  For dedicated scripts it may be more desirable to use all flag arguments, but this seems like a useful script to put in /usr/local/bin.

yihui yihui 3y ago

Thanks for sharing the script. I have a simplified version in the package as well: https://github.com/yihui/knitr/tree/master/inst/bin but I saw you said texi2pdf() did not work for you, so probably this script will not work for you either.

Originally posted on 2012-10-01 20:07:13

giscus-bot giscus-bot 3y ago
Guest *David Orme* @ 2012-10-04 14:18:16 originally posted:

Is there any simple way to reduce the spacing between input and output text in knitrout blocks? I think that the flushleft and verbatim environments both introduce padded space above and below. For verbatim, changing parskip to 0pt helps for the knitted output but the report text paragraphs are then crunched together. There is still some vertical space around the flushleft environments that aren't affected by parskip. I could simply put negative vspace at the end of each flushleft and verbatim, but I feel like I'm missing a more elegant mechanism.

The package is fantastic. Many thanks.

yihui yihui 3y ago

Perhaps these two examples can help: https://gist.github.com/2760395

Originally posted on 2012-10-04 16:36:40

giscus-bot giscus-bot 3y ago
Guest *David Orme* @ 2012-10-04 17:14:17 originally posted:

That's very helpful, thanks, and thanks for such a quick response. Sorry I didn't spot the examples. 

That provides a simple way of cutting down the space around the verbatim and before and after the whole knitrout chunk. There is still some vertical space between input and output lines that remains that doesn't seem to be affected by those lengths. It has to be something that flushleft triggers - if I replace everything in the flushleft environment with simple text, the space around it remains. 

yihui yihui 3y ago

The flushleft environment should not come unless you are using an old version of knitr, or have explicitly set opts_knit$set(use.highlight = TRUE).

Originally posted on 2012-10-04 18:11:25

giscus-bot giscus-bot 3y ago
Guest *Tianwaitian21* @ 2012-10-05 20:23:12 originally posted:

Impressive!

giscus-bot giscus-bot 3y ago
Guest *Chuck Up* @ 2012-10-20 06:07:57 originally posted:

Hello, thanks for the great package!

I have run into a couple issues using Knitr with an R Markdown page.

  1. The Markdown "###" for HTML headers are not getting translated, so the output file contains the "###" directly.

  2. When I attempt to execute R inline in a MathJax "$...$" block, the code is executed, but MathJax is not, and the output of R is HTML-ified.

Example:

$text{VaR}_{.01}^{msft} = r msft.VaRq01$

Which outputs:

${VaR}{.01}{msft} = -1.6937 × 104$

Your help will be greatly appreciated!

yihui yihui 3y ago
  1. I cannot reproduce it; do you have a space after ###?
  2. That is because the number was represented in scientific notation; I think you can use r I(knitr:::format_sci(msft.VaRq01, format="latex")) if you want scientific notation, otherwise just write r I(as.character(msft.VaRq01))

Originally posted on 2012-10-20 19:52:59

giscus-bot giscus-bot 3y ago
Guest *Chuck Up* @ 2012-10-21 13:10:27 originally posted:

Thanks for the quick reply.

For 1, putting a space corrected the issue, but this has not been required for other Markdown documents.

For 2, your suggestion worked.

yihui yihui 3y ago
  1. I see this is required according to the markdown documentation: http://daringfireball.net/projects/markdown/syntax#header

Originally posted on 2012-10-21 17:34:39

giscus-bot giscus-bot 3y ago
Guest *Chuck Up* @ 2012-10-21 18:15:12 originally posted:

Technically, it is not specified. Markdown's # headers are based on atx, which is defined here: http://www.aaronsw.com/2002/atx/intro

yihui yihui 3y ago

Well, first you should look at Markdown's syntax instead of Atx, and Markdown has showed examples where you can see the spaces after the hashes; secondly, even if you insist on looking at Atx, see line 47 of its source code http://www.aaronsw.com/2002/atx/atx.py and it will be clear that a space is required. BTW, I'm not the right person to argue with in terms of the Markdown syntax; that is not something I invented.

Originally posted on 2012-10-21 19:16:34

giscus-bot giscus-bot 3y ago
Guest *Mk9y* @ 2012-10-29 19:30:39 originally posted:

The following code:
<>=
add <- read.table('http://www.uvm.edu/~dhowell/methods7/DataFiles/Add.dat', header = TRUE)
add$CaseNum <- factor(add$CaseNum)
library(car)
add$Gender <- Recode(add$Gender, " 1 = 'Male'; else = 'Female' ", as.factor.result = TRUE)
add$Repeat <- Recode(add$Repeat, " 1 = 'RepeatedGrade'; else = 'DidNotRepeatGrade' ", as.factor.result = TRUE)
add$EngL <- Recode(add$EngL, " 1 = 'CollegePrep'; 2 = 'General'; else = 'Remedial' ", as.factor.result = TRUE)
add$EngG <- Recode(add$EngG, " 4 = 'A'; 3 = 'B'; 2 = 'C'; 1 = 'D'; else = 'F' ", as.factor.result = TRUE)
add$SocProb <- Recode(add$SocProb, " 0 = 'No'; else = 'Yes' ", as.factor.result = TRUE)
add$Dropout.f <- Recode(add$Dropout, " 1 = 'Dropped'; else = 'DidNotDrop' ", as.factor.result = TRUE)
@Producesbegin{knitrout}
definecolor{shadecolor}{rgb}{0.749, 0.937, 1}color{fgcolor}begin{kframe}
begin{alltt}

add <- hlfunctioncall{read.table}(hlstring{"howell.txt"}, header = TRUE)
add$CaseNum <- hlfunctioncall{factor}(add$CaseNum)
hlfunctioncall{library}(car)
add$Gender <- hlfunctioncall{recode}(add$Gender, hlstring{" 1 = hlstring{'Male'}; else = hlstring{'Female'} "}, as.factor.result = TRUE)
add$Repeat <- hlfunctioncall{recode}(add$Repeat, hlstring{" 1 = hlstring{'RepeatedGrade'}; else = hlstring{'DidNotRepeatGrade'} "}, 
       as.factor.result = TRUE)
add$EngL <- hlfunctioncall{recode}(add$EngL, hlstring{" 1 = hlstring{'CollegePrep'}; 2 = hlstring{'General'}; else = hlstring{'Remedial'} "}, 
       as.factor.result = TRUE)
add$EngG <- hlfunctioncall{recode}(add$EngG, hlstring{" 4 = hlstring{'A'}; 3 = hlstring{'B'}; 2 = hlstring{'C'}; 1 = hlstring{'D'}; else = hlstring{'F'} "}, 
       as.factor.result = TRUE)
add$SocProb <- hlfunctioncall{recode}(add$SocProb, hlstring{" 0 = hlstring{'No'}; else = hlstring{'Yes'} "}, as.factor.result = TRUE)
add$Dropout.f <- hlfunctioncall{recode}(add$Dropout, hlstring{" 1 = hlstring{'Dropped'}; else = hlstring{'DidNotDrop'} "}, 
       as.factor.result = TRUE)
end{alltt}
end{kframe}
end{knitrout}This rersults in the following console error:! Undefined control sequence.

'

            Male'

l.1431 ...g{'Male'}; else = hlstring{'Female'} "}

                                                  , as.factor.result = TRUE)

yihui yihui 3y ago

Duplicate with yihui/knitr#413

Originally posted on 2012-10-29 20:21:13

giscus-bot giscus-bot 3y ago
Guest *Jinsong Zheng* @ 2012-11-02 15:59:01 originally posted:

Hi Yihui,

I found a small bug related to memory allocation. This is my example:

documentclass{article}
begin{document}
<>=
sessionInfo()
memory.limit()
dat <- matrix(runif(10*10000), nrow=10000,ncol=10)
@
<>=
gcinfo(TRUE)
pairs(dat)
gcinfo(FALSE)
@google-8cdeb5eca08c47a693eab27d323387a2:disqus
end{document}

I got the following messages(if I raise the memory limit memory.limit(size=2047), then there will be a error -"can not allocate vector of size..".):

Garbage collection 275 = 113+17+145 (level 2) ...
18.1 Mbytes of cons cells used (63%)
1434.5 Mbytes of vectors used (94%)
Warning in recordPlot() :
Reached total allocation of 1535Mb: see help(memory.size)
Garbage collection 276 = 113+17+146 (level 2) ...
12.7 Mbytes of cons cells used (44%)
773.1 Mbytes of vectors used (51%)
Garbage collection 277 = 113+17+147 (level 2) ...
18.5 Mbytes of cons cells used (59%)
1472.6 Mbytes of vectors used (92%)
Warning in recordPlot() :
Reached total allocation of 1535Mb: see help(memory.size)If I run the R code in the R-console, there is no memory problem. Furthermore, there is no warnings or errors in Sweave as well. Some further information about my R:

sessionInfo()

R version 2.15.1 (2012-06-22)

Platform: i386-pc-mingw32/i386 (32-bit)

locale:

[1] LC_COLLATE=German_Germany.1252

LC_CTYPE=German_Germany.1252

[3] LC_MONETARY=German_Germany.1252 LC_NUMERIC=C

[5] LC_TIME=German_Germany.1252

attached base packages:

[1] stats

graphics
grDevices utils
datasets
methods
base

other attached packages:

[1] knitr_0.8

loaded via a namespace (and not attached):

[1] digest_0.5.2

evaluate_0.4.2 formatR_0.6
plyr_1.7.1

[5] stringr_0.6.1

tools_2.15.1
memory.limit()

[1] 1535

Could you check it? Thanks a lot in advance.

yihui yihui 3y ago

Thanks for the report. I kind of expected that. In this case, recordPlot() can no longer record the plot as displaylist because it is too big. Before I start thinking of a solution, may I ask if you really need such a huge plot? I mean scatter plots of a huge number of points are often not useful because you cannot really see anything in the plots.

Originally posted on 2012-11-02 16:16:34

giscus-bot giscus-bot 3y ago
Guest *Jinsong Zheng* @ 2012-11-05 13:04:34 originally posted:

Many thanks for your reply.  I use pair plot to check the correlation structure with low panel of correlation value  and upper panel of contour plots.  It occurs the same problem. I use  scatter plots  here as an illustration to show that there may be a problem by using pairs().  Anyway, I can run this part in sweave or R-console.  Thanks again.

yihui yihui 3y ago

I just wrote an example for this case which works fine for me: https://github.com/yihui/knitr-examples/blob/master/056-huge-plot.Rmd

Originally posted on 2012-11-05 19:31:01

giscus-bot giscus-bot 3y ago
Guest *Abd Rahman* @ 2012-11-15 07:22:46 originally posted:

Dear Yihui,
Very new to this interesting application R Studio and knitr package. I have a basic question. 

I'm trying to inserrt the R logo using the following command, but it doesn't work. 

R logo

It generates a box with ? symbol inside instead. Appreciate any response.

ARK

yihui yihui 3y ago

Does figure/r-logo.png exist at all? I guess not.

Originally posted on 2012-11-15 14:57:19

giscus-bot giscus-bot 3y ago
Guest *Hank Stevens* @ 2012-11-15 12:36:53 originally posted:

I collaborate with folks who do not have Latex on their machines (Windows). Would knitr allow them to generate PDF from Sweave, or - as I assume - do they they need LaTex on their machines?

Aside from HTML, is there any way for Windows folks - without LaTex - to automatically generate reports as we do with Sweave and Latex? I looked at latex2rtf as a possibility, but I assume it requires a version of LaTeX.

yihui yihui 3y ago
  1. Yes, they do need LaTeX, but I guess installing MikTeX is easy, and it would be much more painful if they do not know LaTeX at all;
  2. You can use R Markdown (.Rmd) to generate a Markdown document (.md), then use pandoc to convert it to many other formats including Word;

Originally posted on 2012-11-15 15:00:54

giscus-bot giscus-bot 3y ago
Guest *Mons Magnusson* @ 2012-11-30 09:27:16 originally posted:

Hi Yihui!

I use knitr in R-Studio and pandoc. I use pandor to produce pandoc markdown tables in R-studio but it does only seems to work with simple pandoc tables and not "grid" tables for example, is there something I've done wrong or is it simply not implemented in knitr/Rmarkdown yet?

Regards
Måns

yihui yihui 3y ago

It is a matter of syntax. The biggest pain of markdown is that there are tons of variants of markdown. For now, you have to stick to one of them, either pandoc's markdown, or R's markdown.

Originally posted on 2012-11-30 16:29:37

giscus-bot giscus-bot 3y ago
Guest *Aureincm* @ 2012-11-15 17:07:20 originally posted:

Hi ,

trying  to use your (apparently) amazing package (thanks for developing it by the way!), I came across this error when trying to install it:

install.packages("knitr", lib="/Applications/http://RStudio.app/Contents/Resources/R/library")
Warning in install.packages :
  package ‘knitr’ is not available (for R version 2.13.0)

I am running R 2.13.0 using R.studio (version 0.96.330) under Mac OS X 10.8.
Do you have any idea what is going wrong?

Thanks
 - Aure

yihui yihui 3y ago

Yes, please update R; knitr requires R >= 2.14.1. Note the current version of R is 2.15.2.

https://github.com/yihui/knitr/blob/master/FAQ.md

Originally posted on 2012-11-15 17:32:43

giscus-bot giscus-bot 3y ago
Guest *Aureincm* @ 2012-11-15 23:12:10 originally posted:

Silly me.....
Thanks for you QUICK answer!!!  Everything seems to be working fine now!!
Can't wait to use your package!!! And as a knitter.. I  have to say, I LOVE its name ;-)
Thanks 
 - Aure

yihui yihui 3y ago

You are not the only real knitter who uses knitr, and I'm always happy to know that this is a neat name for real knitters. Perhaps someone can draw knitting patterns using R some day :)

Originally posted on 2012-11-16 01:29:32

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-19 21:33:13 originally posted:

I'm building a document in LaTeX and using Knitr to insert ggplot2 objects, If i want to create a scatterplot, where, as part of this the plot labels are actual bibliography references by number (from a bibtex database), is this possible? Can you please point me in the right direction? 

The obvious problem, is that in LaTeX, references are parsed as bibtex keys via the cite{key} command, when the document is parsed twice, these are replaced by numbers (or the format defined by the user) which correlate to the order that the actual bibliography is assembled. It is these ordered numbers which are of interest to me, to insert, for instance, as labels in a ggplot2 object.

To put this in context, I'm writing a thesis, and as part of the literature review,  need to create a plot to summarize the works of say 20-30 previous publications. Each of these publications/authors need to be identified on the plot and correlated to specific records in the bibliography/references section.

yihui yihui 3y ago

It is really a challenging problem but not impossible. Here is my example:  https://github.com/yihui/knitr-examples/blob/master/064-bib-plot.Rnw

Note you need to install the tikzDevice package from R-Forge.

Originally posted on 2012-11-20 20:18:10

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-21 00:56:06 originally posted:

Fantastic. That works perfectly, also needed to install the R filehash package in order to get it to work.

I'm getting less issues with image scaling too now (better consistency), since the dev='tikz' package is being used.

Is there a way to set the fig.height and fig.width values as default values, once at the beginning of the document, so that I can keep the same across multiple plots on different pages without having to specify on a individual plot basis?

This package is fantastic, it is going to save me so much time on the whole.....

Cheers.

yihui yihui 3y ago

See http://yihui.name/knitr/options; use opts_chunk$set()

Originally posted on 2012-11-21 02:27:45

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-21 02:39:25 originally posted:

'cite{xyz}' works perfectly but if I use 'citep{xyz}' or 'citet{xyz}' as per natbib, it throws error. Any ideas?

yihui yihui 3y ago

You need to add natbib to tikz metric packages; see ?tikzDevice

For example,

library(tikzDevice)
options(tikzMetricPackages = c(getOption('tikzMetricPackages'),
'usepackage[authoryear]{natbib}'))

Originally posted on 2012-11-21 04:17:36

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-21 00:55:05 originally posted:

Doesn't seem to be a way to delete post.

yihui yihui 3y ago

What does that mean?

Originally posted on 2012-11-21 02:29:28

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-21 04:23:45 originally posted:

I accidentally posted a new post, when what I wanted to do was reply to an old one. There didn't seem to be a button to delete the error/mistake post, only edit what was already submitted provided one doesn't simply delete the entire paragraph leaving an empty post, so I had to type something trivial and re-submit where it was supposed to go.

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-21 04:06:16 originally posted:

How can I use textwidth or equivalent in the BODY of a chunk?

Have used it successfully via arguments via xyz='textwidth', but it doesn't seem to be working in the body.

Specifically, Lets say I define my own parameter such as:

defmywidthparm{6}
defmyheightparm{4.5}

The below chunk throws error.
<<defaultfiguresizes,eval=true,echo=false>>=
library(knitr)
W <- 'mywidthparm'
H <- 'myheightparm'
opts_chunk$set(fig.width=W, fig.height=H)
@

However, the below code works fine.
<<defaultfiguresizes,eval=true,echo=false>>=
library(knitr)
W <- 6
H <- 4.5
opts_chunk$set(fig.width=W, fig.height=H)
@

In context, I want to refer to the same parameters which control width of both 1. plots and 2. graphics (image) objects.

Cheers.

yihui yihui 3y ago

use out.width and out.height instead; see http://yihui.name/knitr/options again

Originally posted on 2012-11-21 05:24:49

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-28 23:26:42 originally posted:

Hi Yihui,

out.width and out.height aren't doing what is expected. I have read the link above, but cant seem to get it to work.

defmywidth{500px}
defmyheight{400px}
<<defaultfiguresizes,eval=true,echo=false>>=
W <- 'mywidth'
H <- 'myheight'
opts_chunk$set(out.width=W, out.height=H)
@

It i use fig.width or fig.height, with explicit numerical values INSIDE the block, works fine, but the above has no effect. Can you see anything obvious that I am doing wrong?

Cheers.

yihui yihui 3y ago

It does work for me. Can you take a look at the tex file? If you can see width=mywidth,height=myheight after includegraphics, it is your LaTeX problem instead of knitr's. And you need to keep in mind that the unit px may not be supported by LaTeX; Google search gives me this http://tex.stackexchange.com/a/41371/9128

Originally posted on 2012-11-29 03:18:17

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-29 03:39:05 originally posted:

There is no includegraphics in the 'tex' file. Below is the relevant part. This TEX file comes from the relevant .Rnw file, which contains the actual code, being a call to R to plot something. The object DOES plot, but the out.width and out.height have apparent bearing on the size as it appears in the final typset .pdf. If I use fig.width and fig.height the plot gets inserted at the right size.

begin{knitrout}
definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}input{figure/MYPLOT.tikz}
end{knitrout}

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-29 03:40:03 originally posted:

*In the below post meant to say *NO apparent bearing....

yihui yihui 3y ago

So your example code did not tell me you were using the tikz device, which makes this a completely different story. Tikz graphics cannot be rescaled in the usual way. Search for resize.width in http://yihui.name/knitr/options

Originally posted on 2012-11-29 20:22:18

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-29 23:18:13 originally posted:

Apologies, should have made made that clear. Based on my other post, where you suggested to use library(tikzDevice) to get citations/references into the plot area, I assumed that was understood.

resize.width and resize.height screw up the scaling.

out.width and out.height do a perfect job, I just cant use declared variables outside of the scope of a chunk, declared elsewhere in the LaTeX document, as per the above post.

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-21 16:28:15 originally posted:

Got another sticky one...

Is it possible to use LaTeX equation output (ie the output between begin{equation} and end{equation}, you know, the pretty formulas} to replace items in a ggplot2 legend or elsewhere on a ggplot R plot?

yihui yihui 3y ago

Why use the equation environment? I mean you can change the legend labels (write $$ there); this trick was extensively used in the book "The Analysis of Data", e.g. http://theanalysisofdata.com/probability/2_2.html

Originally posted on 2012-11-21 17:15:43

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-22 00:51:50 originally posted:

Thanks. Feel a bit dumb but Works perfectly.

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-21 16:37:37 originally posted:

On a light-hearted topic, in reading the above, under the misc section, RE the origins of the name 'knitr', I personally never saw the connections you mentioned (with weave and neatr), to me the name 'knitr' really implies 'Knit-R', as in, stitching R with other things...

yihui yihui 3y ago

You are right. This is a long history (WEB, Noweb, weave, tangle, literate programming, Sweave = S + weave). As time goes by, people will never understand knitr is neater than "what" and there will be packages neater than knitr :)

Originally posted on 2012-11-21 17:00:26

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-21 17:04:47 originally posted:

Is it appropriate to make some reference to string theory?

giscus-bot giscus-bot 3y ago
Guest *ADPowers* @ 2012-11-21 17:06:06 originally posted:

People should just 'cotton-on'

Sign in to join the discussion

Sign in with GitHub