Cannot read csv into R Markdown: Error in file(file, "rt") - r

I have been reading other questions on this topic (see read.table() and read.csv both Error in Rmd), but I believe I have set my working directory fine and the answers are not adequately answering my question...
Here is my code:
---
title: "WQ"
author: "A"
date: "October 13, 2017"
output:
html_document:
fig_height: 6
fig_width: 12
classoption: landscape
---
```{r}
setwd("C:/Users/K/Box/Projects/DRIP/3. Data/working/R_markdown")
x <- read.csv("Nash_longform_subset.csv",as.is=T)
y <- read.csv("Nash_longform.csv", as.is=T)
```{r}
All files and the R markdown file are in the same folder (set above in the code). The code itself runs perfectly, but will not export through R Markdown...
And I get the error:
x Line 14 Error in file(file, "rt"): cannot open the connection calls:
<Anonymous>... withVisible -> eval -> eval -> read.csv -> read.table -> file

The problem is that you are missing an slash in your wd so R doesn't find the document, that's what Error in file(file, “rt”) means. More explicitly is that R is looking for the first file in this path:
"C:/Users/K/Box/Projects/DRIP/3. Data/working/R_markdownNash_longform_subset.csv"
change your wd to:
setwd("C:/Users/K/Box/Projects/DRIP/3. Data/working/R_markdown/")

Related

Chunk option eval=FALSE ignored when spinning R-script

Spinning the following code (by clicking compile report in Rstudio):
#+ eval = FALSE
This line should not be syntax-checked, but it is.
Returns this error:
Error in parse(text = x, keep.source = TRUE) :
<text>:2:6: unexpected symbol
1: #+ eval = FALSE
2: This line
Knitting the equivalent Rmd-chunk works fine:
```{r, eval = FALSE}
Using Rmd, eval=FALSE disables the syntax-check, and does not error
I was expecting that I could spin a chunk syntactically incorrect code without getting an error (https://bookdown.org/yihui/rmarkdown-cookbook/spin.html). Am I mistaken for expecting this?
Thanks.
This is not possible, but a workaround is to quote the sentence :
# Syntax checked:
2+2
#> [1] 4
# Not syntax checked:
"
2 a
"
#> [1] "\n2 a \n"
(source: Yihui Xie's comment above at 28jun2022)

reticulate python engine - Use r as a name for Python object shared between multiple chunks

I am writing an R Markdown document using the Python engine of {reticulate}. I am quite happy with how it works.
The only thing is, I cannot use r as a Python object name that I'm going to use in multiple chunks.
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
r = 10
print(r) ##> 10
```
```{python}
print(r) ##> <__main__.R object at 0x119ad37d0>
```
I understand r is a good name when we use R objects from within a Python chunk. Since I know I am not going to do that in my project, I would like to use r as a name for my Python object.
Is there any way to change the name, r, for the R object created by reticulate? Or, to tell reticulate not to create r object?
I am aware of the two straightforward workarounds
Don't use r for Python objects.
Write everything in one big chunk and not share r between Python chunks.
but I'd like to have more freedom.
The object name r is special since it is used to communicate between R and python. The same holds for py in R:
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
foo = 10
print(foo) ##> 10
```
```{r}
library(reticulate)
py$foo ##> [1] 10
```
```{r}
foo <- 10
```
```{python}
print(foo) ##> 10
print(r.foo) ##> 10.0
```
Avoiding the use of r as an opject name is therefore the only good possibility I can see.
Still working on the details but I think setting source and output knit hooks may help. My dirty first try looks like this:
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
knitr::knit_hooks$set(
source = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
sprintf('<div class="%s"><pre class="knitr %s">%s</pre></div>\n', "source", tolower(options$engine), x)
},
output = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
paste0('<pre><code>', x, '</code></pre>\n')
}
)
```
```{python, rsub='rrr'}
rrr = 10
print(rrr)
```
```{python, rsub='rrr'}
print(rrr)
```

Why does a piece of R code does not work during Knit in Rmarkdown

