How to troubleshoot error with "sew" when knitting my rmarkdown file - r

Can't find generic `sew` in package knitr to register S3 method.
i This message is only shown to developers using devtools.
i Do you need to update knitr to the latest version?
I keep receiving the above error when I try to knit my rmarkdown file to html.
All I am doing is cleaning up my dataset with dplyr (select, mutate,etc.)
And generating cross tabs with the expss package
I am not using devtools. In fact, I didn't even have the package installed when the error appeared.
My code was knitting to html just fine. All I did was copy my code and change one variable (Race to Ethnicity), and then knit to HTML stopped working. It was working minutes before.
To fix this, I have tried:
knit to PDF (same error)
updating knitr and rmarkdown and expss
installing devtools and running library(devtools)
Closing out R and restarting my session
Clearing out my global environment and re-running everything
deleting the new code and running the original code that was working minutes before
None of these things worked! Any idea what could have happened with R markdown?
All I do is read in my excel sheet into "FullData"
And then I run this code
```{r, include = FALSE}
Racedata <- FullData %>%
select(Coder, Link, Chamber, SenateCommittee, SenateSubcommittee, HouseCommittee, HouseSubcommittee, Name, BillType, BillNumber, Race1, Race2) %>%
#Fix issues with Race columns
mutate(Race2 = na_if(Race2, "Other")) %>%
mutate(Race2 = na_if(Race2, "White"))
#Combine 2 Race columns into 1
Racedata$Race2 <- gsub("Unknown", "Audio Only", Racedata$Race2)
Newrace <- data.frame(Race = with(Racedata, replace(Race2, is.na(Race2), Race1[is.na(Race2)])))
Racedata$Race <- Newrace$Race
Racedata <- Racedata %>%
select(-c(Race1, Race2))
```
The code works just fine when I run it, but the error occurs when I try to knit to html.
This is the table that I want to produce with Knit to HTML:
```{r RACE CHARTS, echo = FALSE}
cross_cpct(Racedata, Race, list(total(), Chamber, HouseCommittee, SenateCommittee))
```

I figured it out! Stupid mistake
Two of my code blocks had the same name (facepalm)

Related

Unable to Import .Rdata to RMarkdown

I use Windows and try to read .Rdata file to RMarkdown using rio's import function. It keeps giving me errors. This works just fine when I'm using R code in the same folder.
So here is the code in the first RMarkdown code chunk
{r setup, include = FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(tidyverse)
library(rio)
df_clean <- import("data/df_clean.rdata")
Error in import("data/df_clean.rdata") : No such file
Is there a different between using R Code or RMarkdown? This also works fine when I type it in the R console, but doesn't work in the R Code chunk in the RMarkdown.
When I check in the working directory, the file is there
> getwd()
[1] "C:/Users/Project/Project A"
> list.files()
[1] "code" "data"
[3] "documentation" "output"
> list.files("data")
[1] "archive" "df_clean.rdata" "df_unique.rdata"
I'm new to R and just start coding this year. I hope I can do my EDA in RMarkdown to become more organized. Kindly help me with the question format if I did not posted it correctly.
if you unsure of the file path of the RData to import, use this to make Selection manually first..
df_clean <- import(file.choose())
or you can also get the full path of your RData stored in variable by doing:
RData_path <- file.choose()
df_clean <- import(RData_path)

Errors when using kable. Issues with phantomjs or ghostscript?

I am trying to create a table in R. I used mtcars as ax example dataset. I keep getting the error below. I am truly at a loss for how exactly to fix this and where to move certain files or programs to (ghostscript, magick, phantomjs..). Is there an easy fix? I am not using markdown.
kable(rawCSV, "latex", booktabs = T) %>%
kable_styling(latex_options = c("solid", "scale_down")) %>%
as_image()
save_kable(file="table.pdf")
Error in save_kable_latex(x, file, latex_header_includes, keep_tex, density) :
We hit an error when trying to use magick to read the generated PDF file. You may check your magick installation and try to use magick::image_read to read the PDF file manually. It's also possible that you didn't have ghostscript installed.

How to avoid a rmd file to execute the entire R script every time I knit it to pdf?

Here is the question:
In file.r I ran an extensive analysis based on a huge dataset.
Every time I open the file I just need to load the libraries and everything is ready.
I don't need to download anymore any of the dataset inputs I need.
Now I have created a RMD file.rmd with the same code of file.r to present its findings.
I'm trying to get a preview of how the pdf will look like.
The problem is that when I click "Knit to pdf", it starts to download all the packages and datasets again. I have to wait hours to see the effects of small changes in code.
And there is more:
Some objects created in R file simply are not working in the rmd file.
Ex: in R file I coded:
edx2 <- edx2 %>% mutate(timeRr = yearRating - release)
When I try to run the same code in the rmd file I get the message:
Error in Func(x[[i]],...) : object 'timeRr' not found calls: f -> scales_add_defaults - > lapply - > fun
The same libraries loaded in both files (r and rmd)
What am I doing wrong?
1) At the end of the data analysis (file.R), save the data you need for the Notebook in a .RDS file.
For example, if you generated 3 results : res1, res2 and res3
results <- list(res1 = res1, res2 = res2, res3 = res3)
saveRDS(file = 'results.RDS', results)
2) instead of sourcing the analysis script, just read the results in the Notebook (.Rmd)
data <- readRDS('results.RDS')
# Results available for further use in the Notebook
data$res1
data$res2
data$res3
The error you get with edx2 is probably due to the fact that a new session is opened during generation of a notebook : are you sure that file.R really generates edx2, or is it only available in your current session?

