I am using Rmarkdown with python. What is the equivalent of the R inline code for python?
Example, in https://rmarkdown.rstudio.com/lesson-4.html I can do
``r x`
to display the value of x in the text. but If I do
``python x`
I just get the text python x
Not sure whether this is possible. All examples I have found use R inline code like so `r py$x` to achieve that. See e.g. the rmarkdown cookbook.
With this workaround, it's possible:
```{r setup, include=FALSE}
library(reticulate)
```
```{python include=FALSE}
result = 1 + 1
```
1 + 1 = `r py$result` # 1 + 1 = 2
Where py$result means: take the value of the Python variable called result.
Related
I am using Quarto to produce some revealjs slides using RStudio and have been using the code-line-numbers option to selectively highlight lines of code. For instance:
```{r, echo = TRUE}
#| code-line-numbers: "1|3"
x <- 1
y <- 2
x + y
x * y
```
Allows me to highlight the first and third lines of code in the presentation.
I would like to additionally be able to highlight certain lines in the output. For instance, if I wanted to only highlight the result of x+y but not x*y, is there a way of doing so? I wondered if there was an option for output-line-number or similar that might have the desired effect, but couldn't find anything like this.
Any pointers appreciated!
A possible way to do this could be based on using pandoc Lua filter.
Here I have created a chunk-option output-line-numbers to specify which output lines to highlight (works just as code-line-numbers chunk option), but please note that you must have to use class-output: highlight to get this line specific highlighting on chunk output.
---
title: "Output Line highlight"
format: revealjs
filters:
- output-line-highlight.lua
---
```{r, echo = TRUE}
#| code-line-numbers: "1"
#| class-output: highlight
#| output-line-numbers: "2"
for (i in 1:3) {
print("This is some random line")
}
```
output-line-highlight.lua
function highlight(line_number)
local highlighter = {
CodeBlock = function(block)
if block.classes:includes('highlight') then
block.classes:insert('has-line-highlights')
block.attributes["code-line-numbers"] = line_number
return block
end
end
}
return highlighter
end
function Div(el)
if FORMAT == 'revealjs' then
if el.classes:includes('cell') then
line_number = tostring(el.attributes["output-line-numbers"])
return el:walk(highlight(line_number))
end
end
end
I have many markdown files, each with many codeblocks, see an example below. (They were converted to this format via pandoc from other file types)
I would like to knit these in as Rmd files. Right now, the codeblocks have no decorators. When I knit the file below, there is no code syntax styling/coloring. I do not want to evaluate the code, I just want to print them out, hence: knitr::opts_chunk$set(warning=FALSE, message=FALSE, cache=FALSE).
Suppose all the code are MATLAB code, is there something I can add like: knitr::opts_chunk$set(code=MATLAB), so that they would all get MATLAB code styling/coloring?
My code chunks are actually all MATLAB code, so MATLAB stlying/coloring would be more helpful, but any code styling would be great to make the code chunks in outputted HTML/PDF etc easier to read.
---
title: matlab code in blocks
output: html_document
---
# RMD file with Markdown Code Blocks
```{r global_options, include = FALSE}
knitr::opts_chunk$set(warning=FALSE, message=FALSE, cache=FALSE)
```
## Example 1
Here is a code block A
fl_fig_wdt = 3;
fl_fig_hgt = 2.65;
figure('PaperPosition', [0 0 fl_fig_wdt fl_fig_hgt], 'Renderer', 'Painters');
x = rand([10,1]);
y = rand([10,1]);
scatter(x, y, 'filled');
grid on;
grid minor;
## Section 2
Here is a code block B
fl_fig_wdt = 5;
fl_fig_hgt = 5.65;
figure('PaperPosition', [0 0 fl_fig_wdt fl_fig_hgt], 'Renderer', 'Painters');
x = rand([20,1]);
y = rand([20,1]);
scatter(x, y, 'filled');
grid on;
grid minor;
End of file.
If you need a general solution, you need to use a Pandoc Lua filter (I'm not able to write one for you; see the Github issue that you cross-posted). If you only need HTML output, you may use JavaScript to add a class name to the code blocks, e.g., add this js code chunk to the end of your document:
```{js, echo=FALSE}
document.querySelectorAll('pre').forEach(function(el) {
// the class name is the language name
// (I'm using R here, although it's not the right name)
if (!el.className) el.className = 'r';
});
```
The output looks like this:
I am trying to render the syntax for chunks of code in RMarkdown to a pdf. The final output should look like
```{r}
#some code
```
Rather than just
#some code
The best options to answer this can be found on the RStudio website. See the article on getting verbatim R chunks into rmarkdown http://rmarkdown.rstudio.com/articles_verbatim.html
My preferred solution is to add an inline R code at the end of the first line to make the chunk appear correctly in the output like so:
```{r eval=TRUE}` r ''`
seq(1, 10)
```
Which produces
```{r eval=TRUE}
seq(1:10)
```
Rather than
## [1] 1 2 3 4 5 6 7 8 9 10
Another way to do the same thing is treat the code chunk as a string (I don't usually use the -> operator but in this case I think this improves readability):
```{r comment = ""}
"{r eval=TRUE}
seq(1, 10)
" -> my_code_string
cat("```", my_code_string, "```", sep = "")
```
Which outputs:
```{r eval=TRUE}
seq(1, 10)
```
This question is also a possible duplicate of How to embed and escape R Markdown code in a R Markdown document
I would love to use R Markdown to generate homework and exam solutions, but I would prefer to have them more readable to non-coders.
I there a way that I can pass the ECHO output through math mode? That is I would love to have an ECHO that looks more "inline" and less like code. I can see how to hide it, but in the R Markdown Reference Guide I don't see an option to remove the "code block" and wrap each line in $$ (or wrap in anything). Is there a way to do this?
Here is an example. This solution has all the meat, but may be a little intimdating to some students (this is not an R course).
8-22 ...
a. ...
```{r part_a}
D_0 = 2.40
g = 0.06
r = 0.12
V = D_0*(1 + g)/(r - g)
V
```
Instead, I would love to see something more like the following.^[I appreciate that I can generate this output with some cutting and pasting and a text editor, I am just trying to find the most efficient solution, since this is likely something that I will do more than once or twice.]
8.22 ...
a. ...
$$ D_0 = 2.40 $$
$$ g = 0.06 $$
$$ r = 0.12 $$
$$ V = D_0 \times (1 + g)/(r - g) = 2.40 \times (1 + 0.06)/(0.12 - 0.06) = `r V`$$
I have a partial answer. I don't yet know how to replace variable x with its value so that a can print the formula with variables, replaced by numbers. But I can generate the "math code" block so that I can solve the problem and generate the pretty solution without a lot of cut and paste.
Here is an example .Rmd file.
---
author: Richard Herron
title: Homework Solutions
---
8-22 ...
a. ...
There are three parts to this solution.
1. write the equations to solve the problem in R-readable strings.
2. loop over the list and `eval(parse())` the equation strings
3. wrap strings in `$$ $$` with `cat(paste0())`
Chunks should be set to `echo=FALSE` and `results="asis`. You may need to suppress some function output with `invisible()`.
```{r part_a, echo=FALSE, results="asis"}
# just to make sure my eval below works
rm(list=ls())
# store solution as a list of character equations
solution <- list(
"D_0 = 2.40",
"g = 0.06",
"r = 0.12",
"V = D_0*(1 + g)/(r - g)"
)
# "solve" problem
for (i in seq_along(solution)) eval(parse(text=solution[[i]]))
# display solution as math
cat(paste0("$$", solution, "$$"), sep="\n")
```
Because of the `eval()` loop in the first chunk I can say that $V = `r V`$ in the text that follows.
And here is an outer file that convert each .Rmd file into a .pdf.
# load `render` and set working directory
setwd("C:/Users/Richard/Dropbox/Babson College/SME 2021 for 2015 fall/Homework")
# loop over all Rmd files
require(rmarkdown)
require(tools)
files <- list.files(path=".", pattern="*.Rmd")
roots <- sapply(files, file_path_sans_ext)
namesIn <- paste0("", roots, ".pdf")
namesOut <- paste0("", roots, ".pdf")
# solutions
myPdf <- pdf_document(
fig_caption=TRUE,
keep_tex=TRUE,
pandoc_args=c(
"--variable=classoption:fleqn",
"--variable=classoption:twocolumn",
paste0("--metadata=date:", format(Sys.time(), "%B %d, %Y"))
)
)
lapply(files, FUN=render, output_format=myPdf)
mapply(file.rename, namesIn, namesOut)
Which yields this pdf.
I am producing an HTML output but I am having issues with the output width of R code output.
I'm able to adjust the figure width with no difficulty but when I try to write a data table or the factor loadings, R is outputting at a fixed width which is only about a third of my screen width. This results in the columns of the table being split up rather than all of the columns displayed in a single table.
Here is a reproducible example:
---
output: html_document
---
# Title
```{r echo = FALSE, fig.width=16, fig.height=6}
x = matrix(rnorm(100),ncol=10)
x
plot(x)
```
Add this at the start of your document:
```{r set-options, echo=FALSE, cache=FALSE}
options(width = SOME-REALLY-BIG-VALUE)
```
Obviously, replace SOME-REALLY-BIG-VALUE with a number. But do you really want to do all that horizontal scrolling?
Your output is probably being wrapped somewhere around 80 characters or so.
Also, you can temporarily change the local R options for a code chunk:
```{r my-chunk, R.options = list(width = SOME-BIG-VALUE)}
```