Knitr error in loading in-built data - r

I am trying to run a code in R using knitr compiler. It for some reason generates this error:
Error in str(Oats) : object 'Oats' not found
Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> str
Execution halted
Here is the code I am using:
```{r}
data(Oats)
str(Oats)
plot(Oats)
sp.oats <- within(Oats, nitroF <- factor(nitro))
model1=lm(yield~Variety*nitro,data=Oats)
summary(model1)
model2=lme(yield~Variety*nitro,data=Oats,random=~1|Block/Variety/nitro)
summary(model2)
coef(model1)
coef(model2)
plot(ranef(model2))
plot(model2)
```
Please suggest what I should do to resolve this issue. Thanks!

I think you're looking for
data(Oats,package="nlme")
Quotation marks are optional around the data set name (Oats, "Oats") but mandatory for the package name ("nlme").
But
library(nlme)
data(Oats)
will also work, and since you're going to be using functions from nlme anyway, you might as well do it that way.

Adding comment as an answer. I thought it might be a duplicate (ansd still suspect it might be, but I couldn't find it in a search, so maybe it will be useful in subsequent searches.:
It is in the nlme-package which is not loaded by default, but it is shipped with every copy of R since its priority is "recommended". #MAPK should add a line that says data(Oats, pac=nlme) before he tries to access it, and hpesoj626 should try that at his console. Of course, that will then possibly lead to another error since the lme-function might not be there. So I think the final solution might be
```{r}
library(nlme)
data(Oats)`
....
as a starting point (inside the knitted section).

Related

Error in R Markdown: could not find function "split_chain"

Hello I am using R markdown and have ran into trouble.
When I try to knit this section of my document (the "example" variable is a data frame with a column called "text" which contains strings):
library(qdap)
frequent_terms <- freq_terms(example$text, 4)
frequent_terms
I get this error message:
Error in split_chain(match.callQ), env = env) :
could not find function "split_chain"
Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> %>%
I have updated Rstudio and the relevant packages(such as magrittr) but I am still running into this issue, one I have never encountered.
How do I fix this error, or how to I interpret the error message, I am at a loss here. Thank you.
According to this issue, your problem should be solved if you add qdap first, and magrittr / tidyverse afterward because gdap uses an old version of the pipe and masks the most recent magrittr version.
However, it is not entirely clear since we do not have a complete reproducible example

Knitr cannot find img files in /static/ folder

I have a hugo-academic website (methods101.com) that has been working well for last year.
I just went to edit some pages and I've started getting a new error.
The code that seems to be creating the problems is the knitr::include_graphics() function.
This is an example of the text that produces an error:
{r, echo=FALSE, out.width=600,
fig.cap="Newspaper article in Word document, next to same article on internet.",
fig.align='center'}
knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png")
This is the error message:
Rendering content/docs/SOC224_qual_analysis_eg.Rmd
Quitting from lines 80-81 (SOC224_qual_analysis_eg.Rmd)
Error in knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png") :
Cannot find the file(s): "/img/soc224_qual_analysis_eg_figure_1.png"
Calls: local ... withCallingHandlers -> withVisible -> eval -> eval -> <Anonymous>
Execution halted
<simpleError in render_page(f): Failed to render 'content/docs/SOC224_qual_analysis_eg.Rmd'>
I get the same problem on different computers, and after fresh re-installing/downloading the website contents.
The image file is definitely inside the folder:
/static/img/
You may see the help page ?knitr::include_graphics. In your case, you need
knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png", error = FALSE)
We managed to solve this problem by rolling back to the earlier version of Knitr.
This was the code we used:
remove.packages("knitr")
packageurl <- "https://cran.r-project.org/src/contrib/Archive/knitr/knitr_1.27.tar.gz"
install.packages(packageurl, repos=NULL, type="source")
We had no problems on 5th Feb, but noticed the new version of knitr came out on 6th Feb, and so thought this could be causing the problems.
We don't get the problems with the old version of knitr.
Not sure what the underlying cause is.

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.

Retrieving expected data.frame for testthat expectation

I'd like to test that a function returns the expected data.frame. The data.frame is too large to define in the R file (eg, using something like structure()). I'm doing something wrong with the environments when I try a simple retrieval from disk, like:
test_that("SO example for data.frame retreival", {
path_expected <- "./inst/test_data/project_longitudinal/expected/default.rds"
actual <- data.frame(a=1:5, b=6:10) #saveRDS(actual, file=path_expected)
expected <- readRDS(path_expected)
expect_equal(actual, expected, label="The returned data.frame should be correct")
})
The lines execute correctly when run in the console. But when I run devtools::test(), the following error occurs when the rds/data.frame is read from a file.
1. Error: All Records -Default ----------------------------------------------------------------
cannot open the connection
1: withCallingHandlers(eval(code, new_test_environment), error = capture_calls, message = function(c) invokeRestart("muffleMessage"),
warning = function(c) invokeRestart("muffleWarning"))
2: eval(code, new_test_environment)
3: eval(expr, envir, enclos)
4: readRDS(path_expected) at test-read_batch_longitudinal.R:59
5: gzfile(file, "rb")
To make this work, what adjustments are necessary to the environment? If there's not an easy way, what's a good way to test large data.frames?
I suggest you check out the excellent ensurer package. You can include these functions inside the function itself (rather than as part of the testthat test set).
It will throw an error if the dataframe (or whatever object you'd like to check) doesn't fulfill your requirements, and will just return the object if it passes your tests.
The difference with testthat is that ensurer is built to check your objects at runtime, which probably circumvents the entire environment problem you are facing, as the object is tested inside the function at runtime.
See the end of this vignette, to see how to test the dataframe against a template that you can make as detailed as you like. You'll also find many other tests you can run inside the function. It looks like this approach may be preferable over testthat in this case.
Based on the comment by #Gavin Simpson, the problem didn't involve environments, but instead the file path. Changing the snippet's second line worked.
path_qualified <- base::file.path(
devtools::inst(name="REDCapR"),
test_data/project_longitudinal/expected/dummy.rds"
)
The file's location is found whether I'm debugging interactively, or testthat is running (and thus whether inst is in the path or not).

KFAS package; error with documentation code

This is an example from the KFAS manual page 13. I just tried a copy/paste and this was the result. Any idea what the problem is?
There were additional errors with the rest of the example.
> require(KFAS)
Loading required package: KFAS
> data(GlobalTemp)
> model<-SSModel(GlobalTemp~SSMtrend(1,Q=NA,type= common ),H=matrix(NA,2,2))
Error in ts(x) : object is not a matrix
Did you copy the example by hand? The line in the manual (at least this one: http://cran.r-project.org/web/packages/KFAS/KFAS.pdf) uses this command:
require(KFAS)
data(GlobalTemp)
model<-SSModel(GlobalTemp~SSMtrend(1,Q=NA,type='common'),H=matrix(NA,2,2))
With the ' around common (and it works fs)
However you should have got the "common not found" error message, not the one you quote (except you already have an object named common in your environment), so I don't really know if this answer will help you.

Resources