I cannot show object in markdown document that are objects generated in different R script(within the same session). I would like to point out that I am newbie to markdown. So the code is as follows(''' are added before and after):
{r eval=TRUE, echo=FALSE}
head(output_by_size,10) # 1st line
summary(cars) # 2nd line
dim(iris) # 3rd line
when I comment line 2nd and 3rd the following error is generated:
Error in head(output_by_size, 10) : object 'output_by_size' not found
Calls: ... withCallingHandlers -> withVisible -> eval -> eval -> head
When 1st line is commented, lines 2nd and 3rd work as expected. Output_by_size is just simple data frame object. Could you please help me out?
There are 2 ways to load the data "output_by_size" to your .RMD file:
Don't knit your file with the Rstudio "knit" button, save your RMD file and then use the console:
library(knitr)
knit('your_file.Rmd')
This will take your recent environment into account and the error should be gone.
Store your "output_by_size" as "output_by_size.RData" and load it manually in your RMD file
```{r load myData, include=FALSE}
load("output_by_size.RData")
```
If you do it this way you can use the "knit" button from RStudio.
I hope one of this ways is a good solution for you.
Related
I included a check to install an R package if it's not already installed by the following syntax:
```{r setup-packages, results=FALSE, message=FALSE, warning=FALSE}
if(! require("readxl")) install.packages("readxl")
```
which returns this error:
processing file: Testing.Rmd
Error in parse_block(g[-1], g[1], params.src, markdown_mode) :
Duplicate chunk label 'setup-packages', which has been used for the chunk:
if(! require("readxl")) install.packages("readxl")
Calls: <Anonymous> ... process_file -> split_file -> lapply -> FUN -> parse_block
Execution halted
The knitting works if I change {r setup-packages, results=FALSE, message=FALSE, warning=FALSE} to {r}.
I want to reuse this chunk {r setup-packages, results=FALSE, message=FALSE, warning=FALSE} for each package but it only works once. Can someone explain or provide a solution to make it work with other packages?
knitr is erroring due to the reuse of a chunk name. Each chunk must be unnamed, as you found works with just {r}, or uniquely named.
You can fix it in any of these ways:
Put the lines for each of your package checks in a single chunk.
Rename each chunk to have a unique name, like setup-packages-readxl.
Set the option options(knitr.duplicate.label = "allow") in your Rprofile, though this is not a recommended use of this power according to the knitr documentation.
I am using rmarkdown to do 5 main steps: reading, cleaning, transformations, analysis and viz.
My plan is to divide the code for each step into one or two markdown files (.Rmd). Each following .Rmd will be called as an external file into the next .Rmd (i.e I want to nest my .Rmd of each step into the next one).
I am nesting the .Rmd files by replacing:
knitr::opts_chunk$set(echo = TRUE)
with:
knitr::knit("**ABSOLUTE PATH TO PREVIOUS .Rmd FILE**")
This worked, until my 3rd nesting, when I get an error at the knitr::knit line:
Error in file(file, "rt" ) Cannot open the connection calls: <Anonymous> … withVisible ->eval ->eval -> read.csv ->read.table -> file
NOTE: every time I have referenced anything this has been done with absolute paths, so this shouldn't be the issue.
Can anyone point me to the correct way of nesting .Rmd into eachother?
Finally, if this workflow seems savage, I would welcome any other suggestions on architecture! My reasons for the nesting (as opposed to putting everything in a big R Notebook are) are:
I want to work in .Rmd 'pages' to have separate tabs with less code I need to scroll through (and potentially mess up by accident).
I can pass data from one step to the other without losing time to write it somewhere on my disk.
(Basically I want to be able to evaluate and use the results from the previous .Rmd)
I can make a clean html or pdf page for every step of the process.
To combine multiple child Rmd files, I use a general Rmd one that call all childs. In that way, you can also decide not to show some of them with eval=FALSE directly in this main file.
More info on https://yihui.name/knitr/demo/child/
The main file would look like any Rmd:
---
title: Modelling distribution of species in the Bay of Biscay
author: "StatnMap - Sébastien Rochette"
date: '`r format(Sys.time(), "%d %B, %Y")`'
output:
html_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
<!-- Content -->
```{r reading, child='Reading.Rmd', eval=TRUE}
```
```{r cleaning, child='Cleaning.Rmd', eval=TRUE}
```
```{r analysis, child='Analysis.Rmd', eval=TRUE}
```
I am getting an error when I try to save a file in R Markdown using Knit
'Error in yaml::yaml.load(string, ...) :
Scanner error: while scanning for the next token at line 7, column 1found character that cannot start any token at line 7, column 1
Calls: ... parse_yaml_front_matter -> yaml_load_utf8 -> -> .Call
Execution halted'
Can you please how to fix this? I cant save anything at the moment
The YAML header had to look like this:
---
title: "Microarray analysis 2"
author: "Ania"
date: "3/9/2017"
output: html_document
---
You can implement your R code after this header. Note that your R code has to be implemented in this way:
```{r}
source("http://bioconductor.org/biocLite.R")
```
The way you tried will not work, because (1) the source command was not in an R-environment, (2) the URL http://bioconductor.org/biocLite.R [1] was not found.
```
I am trying to use RMarkdown (Knit) for the first time to produce pdf. The default file (File > New File > R Markdown) works well, it shows the generated pdf when compiled. For example, the following code runs,
```{r cars}
summary(cars)
```
However, if I just change cars with "myData," it does not compile and shows,
Error in object[[i]] : object of type 'closure' is not subsettable
Calls: <Anonymous> ... withVisible -> eval -> eval -> summary -> summary.default
Execution halted
I have "myData" loaded in the global-environment and can do other operations in original R script. Can someone please provide some guideline. Thank you very much for your time.
Running an Rmarkdown file starts a new R session.
Within the new session, you can load the data.frames that are stored in the data package, but other datasets must be loaded from within the Rmarkdown document.
To get myData to show up in your Rmarkdown document,
save the file somewhere with save in your current R session
then in your Rmarkdown document, use load to open up the data set
So, in your current R session:
save(myData, file="<path>/myData.Rdata")
and in your Rmarkdown file:
```{r myDataSummary}
load("<path>/myData.Rdata")
summary(myData)
```
If your data is stored as a text file, and you don't wish to store a separate .R file, use read.csv or friend directly within your Rmarkdown file.
```{r myDataSummary}
myData <- read.csv("<path>/myCSV.csv")
summary(myData)
```
This is the error you get when you try to subset (= via x[i]) a function. Since this error is caused by summary(cars) in your code, we may surmise that the cars object refers to a function in the scope in which the document is knit.
You probably forgot to load your data, or you have a function with the same name defined in the current scope.
As #Imo explained, the basic problem is the new session. So, the answer would be adding the script in the rMarkdown. However, it will create few more hiccups. Here is how I handled few of them,
```{r global_options, include=FALSE}
source(file = "C:\\Path\\to\\my\\file.R")
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/',
echo=FALSE, warning=FALSE, message=FALSE)
```
I'd like to pull child documents from github to knit as child items inside an rmarkdown document.
Using yihui's example from allowing child markdown files we can have a main doc (modified) that refers to the child doc on github instead of downloading it first.
I've resolved a Windows compatibility issue, and am now getting a setwd() fail.
How do you correctly setup a knitr document to knit child items from a URL? (if possible)
Initial (on windows)
You can also use the `child` option to include child documents in markdown.
```{r test-main, child='https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd'}
```
You can continue your main document below, of course.
```{r test-another}
pmax(1:10, 5)
```
Error output
## Quitting from lines 4-4 (https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd)
## Error in readLines(if (is.character(input2)) { :
## cannot open the connection
## Calls: <Anonymous> ... process_group.block -> call_block -> lapply -> FUN -> knit -> readLines
## In addition: Warning message:
## In readLines(if (is.character(input2)) { : unsupported URL scheme
## Execution halted
This was erroring because the readLines command was unable to access HTTPS by default when working on Windows.
v2 (on windows)
To correct for the readLines issue I added a chunk that adds the ability to access HTTPS
You can also use the `child` option to include child documents in markdown.
```{r setup, results='hide'}
setInternet2(use = TRUE)
```
```{r test-main, child='https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd'}
```
You can continue your main document below, of course.
```{r test-another}
pmax(1:10, 5)
```
Error output
## processing file: https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd
## Quitting from lines 2-2 (https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd)
## Quitting from lines NA-7 (https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd)
## Error in setwd(dir) : cannot change working directory
## Calls: <Anonymous> ... process_group.inline -> call_inline -> in_dir -> setwd
## Execution halted
Trying to add in a setwd("~") into chunk setup has no impact on the error message
I don't think you can do this because as I understand it, there is a directory change (to the child document's directory) during knitting. Because your child document is not a local file, the implicit setwd will fail.
A solution would be to add a hidden chunk that downloads the github file to a temporary directory and then deletes the downloaded file. Something like:
```{r setup, echo=FALSE, results='hide'}
setInternet2(use = TRUE)
x <- tempfile(fileext = "Rmd")
on.exit(unlink(x))
download.file("https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd", x)
```
```{r test-main, child=x}
```
You can continue your main document below, of course.
```{r test-another}
pmax(1:10, 5)
```
If the child is only markdown (no R code to process), then this may work for you.
```{r footer, echo=FALSE, results='asis'}
url <- "https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd"
childtext <- readLines(url)
cat(childtext, sep="\n")
```