When Knitting ans Rmarkdown (R Studio) document containing chunks of R code a chunck returns
line 192 Error in stats::hclust(dd, method=hc.method) :
must have n>= 2 objects to cluster Calls: <Anonymous> ... eval -> ggcorrplot -> .hc_cormat_order -> <Anonymous>
Same piece of code runs fine when run in R (R Studio) and runs from within markdown. This only happens during Knit!
Made no significant changes code in chunk is copy/paste from R-file. Added cache=FALSE and echo=FALSE. Didn't help.
Did put every line in separate chunk. This showed the error not to be at the library (dplyr) line but at the actual ggcorrplot line
library(dplyr)
dfNed_2b <- dfNed_2a %>% dplyr:: select(grep("GDP", names(dfNed_2a)), grep("GDY", names(dfNed_2a)), grep("GNP", names(dfNed_2a)))
dfNed_2b[is.na(dfNed_2b)] <- 0
corrNed_2b <- round(cor(dfNed_2b), 4)
library(ggcorrplot)
ggcorrplot(corrNed_2b, hc.order = TRUE,
type = "lower",
lab = TRUE,
lab_size = 2,
method="circle",
tl.cex=7,
colors = c("orangered1", "white", "darkolivegreen1"),
title="Correlogram GDP, GDY en GNP indicatoren",
ggtheme=theme_minimal)
From the R code I get a great Correlogram. The knit in Rmd returns:
line 192 Error in stats::hclust(dd, method=hc.method) :
must have n>= 2 objects to cluster Calls: <Anonymous> ... eval -> ggcorrplot -> .hc_cormat_order -> <Anonymous>
Error seem to refer back to first line in chunk while actual error is on the ggcorrplot line(s)
==================================================
Error still seems to persist. Changed Rmd to only use external R scripts
Rmd:
### Correlatie plot van de GDP, GDY en GNP indicatoren
{r cache=FALSE}
knitr::read_chunk('6e_corr_dfNed_2b.R')
```{r 6e_corr_dfNed_2b}
```
R:
## ---- 6e_corr_dfNed_2b
library(dplyr)
dfNed_2c <- dfNed_2b %>% dplyr::select(grep("GDP", names(dfNed_2b)),
grep("GDY", names(dfNed_2b)), grep("GNP", names(dfNed_2b)))
dfNed_2c[is.na(dfNed_2c)] <- 0
head(dfNed_2c,2)
library(ggplot2)
library(scales)
library(ggcorrplot)
corrNed_2c <- round(cor(dfNed_2c), 4)
ggcorrplot(corrNed_2c, hc.order = TRUE,
type = "lower",
lab = TRUE,
lab_size = 2,
method="circle",
tl.cex=7,
colors = c("orangered1", "white", "darkolivegreen1"),
title="Correlogram GDP, GDY en GNP indicatoren",
ggtheme=theme_minimal)
Only thing I can think of is that Knitr does like the library(dplyr) being used in aprevious chunk. Thought that was tackled by the cache=FALSE

rmarkdown error with ggplot and png

