Removing exponents from RMD output - r

I am trying to output a large number that is stored in a variable in a RMD file. I would like the number to print something like
Large number: 4123125.2
however when I knit the rmd it always comes out as
Large number: 4.123125210^{6}
I would like to do away with the exponent notation to make it easier to read.
---
output: html_document
---
```{r}
large.number <- 4.1231252*10^6
```
Large number: `r large.number`.
```{r}
large.number <- 4123125.2
```
Large number: `r large.number`.

use this syntax:
sprintf("%f", large.number)
you can then define how many figures you want to be printed:
sprintf("%.2f", large.number)

Related

RMarkdown PDF add non-spacing linebreak inside paste0()

I want to use RMarkdown to combine several sentences in the paste0-function, and insert a non-spacing line break in between.
In pure Markdown, a simple backslash \ is sufficient to generate a non-spacing line break. However, this does not work in the character string of the paste0-function.
I have already inserted \n\n between the sentences. However, there is a space between the lines, which I want to avoid.
Can anyone help me with my problem?
The programmatic scheme with the code chunk and the subsequent inline code should be the same.
Here is my example code:
---
title: "Untitled"
output: pdf_document
date: "2023-01-17"
---
```{r echo=FALSE}
result_1 <- 100
result_2 <- 200
```
```{r echo=FALSE}
final_text <- paste0("My first result is ", result_1, "My second result is ", result_2)
```
`r final_text`
The first and second sentences are the result of the \n\n-separator.
The third and fourth sentences are my desired outcome (created with a \ in plain Markdown)
The result of putting `r final_text` into your text will be the same as if the characters in the final_text variable were inserted there. So you just need to insert the characters that resulted in the output you want.
If those characters are
My first result is 100\
My second result is 200
then you can get that output using this R code:
---
title: "Untitled"
output: pdf_document
date: "2023-01-17"
---
```{r echo=FALSE}
result_1 <- 100
result_2 <- 200
```
```{r echo=FALSE}
final_text <- paste0("My first result is ", result_1, "\\\nMy second result is ", result_2)
```
`r final_text`
The explanation for the string \\\n at the start of the second line is as follows: Use \\ to get a single backslash, then use \n to get a line break.

How to run a rmarkdown to create multiple html with different parameters?

I have a code in R, which is done in rMarkdown, it needs to run several times but with different parameter values.
How can I solve it? I have put an example of simplified problems.
Suppose I need to print different values in a loops, in order to make it simple I used simple loops.
For each combination of these two loops I want to make one html file, for example means 200 *400 different html report files.
---
title: "file1"
author: "user"
date: "25 1 2021"
output: html_document
---
# The first loop should be done, from 1:100, 101:200 ... to ... 20001:20100
```{r}
i=getfirst()
j=getsecond()
```
```{r}
for (i in i:j) print(i)
```
# The second loop should be done, from 1:50, 51:100 ... to ... 20001:20050
```{r}
for (i in i-50:j-50) print(i)
```
suppose each time we may have different i and j which should pass into markdown file.
I'd simply create a wrapper script (i.e. a separate e.g. .R) file, where you specify:
R file
for (i in 1:10){
j = i+50
if(!dir.exists(paste0("directory_",i))){dir.create(paste0("directory_",i))}
knitr::knit(input = "markdown.Rmd",output = paste0("directory_",i,"/output",i,"_",j,".html"))
}
And then your Rmd file, which you have saved as markdown.Rmd in this example looks like this:
RMarkdown file
---
title: "file1"
author: "user"
date: "25 1 2021"
output: html_document
---
# The first loop should be done, from 1:100, 101:200 ... to ... 20001:20100
```{r}
for (i in i:j) print(i)
```
# The second loop should be done, from 1:50, 51:100 ... to ... 20001:20050
```{r}
for (i in i-50:j-50) print(i)
```
There is a dedicated chapter in the official documentation, "Knitting with parameters", that outlines how to proceed in your use-case.

How to generate rmarkdown chunk within a chunk

