R Markdown error in code when knit to HTML - r

I am trying to run code chunks in my markdown document. I have an R script that runs all the code that I need without any issues. Then, when I copy and paste the code into the markdown document, the code will run within the chunk, but will fail when trying to knit into an output document (html/pdf).
I had to create a safe.ifelse function to prevent r from converting my dates to a numeric format as discussed here.
The error appears to be with the code:
safe.ifelse = function(cond, yes, no){structure(ifelse(cond, yes, no), class = class(yes))
}
The error message I get is:
Line 121 Error in structure(ifelse(cond,yes,no), class = class(yes)) : could not find function "days" Calls: ... transform.data.frame ->eval->eval-> safe.ifelse-> structure Execution halted
The line of code following my safe.ifelse function is
seminoma1 = transform(seminoma1, recur.date = safe.ifelse(salvage.tx=="Yes",
date.diagnosis + days(pmax(time.rad, time.chemo, na.rm=TRUE)), NA))
Any help would be appreciated. Thanks.

I'm still too new to comment, but the only time I get an error like that is when I forget to define a function/variable or forget to source a package.
Since days() isn't part of R's base package, I think you need to add:
```{r echo = FALSE}
library("lubridate")
```

Related

Using base load in an active renvironment

I am working on an R markdown notebook in an active renv in my R project directory. Before I had activated the environment, I could use the load function from base R without a problem. But since activating the environment, I get errors when I use load(file=abc.RData).
I have a code chunk as follows:
rm(list=ls())
library(haven)
library(dplyr)
library(data.table)
# Load complete (individual+network) data ---------------------------
load(file="/Volumes/caas/CADRE CLC Data Project5/Clean Data/AK-SU-NETWORKS-ROUT/eda.RData")
If I try to run the chunk, I get the following error:
Error in load(file = "/Volumes/caas/CADRE CLC Data Project5/Clean Data/AK-SU-NETWORKS-ROUT/eda.RData") :
unused argument (file = "/Volumes/caas/CADRE CLC Data Project5/Clean Data/AK-SU-NETWORKS-ROUT/eda.RData")
But if I knit the document, it compiles without a problem.
What might I be doing wrong?
It looks like all I had to do was specify that I wanted to use load from base, as:
base::load(file="/Volumes/caas/CADRE CLC Data Project5/Clean Data/AK-SU-NETWORKS-ROUT/eda.RData")
That seems to have fixed it.

How to pass errors back to the Rmarkdown::render function?

I am trying to render an Rmarkdown file through an R script. (Code for both files below). What I would like to do is to pass information back to the render function depending on where the error is. This may be that the file can't read the input dataset. I would like to do this as I would like to run the script as a cron job and would like it to send me an email telling me why I might need to re run the code or what the error is.
I have read some of the other stackoverflow similar questions and couldn't see how it did what I wanted with some testing.
The r script: (I have attempted using something like the following)
rm(list = ls())
setwd("C:/Users/joel.kandiah/Downloads")
a <- print(try(rmarkdown::render("test.Rmd", quiet = T), TRUE))
#> [1] "C:/Users/joel.kandiah/Downloads/test.nb.html"
cat(eval(a))
#> C:/Users/joel.kandiah/Downloads/test.nb.html
The Rmarkdown document:
if(!exists("data_raw")) simpleError("Dataset has not been loaded")
#> <simpleError: Dataset has not been loaded>
What I would like is to see the simple error as an object in the R script. Something akin to an exit code might also be acceptable.
A possible approach, is the wrapping tryCatch around render in your R script.
R Script
# Render the markdown document; ####
tryCatch(
expr = rmarkdown::render(
"markdown.Rmd",
clean = TRUE
),
error = function(cond) {
message(cond)
},
warning = function(cond) {
message(cond)
}
)
R Markdown
# Force an error;
stop("You do not have permission to render. Admin password is needed.")
This will return the same error-message to your script.

Knitr Markdown - Sourced Script returns empty lists + ugly source file output

I'm trying on a simple knitr markdown "exercise". What I want to do is to simply source my R script file and output some of the data, e.g. the mean of a vector.
My code
```{r, echo = FALSE}
summary(cars)
source("GETPrices.R")
x <- BooliReq()
mean(x$sold$listPrice)
```
Firstly, the source ("GETPrices.R") generates an ugly
Attaching package: 'jsonlite'
The following object is masked from 'package:utils':
View
in the output file. How can this be prevented?
Secondly, when I e.g. try to output the mean value (see code above), all I get is
Warning in mean.default(x$sold$listPrice): argument is not numeric or
logical: returning NA
Outputting the mean in this way works fine though in console. So what is the issue?
For the first error, use the options:
{r, echo = FALSE, message=FALSE,warning=FALSE}

Knitting returns parse error