I have tried (in vain) to produce a chart with ggplot in Rmarkdown.
The code is the following:
```{r,echo=FALSE}
#fig.width=12,fig.height=6
panel2$PlotSize<-round(log(panel2$BSFA0200),0)- min(round(log(panel2$BSFA0200),0))+1# set size of dots
panel2$PlotSize[panel2$PlotSize==-Inf]<-NA
panel2$PlotColour<-ifelse(panel2$PlotSize<7,1,panel2$PlotSize)
panel2$PlotSize<-as.factor(panel2$PlotSize)
panel2$PlotColour<-as.factor(panel2$PlotColour)
g1<-ggplot(data=panel2,aes(x=NFR,y=PROF7*100,size=PlotSize,colour=PlotSize))+ geom_point()
g1
```
Out of knits this works fine, however when executed within a Rmd file (either as html or pdf) I always get this error message
processing file: 1Profti_model.Rmd
|.. | 4%
ordinary text without R code
|..... | 8%
label: setup (with options)
List of 1
$ include: logi FALSE
|........ | 12%
ordinary text without R code
|.......... | 15%
label: unnamed-chunk-1 (with options)
List of 3
$ echo : logi FALSE
$ warning: logi FALSE
$ message: logi FALSE
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
Loading required package: zoo
Attaching package: 'zoo'
The following objects are masked from 'package:base':
as.Date, as.Date.numeric
|............ | 19%
inline R code fragments
|............... | 23%
label: unnamed-chunk-2 (with options)
List of 1
$ echo: logi FALSE
|.................. | 27%
ordinary text without R code
|.................... | 31%
label: unnamed-chunk-3 (with options)
List of 1
$ echo: logi FALSE
Quitting from lines 98-109 (1Profti_model.Rmd)
Error in png(..., res = dpi, units = "in") : unable to start png() device
Calls: <Anonymous> ... in_dir -> plot2dev -> do.call -> <Anonymous> -> png
In addition: Warning messages:
1: Removed 55 rows containing missing values (geom_point).
2: In png(..., res = dpi, units = "in") :
unable to open file '1Profti_model_files/figure-html/unnamed-chunk-3-1.png' for writing
3: In png(..., res = dpi, units = "in") : opening device failed
Execution halted
I also tried to work around the problem by saving the chart in a png and load it as picture afterwards. Also no results (see Error with loading png in Rmd file)
Thanks for your help
UPDATE:
Following the suggestions from some of you guys I added a different chunk name and I replicated the code from Davit on my data (see updated code).
Unfortunately the error is still there. Interestingly, knitr cannot write a png but can write a csv in the same folder where the code is (I tested it).
Finally, i tested running this very same code onto my C drive and (surprise!) it works. However, this is for me not very efficient as I don't want to be dependent on a specific machine and I need to share this work with others (so network drive is a must). Moreover, all other package/code work fine in the network drive, only this png() seems to be an issue.
Thanks in advance for you help!
---
title: New Document
author: Me
output:
html_document
---
```{r prova,echo=FALSE, results='asis', message = FALSE, error = FALSE, warning= FALSE}
#.libPaths("D:/xxxx/packages")
require(ggplot2)
panel2 <- data.frame(BSFA0200 = rnorm(100),
NFR = rnorm(100),
PROF7 = rnorm(100))
panel2$PlotSize<-round(log(panel2$BSFA0200),0)- min(round(log(panel2$BSFA0200),0))+1# set size of dots
panel2$PlotSize[panel2$PlotSize==-Inf]<-NA
panel2$PlotColour<-ifelse(panel2$PlotSize<7,2,panel2$PlotSize)
write.csv(panel2[1:100,c('BSFA0200',"NFR","PROF7")],file="test.csv")
g1 <- ggplot(data = panel2,
aes(x = NFR,
y = PROF7 * 100,
size = factor(PlotSize),
colour = factor(PlotSize)
))
g1 + geom_point()
```
Error output:
Loading required package: ggplot2
Quitting from lines 9-32 (test.Rmd)
Error in png(..., res = dpi, units = "in") : unable to start png() device
Calls: <Anonymous> ... in_dir -> plot2dev -> do.call -> <Anonymous> -> png
In addition: Warning messages:
1: Removed 35 rows containing missing values (geom_point).
2: In png(..., res = dpi, units = "in") :
unable to open file 'test_files/figure-html/prova-1.png' for writing
3: In png(..., res = dpi, units = "in") : opening device failed
Execution halted
My knitr version is 1.11 (it should be the latest) and R version is 3.2.2
> R.Version()
$platform
[1] "i386-w64-mingw32"
$arch
[1] "i386"
$os
[1] "mingw32"
$system
[1] "i386, mingw32"
$status
[1] ""
$major
[1] "3"
$minor
[1] "2.2"
$year
[1] "2015"
$month
[1] "08"
$day
[1] "14"
$`svn rev`
[1] "69053"
$language
[1] "R"
$version.string
[1] "R version 3.2.2 (2015-08-14)"
$nickname
[1] "Fire Safety"
I got this message as well. The trouble with mine was that the file path was too long. I had my R markdown file in too many sub folders and the name of my R markdown file was too long. Once I reduced the length of the file path, the problem was resolved. I hope that works for you.
I had this same issue once. The code below works. You either had bad header or didn't call the packages: it's hard to tell since you did not provide that information. Also, please post example data next time.
Here is the full code that works (at least for me). If it doesn't run on your machine, post your data and full Rmd script and I'll try to help.
---
title: New Document
author: Me
output:
html_document
---
```{r,echo=FALSE, results='asis', message = FALSE, error = FALSE, warning= FALSE}
require(ggplot2)
panel2 <- data.frame(BSFA0200 = rnorm(100),
NFR = rnorm(100),
PROF7 = rnorm(100),
PlotSize = factor(rep(1:10, 10)),
PlotColour = factor(1:100))
g1 <- ggplot(data = panel2,
aes(x = NFR,
y = PROF7 * 100,
size = PlotSize,
colour = PlotSize))
g1 + geom_point()
```
I have also received this error; I solved it by moving the code to generate the offending figure into its own chunk.
I had a similar problem recently. And in my case, the issue was that antivirus software blocked Rscript.exe while it was trying to process files while knitting and PNG file was not created. So sometimes it is useful to temporarily disable antivirus and check if this solves the issue.
I have struggled with the same error. I understood it was something related to the path but couldn't solve it. Looking at the comments here, I tried closing the software and reopening it. It worked quickly. If this helps someone!

