r,latex,knitr , How can I use values and charts in a knitr / LaTeX document before R has calculated them?

Question:

Tag: r,latex,knitr

A knitr document contains sections of R and LaTeX. My boss wants to read the summary (in LaTeX), but doesn't want to read the R. However the R should be available in an appendix, so the code can be checked if needs be (see below). How to I make values and charts available to LaTeX (for the boss), before they have been created by R in the appendix?

\documentclass[12pt, a4paper]{article}

\begin{document}
\title{For Bosses and R Experts}
\author{Joe Collins}
\maketitle

\section{For the Boss}
The average is 3.3.  Surely this should be calculated?

\appendix
\section{For The R Expert}
\subsection{Data}
<<data, echo=TRUE, results='markup'>>=
n = c(2, 3, 5)
s = c("One", "Two", "Three")
df = data.frame(n, s)
@

\subsection{Chart}
Show a chart.
<<chart, echo=TRUE, fig.height=3, fig.lp="chart">>=
barplot(df$n, names.arg=df$s)
@

\subsection{Statistics}
Calculate the mean.
<<statistics, echo=TRUE>>=
the.mean <- mean(df$n) @ The arithmetic mean is \Sexpr{the.mean}. \end{document}  I could reuse the chunk names like this (see below), but now all the R code is at the beginning of the document and separated from the surrounding discussion in the appendix. It is not an issue in this demo, but the actual document I am working on is huge. \documentclass{article} \begin{document} \title{For Bosses and R Experts} \author{Joe Collins} \maketitle <<data, echo=FALSE>>= n = c(2, 3, 5) s = c("One", "Two", "Three") df = data.frame(n, s) @ <<statistics, echo=FALSE>>= the.mean <- mean(df$n)
@

\section{For the Boss}
The average is \Sexpr{the.mean}.

\appendix
\section{For The R Expert}
\subsection{Data}
<<data, eval=FALSE>>=
@

\subsection{Chart}
Show a chart.
<<chart, echo=TRUE, fig.height=3, fig.lp="chart">>=
barplot(df$n, names.arg=df$s)
@

\subsection{Statistics}
Calculate the mean.
<<statistics, eval=FALSE>>=
@

The arithmetic mean is \Sexpr{the.mean}.
\end{document}


Reusing the chunks in a slightly different way (thanks @george-dontas) gets me what I want. The calculated values before the R and the R with its discussion in the appendix.

\documentclass{article}

\begin{document}
\title{For Bosses and R Experts}
\author{Joe Collins}
\maketitle

<<*, echo=FALSE, include=FALSE>>=
<<data>>
<<chart>>
<<statistics>>
@

\section{For the Boss}
The average is \Sexpr{the.mean}.

\appendix
\section{For The R Expert}

\subsection{Data}
<<data, echo=TRUE, results='markup'>>=
n = c(2, 3, 5)
s = c("One", "Two", "Three")
df = data.frame(n, s)
@

\subsection{Chart}
Show a chart.

<<chart, echo=TRUE, fig.height=3, fig.lp="chart">>=
barplot(df$n, names.arg=df$s)
@

\subsection{Statistics}
Calculate the mean.
<<statistics, echo=TRUE>>=

Replace -inf, NaN and NA values with zero in a dataset in R