How to save a plot as image on disk from Viewer in RStudio?

Summary: my ultimate goal is to use rCharts, and specifically Highcharts, as part of a ReporteRs PowerPoint report automation workflow. One of the charts I would like to use is rendered as html in the Viewer pane in Rstudio, and addPlot(function() print(myChart)) does not add it to the PowerPoint. As a workaround, I decided to try to save myChart to disk, from where I could just add it to the PowerPoint that way.
So my question is really, How do I get my html image into my ReporteRs workflow? Either getting it saved to a disk, or getting it to be readable by ReporteRs would solve my problem.
This question is really the same as this one, but I'm using rCharts, specifically the example found here:
#if the packages are not already installed
install.packages('devtools')
require(devtools)
install_github('rCharts', 'ramnathv')
#code creates a radar chart using Highcharts
library(rCharts)
#create dummy dataframe with number ranging from 0 to 1
df<-data.frame(id=c("a","b","c","d","e"),val1=runif(5,0,1),val2=runif(5,0,1))
#muliply number by 100 to get percentage
df[,-1]<-df[,-1]*100
myChart <- Highcharts$new()
myChart$chart(polar = TRUE, type = "line",height=500)
myChart$xAxis(categories=df$id, tickmarkPlacement= 'on', lineWidth= 0)
myChart$yAxis(gridLineInterpolation= 'circle', lineWidth= 0, min= 0,max=100,endOnTick=T,tickInterval=10)
myChart$series(data = df[,"val1"],name = "Series 1", pointPlacement="on")
myChart$series(data = df[,"val2"],name = "Series 2", pointPlacement="on")
myChart
So if I try
> png(filename="~/Documents/name.png")
> plot(myChart)
Error in as.double(y) :
cannot coerce type 'S4' to vector of type 'double'
> dev.off()
I get that error.
I've looked into Highcharts documentation, as well as many other potential solutions that seem to rely on Javascript and phantomjs. If your answer relies on phantomjs, please assume I have no idea how to use it. webshot is another package I found which is even so kind as to include an install_phantomjs() function, but from what I could find, it requires you to turn your output into a Shiny object first.
My question is really a duplicate of this one, which is not a duplicate of this one because that is how to embed the html output in Rmarkdown, not save it as a file on the hard drive.
I also found this unanswered question which is also basically the same.
edit: as noted by #hrbrmstr and scores of others, radar charts are not always the best visualization tools. I find myself required to make one for this report.
The answer turned out to be in the webshot package. #hrbrmstr provided the following code, which would be run at the end of the code I posted in the question:
# If necessary
install.packages("webshot")
library(webshot)
install_phantomjs()
# Main code
myChart$save("/tmp/rcharts.html")
webshot::webshot("/tmp/rcharts.html", file="/tmp/out.png", delay=2)
This saves the plot to the folder as an html, and then takes a picture of it, which is saved as a png.
I can then run the ReporteRs workflow by using addImage(mydoc, "/tmp/out.png").

Difference between "Compile PDF" and knit2pdf

I have a .Rnw file that I am able to compile into a PDF using the "Compile PDF" button in RStudio (or Command+Shift+k). However, when I use knit2pdf the graphics are not created and the complete PDF is not created. Why would this happen? How do you specifically set where the images will be stored so that pdflatex can find them?
Here is an example. I am aware that this question that I posted a few days ago has a similar example, but in my mind these are two different questions.
This file will run just fine and produce a PDF if I hit "Compile". I don't get any errors, the figure is produced in the /figure directory, and all is well.
%test.Rnw
\documentclass{article}
\usepackage[margin=.5in, landscape]{geometry}
\begin{document}
This is some test text!
<<setup, include=FALSE, results='hide', cache=FALSE>>=
opts_chunk$set(echo=FALSE, warning = FALSE, message = FALSE,
cache = FALSE, error = FALSE)
library(ggplot2)
#
<<printplotscreen, results='asis'>>=
ggplot(diamonds) +
geom_bar(aes(x = color, stat = "bin"))
#
\end{document}
However, when I run this script that is intended to do exactly the same thing as hitting "Compile" (is it?) the figure is not created and I get the not-surprising error below about not being able to find it.
#test.R
library("knitr")
knit2pdf(input = "~/Desktop/thing/test.Rnw",
output=paste0('~/Desktop/thing/test','.tex'))
Error in texi2dvi(file = file, pdf = TRUE, clean = clean, quiet = quiet, :
Running 'texi2dvi' on 'test.tex' failed.
LaTeX errors:
! LaTeX Error: File `figure/printplotscreen-1' not found.
NOTE: If you are trying to reproduce this (and thanks!) then make sure you run the knit2pdf script FIRST to see that it doesn't create the figures. If you hit "Compile" first then the figures will be there for knit2pdf to use, but it will not accurately represent the situation.
The solution: Make sure to set the working directory to the project directory before using knit2pdf, then shorten the "input" path to just the .Rnw file. Thus...
test.R
library("knitr")
diamonds = diamonds[diamonds$cut != "Very Good",]
setwd("/Users/me/Desktop/thing")
knit2pdf(input = "test.Rnw", output = "test.tex")
Here are some references on this issue:
Changing working directory will impact the location of output #38
;
make sure the output dir is correct (#38)
It seems that when using knit2pdf(), it automatically set your output files to the directory where your input file in. And the author doesn't recommend us changing work-directory during the middle of a project.
So the current solution for me is to save the working directory as old one(getwd()), change the working directory to where you want to save the output files, use knit2pdf() to output files, and change the working directory to the original one finally.

Resources