Resolving an error running Rmarkdown from the command line

I want to run Rmarkdown from the command line that will save an HTML output (I don't care if the command line shows me the plot as it's run or not, as long as the result is saved).
My Rmd script is something like:
---
title: "Report"
output: html_document
---
`r load("C:/Users/durlij/Desktop/Reports/.RData")`
## This is the Report as of `r format(Sys.Date(), format="%B %d %Y")`.
`r library(knitr)`
```{r error = FALSE, echo=FALSE, message=FALSE, warnings=FALSE, results='asis'}
kable(sumTable, format = "markdown")
```
### Visualization of data
`r library(ggplot2)
library(scales)
options(scipen = 999)`
```{r fig.width=8, fig.height=6, echo=FALSE}
ggplot()
```
```{r fig.width=8, fig.height=6, echo=FALSE}
ggplot()
```
In the command line I run
Rscript -e "library(knitr);require(methods);knit(C:/Users/durlij/Desktop/Reports/myFile.Rmd)"
It starts to run, completes the first in-line code chunk, but gets an error on the ggplot.
The error is:
Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
Calls: knit ... <Anonymous> -> png -> .handleSimpleError -> h -> cat -> file
In addition: Warning messages:
1: package 'scales' was built under R version 3.1.3
2: In png(..., res = dpi, units = "in") :
unable to open file 'figure/unnamed-chunk-2-1.png' for writing
3: In png(..., res = dpi, units = "in") : opening device failed
4: In file(file, ifelse(append, "a", "w")) :
cannot open file 'rmdRun.md': Permission denied
The whole command line echo is:
Warning message:
package 'knitr' was built under R version 3.1.3
Loading required package: methods
processing file: C:/Users/durlij/Desktop/Reports/myFile.Rmd
|..... | 8%
inline R code fragments
|.......... | 15%
label: unnamed-chunk-1 (with options)
List of 5
$ error : logi FALSE
$ echo : logi FALSE
$ message : logi FALSE
$ warnings: logi FALSE
$ results : chr "asis"
|............... | 23%
inline R code fragments
|.................... | 31%
label: unnamed-chunk-2 (with options)
List of 3
$ fig.width : num 8
$ fig.height: num 6
$ echo : logi FALSE
Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
Calls: knit ... <Anonymous> -> png -> .handleSimpleError -> h -> cat -> file
In addition: Warning messages:
1: package 'scales' was built under R version 3.1.3
2: In png(..., res = dpi, units = "in") :
unable to open file 'figure/unnamed-chunk-2-1.png' for writing
3: In png(..., res = dpi, units = "in") : opening device failed
4: In file(file, ifelse(append, "a", "w")) :
cannot open file 'rmdRun.md': Permission denied
Execution halted

Resources