In attempting to knit a PDF. I'm calling a script that should return two ggplots by calling the chunk:
```{r, echo=FALSE}
read_chunk('Script.R')
```r
But receive the error
processing file: Preview-24a46368403c.Rmd
Quitting from lines 9-12 (Preview-24a46368403c.Rmd) Error in
parse(text = x, srcfile = src) : attempt to use zero-length
variable name Calls: <Anonymous> ... <Anonymous> -> parse_all ->
parse_all.character -> parse Execution halted
The script on its own runs and returns the two plots, but won't return them when knitted.
Similarly attempted to use source()
But got a similar error
Quitting from lines 7-10 (Preview-24a459ca4c1.Rmd) Error in
file(filename, "r", encoding = encoding) : cannot open the
connection Calls: <Anonymous> ... withCallingHandlers -> withVisible
-> eval -> eval -> source -> file Execution halted
While this does not appear to be a solution for you, this exact same error message appears if the chunk is not ended properly.
I experienced this error and traced it to ending chunk with `` instead of ```. Correcting the syntax of the chunk solved the problem I experienced with the same error message as you.
Are you sure that knitr is running from the directory you think it is? It appears that it is failing to find the file.
use an absolute path, if that fixes it, you've found your problem
once you've done that, you can use opts_knit$set(root.dir = "...") -- don't use setwd(.) if you want it (the cwd) to be maintained.
Knitr's default is the directory of the .Rmd file itself.
It may have to do with the "r" at the end of the triple backquotes demarcating your code chunk. There should be nothing after the triple backquotes, but I think the problem is specifically that the letter is "r".
The issue stems from the fact that R markdown processes backquoted statements starting with r as inline code, meaning it actually runs whatever is between the backquotes.
I had similar issues writing a problem set in an Rmd with this statement, which had backquoted text intended to be monospace but not run as inline code:
Use sapply or map to calculate the probability of a failure rate over r <- seq(.05, .5, .025).
When I knit the document, I got opaque error messages saying I had an improper assignment using <-. It was because instead of just displaying the backquoted statement in monospace, r <- seq(.05, .5, .025) was actually processed as R inline code of <- seq(.05, .5, .025)...thus the improper assignment error. I fixed my error by changing the variable name from r to rate.
The actual text of the error message in your question might refer to whatever follows your code chunk, as the knitting process is probably trying to run that as code. In this case, just removing that stray r at the end of the code chunk should fix the error.
You should use the following similar syntax, I had the same exact issue but got it fixed:
```{r views}
bank.df <- read.csv("C:/Users/User/Desktop/Banks.csv", header = TRUE) #load data
dim(bank.df) # to find dimension of data frame
head(bank.df) # show first six rows
```
the ``` has to be in the end of the line.
In my case was that I finished the code with four comas, not three . Check this and If you finished with four comas too, try to delete one of them.

Error in R. Error in gsub("(?<=\n)(?=.|\n)", continue, x, perl = TRUE) :

I am encountering an error in R that I cannot seem to figure out. I am creating an R markdown document where I read in an a csv table using this code.
iati <- read.csv(file="/filepath/IATI_NGOS.csv",head=TRUE,sep=",")
and then using ggplot2 I create a plot using the following code.
figure_one <- ggplot(iati, aes(iati$reporting.org))+
geom_bar(fill="blue")+
ylab("Total Activities")+
xlab("NGO Reporting Organizations in IATI")+
ggtitle("Total Number of Activities compared to each NGO Reporting Organization in IATI")+
coord_flip()
When I try to call figure_one in the R markdown I get the following error:
Quitting from lines 44-55 (NGO_IATI.Rmd)
Error in gsub("(?<=\n)(?=.|\n)", continue, x, perl = TRUE) :
input string 1 is invalid UTF-8
Calls: <Anonymous> ... paste -> comment_out -> line_prompt -> paste -> gsub
In addition: Warning message:
In grep("\n", message) : input string 1 is invalid in this locale
Execution halted
When I run this code in a regular R script I have absolutely no issues. I have search for some answers but can't figure it out.
Thanks!
I ended solving my issue by just doing a fresh install of R and Rstudio on my local machine. I think the recent update to Yosemite on my local environment created a lot of issues with the TeX plugin I had installed for R markdown.
I get the same question when I knit my rmarkdown document and find **encoding is the cause.
When you use functions like read.csv, fread or read_csv, you will read the column name.
If column names are in other languages, like Chinese, the problem will easily happen.
Or you rmarkdown works on Windows, but the encoding bug happens on Mac, a different environment.
The temporal solution is to rename the column name in English and resave the data files.
Here is the pseudocode in R to show my idea.
library(data.table)
library(tidyverse)
fread('yourfile.csv',encoding = 'UTF-8') %>%
purrr::set_names(c('x1','x2','x3')) %>%
write_excel_csv('yourfile_2.csv')
Here the new file yourfile_2.csv is fine to rmarkdown knit without encoding problems happening.

Resources