Caption Outside Float Error When Using Stargazer in R Markdown - r

I try to make a table of summary statistics using R Markdown. Below is my code.
{r new, echo=TRUE, results='asis'}
ws <- t(as.matrix(summary(merged$WS)))
ows <- t(as.matrix(summary(merged$OWS)))
summary1 <- rbind(ws, ows)
rownames(summary1) <- c("Win Shares", "Offensive Win Shares")
stargazer(summary1, title="A Few Summary Statistics on the Data")
When I compile, I get the following error:
! LaTeX Error: \caption outside float.
Error: LaTeX failed to compile stargazers_regressions.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See stargazers_regressions.log for more info.
Execution halted
I have looked up caption outside float in regards to stargazer and haven't seen anything. I have updated all of my packages and even restarted R.
Edit:
Here's a very simple example that still fails:
x <- c(-4, -5)
y <- c(-8, -10)
table_1 <- rbind(x, y)
stargazer(table_1)
It seems that stargazer has an issue with negative numbers. When I changed x to c(4, 5), and y to c(8, 10), the program compiles fine.

Related

R markdown code chunks run with "run current chunk" but not when I knit

I am trying to a read data file within my Rmd file.
It works fine when I use the green arrow to "run current chunk" and when I run selected lines. It does not run when I knit.
I tried chunk option include=TRUE and others that I could think of. Did not work.
I started a new Rmd file using the prettydocs template, and I put the code into an existing chunk in that template that was running and producing output. That code chunk is below. The last two lines are what I added, and they run fine when I select and run or when I run current chunk. When I knit, everything else in the chunk runs, but not those two lines.
The other change I made to the template file was to add: library(tidyverse) and library(readxl).
Here's the code:
```{r fig.width=6, fig.height=6, fig.align='center'}
set.seed(123)
n <- 1000
x1 <- matrix(rnorm(n), ncol = 2)
x2 <- matrix(rnorm(n, mean = 3, sd = 1.5), ncol = 2)
x <- rbind(x1, x2)
head(x)
smoothScatter(x, xlab = "x1", ylab = "x2")
test <- read_excel("test_data.xlsx")
getwd()
```

knitr: knitting chunks with parsing errors

Is it possible to knit chunks with parsing errors?
I want to produce a document explaining some different types of errors one can find while coding in R, but it seems that I can't knit a chunk with parsing error, even with error = TRUE.
For example, this chunk works fine and it shows the error messages:
```{r sum character, error = TRUE}
"1" + "2"
```
However, this chunk doesn't:
```{r missing parenthesis, error = TRUE}
f <- function(x){
z <- sum(x
#
y <- x + 1
return(x + y + z)
}
```
It gives the error: Error in parse(text = x, srcfile = src).
The idea here would be to show all error messages in the chunk "missing parenthesis", is this possible?
This has become possible since the evaluate package >= v0.8.4 (which is expected to be v0.9 on CRAN in the future). For now, you can install evaluate from Github.

Plotting with Knitr in Lyx

I'm trying to plot using Knitr in Lyx. When I run
<<>>=
install.packages("ggplot2")
library(ggplot2)
qplot(y=y, x=1:1000, main = 'Log-Likelihood')
#
I get the error
LaTeX Error: File `figure/unnamed-chunk-6.eps.bb' not found.
I've tried including extensions in the starting brackets, but with no success. How do I get my plot?
Following the first answer, tried this:
Defining function (not that important, just to show how I get y)
<<>>=
exp.loglik <- function(lambda, obs){
xbar = mean(obs)
return(length(obs)*log(lambda)-lambda*xbar)
}
#
Defining y (not that important, but just including to show how y is defined)
<<>>=
y = rep(NA,1000)
for (i in 1:1000){
y[i] = exp.loglik(lambda=i/10000, obs=diet_data$survtime)
}
#
Code that runs and then the error occurs (note that I installed the package in pure R as instructed)
<<warning=FALSE, message=FALSE, echo=FALSE>>=
library(ggplot2)
qplot(y=y, x=1:1000, main = 'Log-Likelihood')
#
Same ERROR: LaTeX Error: File `figure/unnamed-chunk-6.eps.bb' not found.
First, install packages separately, just running install.packages in pure R.
Second, you do not define y.
Here's a minimal example that produces a plot without showing R code, warnings or messages:
<<warning=FALSE, message=FALSE, echo=FALSE>>=
library(ggplot2)
qplot(y=10:1, x=1:10, main = 'Log-Likelihood')
#
Edit:
I am running the following code:
<<>>=
exp.loglik <- function(lambda, obs) {
xbar = mean(obs)
return(length(obs)*log(lambda)-lambda*xbar)
}
#
<<>>=
y = rep(NA,5)
for (i in 1:5) {
y[i] = exp.loglik(lambda=i/5, obs=runif(5))
}
#
<<warning=FALSE, message=FALSE>>=
library(ggplot2)
qplot(y=y, x=1:5, main = 'Log-Likelihood')
#
and I get a picture. Is your code working in clean R? Just re-run it to make sure it is. If everything is ok there, then it might be something with the LATEX/knitr installation.

