I am currently having trouble achieving the desired rounding of numbers using knitr. The issue occurs with numbers that would end with a zero on the final rounded digit. An example of this is 14.04, which I want to be rounded at 1 decimal place to 14.0. The issue is that knitr with latex as the output gives 14 without the 0 as the decimal place.
I would assume that there is some sort of trailing zero option, but I cannot locate it. Any ideas? Bellow is a short minimal working example of the issue.
\documentclass[12pt]{article}
\begin{document}
<<>>=
library(knitr)
options(digits=1)
#
Full number = 14.0417
Number of issue \Sexpr{14.041783}
Should appear as 14.0
\end{document}
EDIT: While looking at the first answer (Thanks for the rapid reply Ben), I realised the other issue that I have here. While solutions where the number is formatted as a string, get around the main issue, they do not solve the same issue when it occurs on "large" numbers, which become formatted using scientific notation.
I will give a second example that demonstrates this: say the number is 100,400,000. The resulting output using options(digits=2) becomes 10^8, where I would prefer 1.04 x 10^8. Rnw example below.
\documentclass[12pt]{article}
\begin{document}
<<>>=
library(knitr)
options(digits=2)
#
Number 100,400,000
\Sexpr{100400000}
\end{document}
I think this answers it: use sprintf().
\documentclass[12pt]{article}
\begin{document}
<<>>=
library(knitr)
options(digits=1)
x <- 14.0417
#
Full number = \Sexpr{x}
Number of issue \Sexpr{sprintf("%.1f",x)}
\end{document}
Related
Imagine I knit this Rnw file:
\documentclass{article}
\begin{document}
Table1
<<example,results='asis', echo=FALSE>>=
require(xtable)
nn <- 15
mydata <- data.frame(A=1:nn,C=nn:1, C=runif(nn), D=rnorm(nn))
xtable(mydata, caption="Table1")
#
Table2
<<example2,results='asis', echo=FALSE>>=
xtable(mydata, caption="Table2")
#
Table3
<<example3,results='asis', echo=FALSE>>=
xtable(mydata, caption="Table3")
#
\begin{obeylines}
Just some text
\end{obeylines}
\end{document}
It's a simple example that just prints some text and three tables.
Strangely it doesn't respect the order of what I've written on my code.
I get this (sideview of the two pdf pages)
But "Table3" text should appear before the table3 itself and after table2, and the text "just some text" should appear at the very end of the document.
If I write several lines there it breaks the lines.
I understand that if a table doesn't fit on a place it must be moved to the next page but so should be done with the following text and tables.
I've also observed that in other examples some tables are reallocated randomly when they don't fit well.
How can I prevent knitr from doing this?
I don't know whether is a knitr problem or latex.
I'm using Texlive 2015, Rstudio, R 3.2.3 and Windows 10 and the latest version of all packages involved.
By default print.xtable() produces a LaTeX \table{...} environment, which is defined as a floating object. See `?print.xtable and try e.g.
<<example2,results='asis', echo=FALSE>>=
print(xtable(mydata, caption="Table2"),floating=FALSE)
#
(untested ...)
alternatively you could try table.placement="H"; you may need \usepackage{float} (see this question from tex.stackexchange.com).
(also untested ...)
I have read a lot of question and relative answer but I didn't find a solution! My request is similar to this:
Putting line number for R code with knitr, but I want to keep the standard style of Knitr. A user, Thomas, suggest to add language=R to the listings options but this doesn't change the output.
A result like this:
would be great! (The theme isn't relevant just the LINE number).
I've tried to use the render_listings() function:
\documentclass{article}
\usepackage{listings}
\lstdefinestyle{Rstyle}{%
fancyvrb=FALSE,escapechar=`,language=R,%
basicstyle={\Rcolor\Sweavesize\ttfamily},% Added \ttfamily
backgroundcolor=\Rbackground,%
showstringspaces=false,%
keywordstyle=\Rcolor,%
commentstyle={\Rcommentcolor\ttfamily\itshape},%
%literate= Removed
alsoother={$},%
numbers=left,
numbersep=5pt,
alsoletter={.<-},%
otherkeywords={!,!=,~,$,*,\&,\%/\%,\%*\%,\%\%,<-,<<-,/},%
escapeinside={(*}{*)}}%
\begin{document}
<<setup, include=FALSE>>=
render_listings()
#
<<a, results='hold'>>=
1:2
3:4
5:6
#
<<b>>=
"test1"
"test2"
"test3"
#
\end{document}
Maybe I Have to modify sweavel.sty file too but I haven't idea how to do that.
How can I get R chunk code to produce the same number of digits as r inline code in RStudio RMarkdown file?
For example:
```{r}
x=1:30
sigma.sq=sum((x-mean(x))^2)/30
sigma.sq
```
Thus, $\sigma^2=`r sigma.sq`$.
The chunk produces the number 74.92, but the inline code produces the number 74.9167. I'd like both to be the same.
Suggestions?
D.
P.S. Here's a screen shot of what the above code produces.
round() function gives you an answer. For example, the below inline code in R Markdown would display the second decimal place of the number of the object.
`r round(sigma.sq, 2)`
I need to call a database that has underscores in the table names in an R chunk in knitr. There are a couple thousand table names, and changing the names would be a huge hassle.
Something like:
<<classRun,fig=FALSE,print=FALSE,echo=FALSE>>=
getdat = function(nbr1,nbr2){
library(RODBC)
database.dsn1<-c("db")
database.user1<-c("username")
database.password1<-c("password")
channel<-odbcConnect(database.dsn1, database.user1, database.password1)
dat = sqlQuery(channel,paste("select * from table_",nbr1,"_",nbr2, sep=""))
}
#
<< results='asis', echo = FALSE>>=
dat = getdat(10,20)
print(dat)
#
I get the error that I am missing a $ ("Missing $ inserted") because of the underscore in "table_10_20". I have played around a lot with adding in '\$\', and '\$\', you name it. Also played around with cat(), and paste(), and single quotes, and double quotes. Any suggestions? Thanks in advance for your help. I am running Ubuntu 11.10, and calling knitr from RStudio with pdfLaTeX, if that matters.
Chances are you have a column name with an underscore in it.
Recall that results='asis' just dumps all the output as-is into the tex document.
For example, this is a reproducible example of your problem:
% test.Rnw
\documentclass[a4paper]{article}
\begin{document}
<<classRun, fig=FALSE, print=FALSE, echo=FALSE>>=
table_10_20 <- data.frame(col_1=1:10, col_2=runif(10))
#
<<results='asis', echo=F>>=
print(table_10_20)
#
\end{document}
If I run this through knitr I get the "Missing $ inserted".
If I look at the .tex file that gets produced, I see:
% test.Rnw
\documentclass[a4paper]{article}
.... lots of tex ....
\begin{document}
col_1 col_2
1 1 0.69699
2 2 0.12988
3 3 0.19662
4 4 0.04299
5 5 0.08750
6 6 0.72969
7 7 0.19818
8 8 0.27855
9 9 0.81806
10 10 0.56135
\end{document}
See how the column names col_1 and col_2 are just dumped as-is into the file? Well, in LaTeX an underscore has a special meaning (subscript), which is only valid in maths mode, hence the LaTeX compiler tries to put the maths mode delimiters ($) around the word, giving your error.
In your case, you have a few options depending on what you want for your output.
Use \begin{verbatim} with results='asis' to protect the underscores. This will dump your output into a verbatim environment.
\begin{verbatim}
<<results='asis', echo=F>>=
print(table_10_20)
#
\end{verbatim}
Use results='markup': this is like a verbatim environment except sweave colours the output. By default it'll put a comment mark (##) in front of every line; to remove this use comment=NA. (You can't see too well how this pic is different from the above; it is the same except it has a grey background to distinguish it from the rest of the document. It's the same markup as when you use echo=T).
<<results='markup', comment=NA, echo=F>>=
print(table_10_20)
#
The above two simply print your table as-is in fixed with font. If you want a proper latex table, you can use a package like xtable, which can convert a data.frame (& similar) ino proper LaTeX (or HTML) markup. I think there are other packages that can do this too but for the moment they escape me. You use results='asis' here. (See the documentation for more details, you really can control every aspect of what gets printed in the table and how):
<<results='asis', echo=F>>=
library(xtable)
print(xtable(table_10_20), include.rownames=FALSE)
#
Sometimes I get to make an R code chunk (in Sweave) which is longer then the margins of the page. Is there a way to force it to "go to the next line" once that happens?
Here is a simple example of that happening:
\documentclass[a4paper]{article}
\usepackage{Sweave}
\DefineVerbatimEnvironment{Sinput}{Verbatim} {xleftmargin=2em,
frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{xleftmargin=2em,
frame=single}
\title{Sweave with boxes}
\begin{document}
\maketitle
<<echo=FALSE>>=
options(width=60)
#
Here is an example of a code chunk followed by an output chunk,
both enclosed in boxes.
<<>>=
print(rnorm(99))
#
<<>>=
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
#
\end{document}
This is a difficult and extreme case, because you do not have spaces among those a's, so LaTeX may not be able to wrap the words. If you do have spaces, knitr will be able to produce the output with the long lines wrapped with tidy=TRUE, highlight=TRUE (so will Sweave, I think, if you set keep.source=FALSE).