Why is ifelse generating print output? - r

I have some code in my RMarkdown file that I knit:
ifelse(Sys.info()[1]=="Linux",
wdir <- "/path/1",
wdir <- "/path/2")
setwd(wdir)
Except it's supposed to be silent. I've got it in a block with
```{r prepare.data,echo=F,warning=FALSE,message=FALSE,error=FALSE}
I don't want to generate any output from that, yet when I knit, I get this in the output:
## sysname
## "/path/1"
I've tried just that code snip in the console and it is generating that print output.
My Questions are:
1. Why is ifelse printing this output?
2. How can I avoid it?
Thanks!

Try wdir <- ifelse(Sys.info()[1]=="Linux", "/path/1", "/path/2"). The reason the output is printed is that if you don't assign the ifelse output to some variable, it will just print it on the screen. It is like writing a <- 1 + 2 vs 1 + 2.

Related

How to create text paragraph for results in R?

I'm writing my results (both text and tables) and the process is quite time-consuming...
I was wondering if a function in R could help me paste my results into the text so I could copy it into WORD?
For example:
R square = put number here, B = put number here... The difference between the models was significant/nonsignificant with p < put number here
Then I would love to paste it into WORD.
Best regards,
Daniel
Couldn't find any function that would help me... Tried Flextable...
If I understand the question correctly, this can largely be done in base R and reported with R Markdown or Quarto. You can either write the document as a .qmd or .rmd file and export to word, or simply render in RStudio and then copy and paste as you like.
I work the following way:
First assign the models to variables using <-.
Then examine the structure of the model with str().
In the text of the document, use $ with the variable name to access the various parts. Or paste it in the console for cut and paste of the values.
You may want to round() some numbers. Additionally, the function scales::pvalue() is very helpful for p values.
library(scales)
# Generate some model and assign it to a variable
model <- cor.test(cars$speed, cars$dist)
# Examine the structure of the model object
str(model)
Then in the text of an R markdown or Quarto document you can write:
$r$(`r model$parameter`) = `r round(model$estimate, digits = 2)`, $p$= `r pvalue(model$p.value, accuracy = 0.05)`
This will give the following: r(48) = 0.81, p= <0.05
In a code chunk $ is used to access a component. In text $ is used to start an equation. That can be confusing. To access a piece of R code in R Markdown text, use the convention `r <function or variable>` as in `r model$parameter` above. Alternatively, you can simply paste model$parameter into the console and copy the results to your target document.
You could knit the document to word, here's a quick example using inline R:
---
title: "test.Rmd"
output: word_document
---
``` {r, echo = FALSE}
# some variables
a <- 24
b <- 100
```
R square = `r a`, B = `r b` ... The difference between the models was `r if (a == 24) {"significant"} else {"insignificant"}` with p < `r b - a`

Plain code chunks for R input in knitr output

Goal
In an R/Markdown document that I want to convert to LaTeX I want to set knitr options so that the entire document uses plain code chunks for all code inputs by default. Thus, for a .Rmd document with
```{r}
x <- 1 + 1
```
I want to obtain the output
```
x <- 1 + 1
```
Using the highlight option
I had hoped that the highlight=FALSE option could be used for this but this generates text-chunks rather than plain chunks. More precisely, for the simple example above, knit() produces an R-chunk by default (i.e., with highlight = TRUE):
```r
x <- 1 + 1
```
After setting knitr::opts_chunk$set(highlight = FALSE) a text-chunk is produced:
```text
x <- 1 + 1
```
But what I would like to have a plain chunk without any special language, see above.
Combination with lang option
I can obtain what I want via
knitr::opts_chunk$set(highlight = TRUE, lang = "")
Thus, I do enable highlighting but set the lang to an empty string. This indeed yields the plain code I want to have.
There is at least one disadvantage, though (apart from the rather hacky feel of this solution). Namely, if in the same document I do want to enable highlighting in the options of one specific chunk, I have to set lang = "r" now instead of highlight = TRUE, e.g.,
```{r, lang="r"}
x <- 1 + 1
```
So I wonder whether there is a better solution for this?
Background
In older versions of pandoc (I tried 2.9.x) text-chunks were converted to {verbatim} code chunks in LaTeX output.
However, more recent versions of pandoc (I tried 2.17.x) text-chunks are converted to {Shaded} instead and only plain chunks are converted to {verbatim}.
Another hacky solution is (I don't even dare to explain it):
```{r}
knitr::opts_hooks$set(highlight = function(options) {
if (!options$highlight) {
options$highlight = TRUE
options$lang = ''
}
options
})
knitr::opts_chunk$set(highlight = FALSE)
```
```{r}
1 + 1
```
```{r, highlight=TRUE}
2 + 2
```
The language name text when highlight = FALSE is currently hard-coded in knitr, so you cannot change it: https://github.com/yihui/knitr/blob/907184f82/R/hooks-md.R#L171 I'm open to making it configurable, but I'm not sure how (I hope not to add a new chunk option for setting the language in the case of highlight = FALSE).
I'm not sure I entirely understand what you want, but does this in the yaml header help?
---
output:
html_document:
theme: null
highlight: null
---

How to retain the scientfic format of the numbers while knitting to pdf in rstudio?

The below two code chunks reflects the same output in the R console. But when knit to pdf,it gives me different output. Why?
```{r}
x = 2.22e-16
x
```
```{r}
as.data.frame(x)
```
Output when knitting to pdf:
You can see that, in the data frame, it shows 0 instead of 2.22e-16.
How to correct this?
Note: I use printr package for the nice dataframe and matrix outputs.
setting options(digits = 17) solved the problem but it doesnot seems to be a good solution since it affects all the other chunks if I set it globally.

knitr: less/greater than sign displayed as (¡) and (¿)

I'm a beginner in using knitr to generate a report.
I have a R script (see below for an example; BTW I'm using RStudio for all of this) that runs without error and the output is a data frame. My rnw.file looks like this:
% !Rnw weave = knitr
\documentclass[a4paper]{article}
\begin{document}
<<echo=FALSE,message=FALSE>>=
source("test.R")
kable(test.mat)
#
\end{document}
which displays the table quite nicely. The only problem I have is with the ">" (greater than) sign in the last column which is shown as "¿".
In found something about using
\usepackage[T1]{fontenc}
but this doesn't seem to do the trick here. Having included this, I can start compiling the script but after 10 minutes or so (and before it only took me some seconds to compile) I run into an error (exit code: 1).
Thanks in advance!
R.script (saved as "test.R"):
temp <- 12
test.mat <- as.data.frame(matrix(NA,ncol=2,nrow=1))
test.mat$V1 <- 2
test.mat$V2 <- paste(temp,"subjects > 28 days",sep=" ")
> is a mathematical symbol and as so it is not recognized unless it is not embedded in a a mathematical environment (inline or as a bloc.)
Try this code.
$>$
A (not so elegant) solution
The behavior of kable remains strange. After I've analyzed the latex code that it produces I've tried this solution, which is not so elegant, but it works. Hoping that some other users will provide more efficient solutions. Here is my code.
% !Rnw weave = knitr
\documentclass[a4paper]{article}
\begin{document}
<<echo = F, message = FALSE>>=
source("test.R")
aa1
#
\end{document}
where the test.R is:
temp <- 12
test.mat <- as.data.frame(matrix(NA,ncol=2,nrow=1))
test.mat$V1 <- 2
test.mat$V2 <- paste(temp,"subjects > 28 days",sep=" ")
aa <- kable(test.mat, format = "latex")
aa1 <- gsub(">", "$>$", aa)
and here is the result:
I can't explain why it is working now, but here is what I found I should use in the preambel:
\usepackage{lmodern}
\usepackage[T1]{fontenc}
Found this in another thread (not really related to my question), but now I get what I want in the R output (no changes required in the R.script) as well as in the pdf.

How to output to pdf using knitr/xtable when tex has square braces ( [ )?

I am trying to output the freq table generated by cut to a PDF file using knitr and xtable. However, when I include the option include.rownames=FALSE the output is not processed and an error is reported whereas the code works with include.rownames=TRUE. Test code is below:
\documentclass[12pt]{article}
\begin{document}
<<test_table, results = "asis",echo=FALSE>>=
library(xtable)
x <- sample(10,100,replace=TRUE)
breaks <- c(1,2,5,10)
x.freq <- data.frame(table(cut(x, breaks, right=FALSE)))
print(xtable(x.freq),include.rownames=TRUE)
#
\end{document}
When I use include.rownames=TRUE I get the output below.
1 [1,2) 5
2 [2,5) 35
3 [5,10) 49
whereas when I use include.rownames=FALSE I get an error:
Test.tex:71: LaTeX Error: \begin{tabular} on input line 58 ended by \end{document}.
I believe that I am getting the error because of the presence of the square braces ' [ ' in the text source.
Does anyone know how to solve this problem?
The problem is that the end of each row in the table is a \\ which has an optional argument to specify how much space to leave before the next row, for example, \\[1in]. There's allowed to be white space between the \\ and the [, so in this case, it's trying to read the [2,5) as that argument.
A simple workaround would be to change the labels of the factor to include some non-printing blank character first, however, if you do so, by default, print.xtable will "sanitize" it so that it actually does print, so you'd need to turn that off by passing a new sanitize function; identity will do none of this fixing.
levels(x.freq$Var1) <- paste0("{}", levels(x.freq$Var1))
print(xtable(x.freq),include.rownames=FALSE, sanitize.text=identity)

Resources