I'm trying to generate a rmarkdown chunk using code. I've read similar questions and their solutions, such as using pander or using cat. I just can't seem to generate it. I also tried knitting the output manually. Here's an example of a Rmd file:
---
title: "test"
output: pdf_document
---
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}",
"2+2",
"```")
pander::pander(txt)
```
When I knit this, I get a verbatim {r} 2+2. I would like to see the number four instead. In my real example, I'm using bookdown and trying to generate a block2 chunk.
Any ideas how to generate this chunk that gets evaluated as R code?
Does this do what you want?
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}",
2+2,
"```")
pander::pander(txt)
```
This evalutates to
```{r} 4 ```
in your markdown document.
You using a string literal "2+2" as opposed to the expression 2+2. This is the first issue, I guess.
If you want it correctly parsed you need to add an sep = "\n" argument to paste or manually add the newline breaks.
I.e.
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}\n",
2+2,
"\n```", sep = "")
pander::pander(txt)
```
This evalutates to
```{r}
4
```
which is interpreted as R code in the markdown document.

R Markdown embedding a function into a simple table

I'm new to R and I'm really liking the flexibility of R Markdown to create reports.
My problem is that I want to use a random number generating function I've created my tables. I want simple tables to include string headers and the following function:
> ran<-function(x){
+ x<-runif(n=1, min=13.5,max=15.5)
+ round(x, digits=2)}.
It won't allow me to create a table using this method?
```{r}
String |String |String
-------|------|------
ran(x)|ran(x)|ran(x)
```
My ultimate goal is to create practice worksheets with simple statistics that will be different but within a bounded integer range - so I can ask follow-up questions with some idea of the mean, median etc.
Any help would be greatly appreciated.
Perhaps you should read up on both how to build working R code and how to code up Rmd files since your function doesn't work and there are a few places in the R Markdown docs that show how to do this:
---
output: html_document
---
```{r echo=FALSE}
ran <- function(x) {
runif(n=1, min=13.5, max=15.5) + round(x, digits=2)
}
```
One |Two |Three
-----------|-------------|-----------
`r ran(2)` | `r ran(3)` | `r ran(4)`
`r ran(2)` | `r ran(3)` | `r ran(4)`
`r ran(2)` | `r ran(3)` | `r ran(4)`
`r ran(2)` | `r ran(3)` | `r ran(4)`
generates:
Also, neither SO nor RStudio charges extra for spaces in code blocks. It'd be good to show students good code style while you're layin' down stats tracks.
Here is an approach that automates much of the report generation and reduces the amount of code you need to type. For starters, you can turn this into a parameterized report, which would make it easier to create worksheets using different values of x. Here's an example:
In your rmarkdown document you would declare parameters x and n in the yaml header. n is the number of random values you want to produce for each value of x. The x and n values in the yaml header are just the defaults knitr uses if no other values are input when you render the report:
---
output: html_document
params:
x: !r c(1,5,10)
n: 10
---
Then, in the same rmarkdown document you would have the text and code for your worksheet. You access the parameters x and n with params$x and params$n, respectively.
For example, the rest of the rmarkdown document could look like the code below. We put x into a list called x_vals with named elements, so that the resulting column names in the output will be the names of the list elements. We feed that list to sapply to get a column of n random values for each value of x. The whole sapply statement is wrapped in kable, which produces a table in rmarkdown format.
```{r, include=FALSE}
library(knitr)
```
```{r, echo=FALSE}
# Create a named list of the x values that we passed into this document
x_vals = as.list(setNames(params$x, paste0("x=", params$x)))
kable(sapply(x_vals, function(i) round(runif(params$n, 13.5, 15.5) + i, 2)))
```
You can now click the "knit" button and it will produce a table using the default parameter values:
If instead you want to use different values for x and/or n, open a separate R script file and type the following:
rmarkdown::render("Worksheet.Rmd",
params = list(x = c(2,4,6,8),
n = 5),
output_file="Worksheet.html")
In the code above, the render function compiles the rmarkdown document we just created, but with new x and n values, and saves the output to a file called Worksheet.html. (I've assumed that we've saved the rmarkdown document to a file called Worksheet.Rmd.) Here's what the output looks like:
You can also, of course, add parameters for the lower and upper limits of the runif function, rather than hard-coding them as 13.5 and 15.5.
If you want to create several worksheets, each with different x values, you can put render in a loop:
df = expand.grid(1:3,5:6,10:11)
for (i in 1:nrow(df)) {
rmarkdown::render("Worksheet.Rmd",
params = list(x=unlist(df[i,]), n=10),
output_file=paste0(paste(unlist(df[i,]),collapse="_"),".html"))
}

Knitr output differs between Rmd and Rnw: data.table output example

Revised title to clarify focus.
We notice an anomaly that R markdown and data.table interact in a surprising way. Same does not happen when knitting LaTeX. Commands which not have a return within the R session do cause a return within the knitted markdown output. I trace the problem back to commands like the following, which do not produce an output in R,
````{r}
poolballs[ , weight2:=2 * weight]
```
but inside Rmarkdown, the output includes the full print of the poolballs DT. Same does not happen if we knit an equivalent chunk in LaTeX.
This produced some funny HTML output because I wrote chunks like this, intending to display only the first 5 lines
```{r}
poolballs[ , weight2:=2 * weight]
head(poolballs)
```
Markdown parses that as the equivalent of two chunks,
> poolballs[ , weight2:=2 * weight]
> poolballs
> head(poolballs)
Here's the markdown file to demonstrate
---
title: "Data Table Guide"
author:
- name: Paul Johnson
affiliation: Center for Research Methods and Data Analysis, University of Kansas
email: pauljohn#ku.edu
date: "`r format(Sys.time(), '%Y %B %d')`"
output:
html_document:
theme: united
highlight: haddock
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=TRUE, comment=NA)
options(width = 70)
```
```{r make_pb_dt}
set.seed(234234)
library(data.table)
poolballs <- data.table(
number = 1:15,
weight = rnorm(15, 45.7, 0.8),
diameter = c(3, 2.9, 3.1) #shows recyling
)
poolballs
```
I want the following to show only head in line 2
```{r}
poolballs[ , weight2:=2 * weight]
head(poolballs)
```
Compare the HTML output:
http://pj.freefaculty.org/scraps/mre-dt.html
I'm sorry if this is a known feature of markdown. I've coded around this wrinkle by hiding chunks, but it seems somewhat inconvenient. Today i'm curious enough to ask you about it. I wrote the same chunks in a LaTeX file and the funny DT output problem does not happen. I put link to PDF from LaTeX in http:/pj.freefaculty.org/scraps/mre-dt-3.pdf
In your final chunk, knitr sees that you have two objects that its attempting to print and you're getting the output for both. This isn't a feature, and has been addressed in a previous question.
If you want to only print the head of the first object in that chunk, your code should be head(poolballs[, weight2:=2 * weight])

Resources