Output of hints function from hints package in R

The following code has been taken from document of hints package. Last line of this code is throwing error.
library(hints)
m <- lm(BOD)
hints(m)
library(xtable)
xtable(hints(m))
The error is
Error in UseMethod("xtable") :
no applicable method for 'xtable' applied to an object of class "hints"
I wonder how to get hints function output to use in knitr or sweave document with xtable function.
It looks like xtable.hints is provided by the package but isn't properly exported so you can't actually use it. It's a fairly simple function though and the easiest solution would probably be to just copy the source and make your own function that does the exact same thing.
xtable.hints <- function(x, align = "llll", ...){
x <- as.data.frame(x$results[, c(2, 1, 3)])
colnames(x) <- c("Package", "Function", "Task")
xtable(x, align = align, ...)
}
x <- 1:10
y <- rnorm(10)
o <- lm(y~x)
xtable(hints(o)) # now it works

2 Knitr/R Markdown/Rstudio issues: Highcharts and Morris.js

I'm presently trying to replicate a few different types of rCharts using my own data. The first is a HighCharts graph with the following code:
````{r}
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8a.csv")`
require(slidify)
require(rCharts)
require(rHighcharts)
```
```{r}
x<-data.frame(blah,stringsAsFactors=TRUE)
colnames(x)<-substr(colnames(x),2,5)
a<-rHighcharts:::Chart$new()
a$chart(type="column")
a$title(text="Percent of Students on Grade Level on G8 FCAT for Reading (1), Math (2), Writing (3), and Science (4)")
a$xAxis(categories=rownames(x))
a$yAxis(title=list(text="Percent Proficient"))
a$data(x)
```
When this is run as a chunk, the graph is produced nicely, but when I use Knit HTML in markdown, it sticks at the preview stage for a while and when I terminate it, it gives a "status 15" message, which I'm unclear what that means and how it should be resolved.
A second graph I'm trying is a Morris.js graph in Markdown with knitr. I took my R code and put into R Markdown which looks like:
```{r}
library(slidify)
library(knitr)
library(rCharts)
library(RColorBrewer)
library(reshape2)
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8.csv")
blah
```
```{r}
m2<-mPlot(x="year",y=colnames(blah)[-1],data=blah, type="Bar")
m2$set(barColors=brewer.pal(4,"Spectral"))
m2$set(xlab="Year")
m2$set(postUnits="%")
m2$set(hideHover="auto")
m2
```
When I run the chunks, it produces a nice graph the way I expected with an html file of (file:///C:/Users/ypetscher/AppData/Local/Temp/RtmpW4q3ka/filed284f137718.html); however, when I click on Knit HTML, I obtain a file which includes the code, but doesn't produce the graph. Additionally, when Google Chrome comes up I receive an error of :
"No webpage was found for the web address:
file:///C:/Users/YPETSC~1/AppData/Local/Temp/Rtmpk1Pfbp/filee0c383670e0.html
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be
found."
Any help would be greatly appreciated in diagnosing these issues. Thank you much!
NOTE: This is the same solution I posted in the knitr google group.
To get rCharts to work with knit2html, you will need to use the print method with the argument include_assets = TRUE. This is because knitr will not add the js and css assets required by an rCharts plot automatically. Here is a minimal working example.
## MorrisJS with Knit2HTML
```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```
Note that you need to use m1$print('chart2', include_assets = TRUE, cdn = TRUE) if you intend to publish your chart on RPubs, for otherwise the JS and CSS assets will be served from your local library.
Hope this helps.

Resources