yihui / knitr-examples Goto Github PK
View Code? Open in Web Editor NEWA collection of knitr examples
A collection of knitr examples
Hi,
this concerns using a custom powerpoint template. Steps to reproduce
This results in a corrupted pptx with the error "Powerpoint found a problem with content in ...".
Edition Windows 10 Business
OS build 19045.3448
R version 4.3.0 (2023-04-21 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19045)
---
title: Results
author: Rewoso
date: "`r format(Sys.time(), '%d/%m/%y')`"
output:
officedown::rpptx_document:
reference_doc: test-template - Copy.pptx
editor_options:
chunk_output_type: console
---
```{r, setup, echo=0, warning=0, message=0}
pacman::p_load(ggplot2)
knitr::opts_chunk$set(
results = "asis",
echo = FALSE,
warning = FALSE,
error = FALSE,
message = FALSE
)
```
## Test
```{r, fig.width=10, fig.height=4}
ggplot(iris) + geom_histogram(aes(Sepal.Length))
```
Attempting to compile this Rnw to PDF in RStudio 0.98.1056 fails with the error:
Writing to file 021-ggplot2-geoms.tex
Processing code chunks with options ...
1 : echo keep.source term verbatim (label = setup, 021-ggplot2-geoms.Rnw:8)
2 : echo keep.source term verbatim (label = write-examples, 021-ggplot2-geoms.Rnw:15)
Error: at 021-ggplot2-geoms.Rnw:26, character argument expected
Execution halted
R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Removing the line:
\Sexpr{knit_child(text = unlist(ex), quiet = TRUE)}
causes it to compile successfully.
Here's my sessionInfo()
:
locale:
[1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252 LC_MONETARY=English_Australia.1252 LC_NUMERIC=C
[5] LC_TIME=English_Australia.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] knitr_1.6.21 ggplot2_1.0.0
loaded via a namespace (and not attached):
[1] colorspace_1.2-4 digest_0.6.4 evaluate_0.5.5 formatR_1.0 grid_3.1.1 gtable_0.1.2 MASS_7.3-35 munsell_0.4.2
[9] plyr_1.8.1 proto_0.3-10 Rcpp_0.11.3 reshape2_1.4 scales_0.2.4 stringr_0.6.2 tools_3.1.1
I think it would be interesting to add a workflow in knitr-example that would trigger a new run of "Check-knitr-example" workflow in knitr repo when we have a new commit to master in this repo.
That way when we push a fix because something changed in knitr we could have the workflow re-run automatically.
Should be possible using
Hi
I've recently started to use knitr to compile latex documents.
<<tidy=TRUE>>=
#Q1b
rep(11:15, times = c(1,5,2,2,1)) # the times vector tells us how much for each of respective numbers 10 to 15 we want repeat.
@
I have fairly long comments because I'm trying to explain myself, but whenever the PDF is compiled. My comments are always cut off. Is there a way I can include my comments? I tried tidy=TRUE but nothing happened.
Thanks
matplotlib plots don't seem to be working.
I've been working on a parser for RMarkdown documents using Boost's Spirit X3 library. I'm currently using the Rmds available within this repo as a test set to make sure my code is working correctly.
In running my parser I've come across some potential typos and inconsistencies in syntax in the example documents and I wanted to clarify.
Chunk begins with 3 backticks and ends with 4, it seems like knitr is not checking for balance between the backticks as long as there is >= 3. Oddly, for the document below RStudio gives me an unexpected token error via the linter but I don't see a similar error when creating my own test documents.
There are a couple of examples where there are two sequential chunks where the first is missing its closing backticks, but it is immediately followed by the start of a new chunk. The documents compile correctly but this seems wrong to me.
There are several documents where the chunk has a format that looks like
```{engine, name, opt=val}
my understanding is that the prefered format should be
```{engine name, opt=val}
is the former syntax allowable?
Hello,
I followed the example and type the following in the rmarkdown file,
{r test-haskell, engine='haskell', engine.path="C:\Program Files\Haskell Platform\8.6.5\bin\ghc.exe", cache=TRUE}
[x | x <- [1..10], odd x]
And the return is the following
Error: unexpected '[' in "["
Can you help for how to get it run?
Thanks
Hello Yihui,
I adore knitr. Just one question to line 46. If I change out.width to e.g. '0.3\linewidth' the graphs become smaller, but they are plotted on the left margin of the page. How I can put them in the center of the page again?
Thank you very much for helping me out. I couldn't find a solution...
Sincerely yours,
Magnus
Are the integration tests on branch still valid ?
https://github.com/yihui/knitr-examples#integration-tests
Following changes in knitr
yihui/knitr@16493ec#diff-6ac3f79fc25d95cd1e3d51da53a4b21b939437392578a35ae8cd6d5366ca5485
I am not so sure this is possible to create a branch in a fork to get the test done.
It seems integration will happen only on master now. Example in one of the last travis jobs:
https://travis-ci.com/github/yihui/knitr/jobs/421565801
I think we won't be needed that at the examples will be checked for each PR (following yihui/knitr#1920), but we would still need a mechanism for someone to add a tests in knitr-examples and have it check when doing a knitr PR.
This issue is
--no-install-recommends
for other packages(Issue split off from #33)
The stitch()
function doesn't currently support chunk options, just chunk names. @yihui requested that I open an issue to serve as a reminder.
I wasn't necessarily advocating that stitch()
implement chunk options. Let me play the devil's advocate for a moment. It may be preferable to keep things as you have them, and avoid adding complexity to a derivative function like stitch()
because,
As long as the documentation redirects the user to the appropriate function, I don't have a strong opinion either way.
I cloned the repo and executed ./knitall
but the output for the 117-messages.md
differs from the output in the repo in that the messages are separated even though the appendLF
flag is set to FALSE
.
Any idea as to what is the cause of this?
R version 3.4.1 (2017-06-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: OS X El Capitan 10.11.6
A message in message(..., appendLF = FALSE)
will be merged with the next adjacent message:
f3 = function() {
message("Hello ", appendLF = FALSE)
message("World!")
}
f3()
## Hello
## World!
Quitting from lines 62-62 (007-text-output.Rmd)
Error in parse(text = x, srcfile = src) :
<text>:10:0: unexpected end of input
8: ##
9: ## dnorm(0)
^
Calls: <Anonymous> ... evaluate -> parse_all -> parse_all.character -> parse
Execution halted
Hi
I have recently typed up a knitr document in Lyx on windows 10. The knitr functions are working perfectly fine and all the chucks evaluated fine in the PDF on Windows.
I then saved all my work and copied the directory to my linux (Ubuntu) laptop which also has lyx installed with knitr enabled. However when I tried reproduce the pdf file on Lyx in ubuntu it gave me this error
I was wondering, why is happening. I have tested knitr on a new file created in Lyx on ubuntu and it works fine, evaluates the chunks, no issues at all.
I like to simultaneously be able to work on windows/ubuntu, hence I find it useful if I have continue to edit and reproduce knitr documents on both using Lyx.
Thanks
Rahul
Calling brew("004-minimal.brew")
returns:
We know the value of pi is , and 2 times pi is .
The brew syntax in knitr is similar to the brew package, but all kinds of
syntax in the brew package will be treated in the same way in knitr: they are
nothing but inline R code.
You can write a number as , or 1.234, or .
The last line seems not as was intended? Is the "brew" language different between knit()
and brew()
?
I am a knitr beginner and I am trying to learn by running .Rnw examples and looking at the resulting PDFs (and reading relevant knitr and R documentation for each example). Thanks a lot for providing so many examples both on github and on the knitr page! Really helpful.
I have proceeded like this: Click on an example, e.g. https://github.com/yihui/knitr-examples/blob/master/002-minimal.Rnw, click on "Raw", and save as a .Rnw file. I open the file in RStudio, and click on compile PDF. The examples I have tried so far runs just fine.
However, when I tried to compile PDF from 020-for-loop.Rnw an error error is returned: 'Error in readLines(if (is.character(input2)) {'. The readme says that the examples could be "for my own test purpose". Being a beginner it is unfortunately difficult for me to tell if something is missing in the code (i.e. the example is not supposed to be a self-contained example, but rather code used for test purpose), or if something is missing in my brain.
Is there a way to find out which examples that are self-contained and which examples that needs additional input to run?
Thanks a lot for your great work with knitr!
Best regards,
Henrik
@yihui Is it possible to create a stitch example (like example 102), but with chunk options? I haven't seen a complete stitching example on any blog, in this repository, or in the demos in the knitr's inst/examples.
Stitching is working for me if I don't divide by chunks, but I'm doing something wrong when I either (a) separate them into chunks, or (b) set options (like the figure path, or the figure width).
The chunks are recognized with I replace '+
with ## @knitr
. But the relative paths for the images don't work, so they're not being embedded in the html as base64.
An example might illuminate my mistakes (and hopefully helps others). Tell me if you want this posed to Stack Overflow instead of a GitHub issue.
knitr::stitch_rmd(
script="./Manipulation/stitch-test.R",
output="./Manipulation/StitchedOutput/stitch-test.md"
)
This is one attempt, which was modified from the existing stitch example.
## title: A test script for the function stitch()
## author: Yihui Xie
# This chunk mimics the *spinning* example at https://github.com/yihui/knitr/blob/master/inst/examples/knitr-spin.R#L6-L8
#+ setup, include=FALSE
knitr::opts_chunk$set(fig.path='./stitch_output')
#+ generate_scores
set.seed(1121)
(x=rnorm(20))
#+ calculate_descriptives
mean(x);var(x)
#+ plot_box, fig.width = 2
boxplot(x)
#+ plot_histogram, fig.width = 6
hist(x,main='')
FYI, minor, but just noticed:
> knitr::knit("003-minimal.Rhtml")
Quitting from lines 54-57 (003-minimal.Rhtml)
Error in library(rgl) : there is no package called 'rgl'
despite
<!--begin.rcode
knit_hooks$set(rgl = hook_rgl) # set up the hook first
end.rcode-->
<!--begin.rcode fancy-rgl, rgl=TRUE, fig.align='center', fig.width=4, fig.height=4, warning=FALSE
if (require('rgl')) {
demo('bivar', package='rgl', echo=FALSE)
par3d(zoom=.7)
}
end.rcode-->
The error occurs because hook_rgl()
is still called;
> traceback()
12: stop(txt, domain = NA)
11: library(rgl)
10: (function (before, options, envir)
{
library(rgl)
if (before || rgl.cur() == 0)
return()
name = fig_path("", options)
...
> packageVersion('knitr')
[1] '1.5.26'
I am using the function of 'include_graphics' to embed some local image,
it works for knitr_1.12.3, and R3.2.3, but when I update my knitr to 1.4 and R3.3, it not works, the problem may due to chinese words in the image path, how can I set the encoding ?
Hi,
Tx for your great work, I have been using knitr with latex for a while now I am switching to markdown. The issue I have is with child docś and child_knitr.
I have a R script that reads data on which I want to do automatic processing (e.g. determine if varabels are numeric or categoric and make a plot or stats based on type of variable in dataset) fully automatic. In the example below I have a list of numeric variable names and for each name in the dataset I want to make a plot and print some stats.
Like your example 020 for loop but then in markdown instead of sweave
Now with Latex the below chunk works but I cannot seem to get it running using markdown.
Please advise
## @knitr run-numeric-lx
out = NULL
for (i in c(1:num_vars)) {
out = c(out, knit_child('da-numeric-template.Rnw', sprintf('da-numeric-template-%d.txt', i)))
}
## @knitr run-numeric-md
out = NULL
for (i in c(1:num_vars)) {
out = c(out, knit_child('da-numeric.Rmd',sprintf('da-numeric-template-%d.txt', i)))
}
tx
hugo
Oops, sorry my misunderstanding - single chunk options don't need comma-separation from the {r
, never mind
Is there an example on how to use the GO language engine? If not, would it be possible to add one?
The language engine itself is already available, I'm just not too sure how to load and run.
Thanks
Here is the diff after having upgraded to rgl 0.103.5
\hlstd{knit_hooks}\hlopt{$}\hlkwd{set}\hlstd{(}\hlkwc{rgl} \hlstd{= hook_rgl)}
\hlkwd{head}\hlstd{(hook_rgl)} \hlcom{# the hook function is defined as this}
\end{alltt}
\begin{verbatim}
-##
-## 1 function (before, options, envir)
-## 2 {
-## 3 if (before) {
-## 4 newwindow <- options$rgl.newwindow
-## 5 if (!is.null(newwindow) && newwindow)
-## 6 open3d()
+##
+## 1 function (before, options, envir)
+## 2 {
+## 3 if (before) {
+## 4 do_newwindow(options)
+## 5 return()
+## 6 }
\end{verbatim}
\end{kframe}
\end{knitrout}
There was a modification in rgl, but not announced in NEWS
https://github.com/cran/rgl/blame/42a757711d47ba7bd25896e886cea2659e3479a3/R/Sweave_knitr.R#L129
Example need to be updated
https://github.com/yihui/knitr/runs/1454400827#step:11:1819
Thanks for providing the example for how to use a zero-width space to show the full code chunk from ```{r} to ```. I think this should be documented somewhere, but if someone were to copy and paste the code chunk into a text editor (other than RStudio) and then run it through knitr, they will get an error that is not entirely helpful.
---
output: html_document
---
```{r test}
x <- runif(5)
x2 <- sum(x^2)
```
This is a test. The sum of x squared is `r x2`
The output error message looks like so...
> render('test.Rmd')
processing file: test.Rmd
|................................ | 50%
ordinary text without R code
|.................................................................| 100%
label: test
Quitting from lines 6-10 (test.Rmd)
Error in parse(text = x, srcfile = src) : <text>:3:6: unexpected symbol
4:
5: This is a test. The sum of x squared is `
^
Calls: render ... evaluate -> parse_all -> parse_all.character -> parse
Execution halted
The solution is to remove the zero-width space between the first and second back ticks in the closing ```
. I don't know that this is a bug with the example so much as something that should be documented and I found confusing when I was teaching this past week.
i am trying to knit gpplot code to pdf file and it gives me an error.The dataframe in R is called retailyoy and the plot is to show .The code run in R Markdown give me this output.
but gives me problem when i am trying to knit.Below is error message:
"Error in ggplot(data = retailyoy, aes(x = retailyoy$Supplier Name
, y = retailyoy$SALES_CHANGE, :
object 'retailyoy' not found
Calls: ... withCallingHandlers -> withVisible -> eval -> eval -> ggplot
Execution halted"
Below is the chunk code:
library('ggplot2')
p1=ggplot(data=retailyoy, aes(x=retailyoy$`Supplier Name`, y=retailyoy$SALES_CHANGE, fill=DEPARTMENT, coord_cartesian(xlim = c(-200, 200))))+ geom_bar(stat="identity") + coord_flip() + scale_fill_brewer(palette="Dark2") + labs(title="YEAR ON YEAR GROWTH OF SALES",x="SUPPLIER NAME", y = "%YOY GROWTH")
p1+ geom_boxplot()
Seems like there is an issue with example 058 in recent knitr commit
yihui/knitr@545aed3
https://github.com/yihui/knitr/runs/4390959355?check_suite_focus=true#step:11:1672
diff --git a/058-engine-tikz.md b/058-engine-tikz.md
index bd095f7..a1044ec 100644
--- a/058-engine-tikz.md
+++ b/058-engine-tikz.md
@@ -13,27 +13,4 @@ You can pass some options to the engine by defining `engine.opts`, e.g. use your
An example of the tikz-engine from <raw.github.com/sdiehl/cats/master/misc/example.md>
-```tex
-\usetikzlibrary{arrows}
-\begin{tikzpicture}[node distance=2cm, auto,>=latex', thick, scale = 0.5]
-\node (P) {$P$};
-\node (B) [right of=P] {$B$};
-\node (A) [below of=P] {$A$};
-\node (C) [below of=B] {$C$};
-\node (P1) [node distance=1.4cm, left of=P, above of=P] {$\hat{P}$};
-\draw[->] (P) to node {$f$} (B);
-\draw[->] (P) to node [swap] {$g$} (A);
-\draw[->] (A) to node [swap] {$f$} (C);
-\draw[->] (B) to node {$g$} (C);
-\draw[->, bend right] (P1) to node [swap] {$\hat{g}$} (A);
-\draw[->, bend left] (P1) to node {$\hat{f}$} (B);
-\draw[->, dashed] (P1) to node {$k$} (P);
-\end{tikzpicture}
-```
-
-
-![Funky tikz](db.yihui.org/knitr-examples/figure/058-engine-tikz-tikz-ex-1.png)
-
-## Tips
-
-To develop the tikz-code, you could use `qtikz` or `ktikz`.
+
@yihui can you have a look at this as this is an old example. It could be completely unrelated to the change
knit_exit() will end the knitting at the end of the chunk and not immediately, you may want to make it clear in the example.
It would be cool if there was a way to stop the one chunk we are knitting while the next chunks will still be knitted, similar to a stop() function in a loop.
@yihui: In an earlier comment you stated that you want to keep a separate repo for knitr-examples
because of many references from various places. It's possible to keep the repository with a README file that points to the new location; as far as I'm aware, README files are shown for subdirectories, too, on GitHub, so the user even might not notice when you can gradually update the external references. I know this is extra work for you, but the advantages are very nice:
Issues to consider:
knitr-examples
to .Rbuildignore
knitr-examples
when importing into knitr
I can implement this.
Attempting to use https://github.com/yihui/knitr-examples/blob/master/077-wrap-output.Rmd
library(knitr)
hook_output <- knit_hooks$get('output')
knit_hooks$set(output = function(x, options) {
# this hook is used only when the linewidth option is not NULL
if (!is.null(n <- options$linewidth)) {
x = xfun::split_lines(x)
# any lines wider than n should be wrapped
if (any(nchar(x) > n)) x = strwrap(x, width = n)
x = paste(x, collapse = '\n')
}
hook_output(x, options)
}
)
to solve wrapping text output in a Quarto PDF output, however, it produces an error:
Error in hook_output(x, options) : could not find function "hook_output"
Calls: .main ... <Anonymous> -> lapply -> FUN -> <Anonymous> -> <Anonymous>
Execution halted
Refer to 027-engine-bash.Rmd
I've set PATH to make sure:
```{r}
>Sys.which('bash')
bash
"D:\\cygwin64\\bin\\bash.exe"
```
Then still get error when I try to run a bash command in R:
```{bash}
echo hello world
echo 'a b c' | sed 's/ /\|/g'
```
bash: C:\Users\MyName\AppData\Local\Temp\Rtmpao1Io3\chunk-code4aa837efa03.: No such file or directory
I use knitr 1.17
, and R version information below:
> version
platform x86_64-w64-mingw32
arch x86_64
os mingw32
system x86_64, mingw32
status
major 3
minor 3.3
year 2017
month 03
day 06
svn rev 72310
language R
version.string R version 3.3.3 (2017-03-06)
nickname Another Canoe
Does the knitr direct to a worng path? How can I avoid this error. Thanks!
When trying to run the example available here, I get the following message from knitr (just executing from within Rstudio GUI).
Invalid Parameter - /annual_review_files
Quitting from lines 16-31 (annual_review.Rmd)
Error in (knit_engines$get(options$engine))(options) :
problems with `convert`; probably not installed?
Calls: <Anonymous> ... process_group.block -> call_block -> block_exec -> in_dir -> <Anonymous>
Execution halted
I get the same message for any chunk in which I set engine='tikz'
. Looks like I am missing some sort of installation but I can't determine what I am missing.
This was previously possible but removed when Github actions was put in place.
#72
I think it could be easier when we add feature into knitr using PR to be able to add a knitr-examples at the time, and merge the PR when we know the knitr-examples check including the new examples will pass.
Currently this is not possible when using only master.
Could be done locally for our work though so opening this as a reminder to do when there are no other priorities
I have an R file with the following content:
library(markdown)
for(j in levels(iris$Species)){
render("iris.Rmd",output_format = "html_document",output_file = paste("iris_",j,".html",sep=""))
}
and an Rnw file called iris.Rmd such as
# iris observations for `r j`
```{r cars,results='asis'}
library(knitr)
for(i in 1:4){
cat("Data for the variable",names(iris)[i],"\n")
cat("\n")
print(kable(subset(iris,iris$Species==j,select=i)))
cat("\n")
}
```
When I run the content of the R file, the table appears as a vector whereas when I execute alone the Rnw file, I get the expected results (I need first to modify it in adding a chunk to define j as a level, for example setosa).
PS: sorry I don't know how to make the chunks appear here.
At some point I'd like to move the whole thing to an internal function knitr:::knit_example
, so that we only need to call Rscript -e "knitr:::knit_example()
in the shell script and powerscript.
Originally posted by @yihui in #82 (review)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.