r,time-series,nan,zoo
I am trying to run some trading strategies in R. I have downloaded some stock prices and calculated returns. The new return dataset has a number of -inf, NaN, and NA values. I am reproducing a row of the dataset (log_ret). Its a zoo dataset. library(zoo) log_ret <- structure( c(0.234,-0.012,-Inf,NaN,0.454,Inf),...

Fitting a subset model with just one lag, using R package FitAR

r,time-series
I am trying to fit a subset model with only lag 4. In the manual it's written "you must use p=c(0,0,0,4) since p=4 will fit a full AR(4)". I did this. #fit a subset model with just lag 4 Fit=FitAR(p=c(0,0,0,4), lag.max = "default", ARModel = "ARz") However, I get the...

Subtract time in r, forcing unit of results to minutes [duplicate]

r,posix,posixct
This question already has an answer here: Getting consist units from diff command in R 4 answers I successfully subtracted two POSIXct cols of df1 (below). However, since the time differences are >= 1 hour in all rows, R gives the results in hours. I know that this make...

Count number of rows meeting criteria in another table - R PRogramming

r
I have two tables, one with property listings and another one with contacts made for a property (i.e. is someone is interested in the property they will "contact" the owner). Sample "listings" table below: listings <- data.frame(id = c("6174", "2175", "9176", "4176", "9177"), city = c("A", "B", "B", "B" ,"A"),...

Store every value in a sequence except some values

r
If I do the following to a string of letters: x <- 'broke' y <- nchar(x) z <- sequence(y) How do I store every value of the z that isn't the first, last, or middle values of the sequence. In this example if z is 1 2 3 4 5...

Find multiple consecutive empty lines

r
I'm trying to chop up a text file into the articles it contains. Usually this is done by identifying a pattern each article begins with. Unfortunately the database I downloaded the articles from doesn't have that. The only pattern I can find is that after each article there are 3...

Limit the color variation in R using scale_color_grey

r,colors,ggplot2
Before I start, allow me to explain my graph: I have two Genotypes (WTB and whd) and each have two conditions (0 and 7), so I have four lines. Now, I want to make a plot where each variable and its condition is the same color. Anything with whd will...

How to split a text into two meaningful words in R

r,string-split,stemming,text-analysis

Subsetting rows by passing an argument to a function

r,subset
I have the following data frame which I imported into R using read.table() (I incorporated read.table() within read_data() which is a function I created that also throw messages in case the file name is not written appropriately): > raw_data <- read_data("n44.txt") [1] #### Reading txt file #### > head(raw_data) subject...

Appending a data frame with for if and else statements or how do put print in dataframe

r,loops,data.frame,append
How do I put what I printed in a dataframe with a for loop and if else statements? Basically, this code: list<-c("10","20","5") for (j in 1:3){ if (list[j] < 8) print("Greater") else print("Less") }) #[1] "Less" #[1] "Less" #[1] "Greater" Or should it be something more like this? f3 <-...

how to call Java method which returns any List from R Language? [on hold]

java,r,rjava
How to call java method which returns list from R Language.

copy a list of data.tables

r,data.table
I have the following situation: 1) a list of data tables 2) For testing purposes I deliberately want to (deeply) copy the whole list including the data tables 3) I want to take some element from the copied list and add a new column. Here is the code: library(data.table) x...

How to build a 'for' loop with input\$i in R Shiny

r,loops,for-loop,shiny
In my shiny app, I build a a number of checkboxes using a for loop, like this: landelist <- c("Danmark", "Tjekkiet", "Østrig", "Belgien", "Tyskland", "Sverige", "USA", "Norge", "Island") landecheckbox <- c() for (land in landelist){ landechek <- paste0("<label class=\"checkbox inline\"><input id=\"", land, "\" type=\"checkbox\" checked><span>", land, "</span></label>") landecheckbox <- c(landechek,...

ggplot2 & facet_wrap - eliminate vertical distance between facets

r,ggplot2
I'm working with some data that I want to display as a nxn grid of plots. Edit: To be more clear, there's 21 categories in my data. I want to facet by category, and have those 21 plots in a 5 x 5 square grid (where the orphan is by...

R — frequencies within a variable for repeating values

r,count,duplicates
I've got a column A, which has several values, some of them repeating. So, example: A = c(5, 9, 6, 5, 5). I need to go through A and count the frequencies of each of the values in A. So, for this example, for the set of 5s in A,...

optimization algorithm for circular data

r,optimization,circular,maximization
Background: I am interested in localizing a sound source from a suite of audio recorders. Each audio array consists of 6 directional microphones spaced evenly every 60 degrees (0, 60, 120, 180, 240, 300 degrees). I am interested in finding the neighboring pair of microphones with the maximum set of...

R: Using the “names” function on a dataset created within a loop

r,paste,assign,names
I am using a for loop to read in multiple csv files and naming the datasets import1, import2, etc. For example: assign(paste("import",i,sep=""), read.csv(files[i], header=FALSE)) However, I now want to rename the variables in each dataset. I have tried the following: names(as.name(paste("import",i,sep=""))) <- c("xxxx", "yyyy") But get the error "target of...